title
stringlengths 3
221
| text
stringlengths 17
477k
| parsed
listlengths 0
3.17k
|
---|---|---|
What are Python coding standards/best practices? | You can use the PEP8 guide as a holy grail. Almost all python world uses this guide to write clean understandable and standard python code. This is available as an extension as a linter for all modern text editors. You can check it out at http://www.python.org/dev/peps/pep-0008/
Properly Structure your folders. All projects need proper structuring. This helps organize code better. Python has an opinionated folder structure that you should use.
README.rst
LICENSE
setup.py
requirements.txt
sample/__init__.py
sample/core.py
sample/helpers.py
docs/conf.py
docs/index.rst
tests/test_basic.py
tests/test_advanced.py
Use doctests. The doctest module searches for pieces of text that look like interactive Python sessions, and then executes those sessions to verify that they work exactly as shown. This is one of the best and most useful peices of the language and you should use it to the max. This allows doing TDD.
Use PyPi to get all your modules. PyPi is a central repository of python modules. Instead of building your own packages, use pip to install modules off of Pypi.
Write Pythonic code by adhering to python idioms. This takes some getting used to but can help you go a long way. You can read more about idiomatic python onhttp://python.net/~goodger/projects/pycon/2007/idiomatic/handout.html | [
{
"code": null,
"e": 1343,
"s": 1062,
"text": "You can use the PEP8 guide as a holy grail. Almost all python world uses this guide to write clean understandable and standard python code. This is available as an extension as a linter for all modern text editors. You can check it out at http://www.python.org/dev/peps/pep-0008/"
},
{
"code": null,
"e": 1511,
"s": 1343,
"text": "Properly Structure your folders. All projects need proper structuring. This helps organize code better. Python has an opinionated folder structure that you should use."
},
{
"code": null,
"e": 1679,
"s": 1511,
"text": "README.rst\nLICENSE\nsetup.py\nrequirements.txt\nsample/__init__.py\nsample/core.py\nsample/helpers.py\ndocs/conf.py\ndocs/index.rst\ntests/test_basic.py\ntests/test_advanced.py"
},
{
"code": null,
"e": 1980,
"s": 1679,
"text": "Use doctests. The doctest module searches for pieces of text that look like interactive Python sessions, and then executes those sessions to verify that they work exactly as shown. This is one of the best and most useful peices of the language and you should use it to the max. This allows doing TDD."
},
{
"code": null,
"e": 2141,
"s": 1980,
"text": "Use PyPi to get all your modules. PyPi is a central repository of python modules. Instead of building your own packages, use pip to install modules off of Pypi."
},
{
"code": null,
"e": 2368,
"s": 2141,
"text": "Write Pythonic code by adhering to python idioms. This takes some getting used to but can help you go a long way. You can read more about idiomatic python onhttp://python.net/~goodger/projects/pycon/2007/idiomatic/handout.html"
}
] |
Predicting vehicle fuel efficiency | by Ranganath Venkataraman | Towards Data Science | My previous posts focused on the application of machine learning and neural networks in datasets from the oil industry. These efforts gave me the confidence to successfully implement XGBoost and artificial neural networks to predict a major safety hazard at the oil refinery where I work. A major success that I’m very proud of!
In order to exercise some versatility, I wanted to use PyTorch and GridSearchCV in this application and first wanted to practice on a simpler and smaller dataset — namely the Auto MPG dataset from the UCI repository.
As before, I’m laying out a step-wise approach to assure systematic application:
Step 1 = Understand the goal and big picture before diving into modeling.
Step 2 = load and get high-level insight into data
Step 3 = further visualization to explore the data. Goal: get an early inkling of the most leveraging features.
Step 4 = plan for modeling. The key here is to get data ready for training and testing models.
Step 5 = execute modeling and evaluate performance. Complete sensitivity analysis as desired
Step 6 = draw conclusions from work to benefit the end-user
Snippets of code are below with full code in GitHub repo.
Step 1: our goal is to predict mileage for cars based on various characteristics. Through the modeling effort, we can understand what makes a car efficient and how to achieve target mileage consumption.
Step 2: reading the input data into Python and using .describe(), .head() functions to get the key statistics and a first look at the data. I also want to name the columns, since this wasn’t available in the raw data.
High-level takeaways:
The dataset has variables covering a wide range of numbers; if we use algorithms like kNN, this suggests the need for scaling.
Seems that we have a mix of continuous and discrete variables, one of which is non-numeric. This suggests the need for some kind of encoding.
There are 398 entries with average mileage of 23 mpg, 3 possible origins, 5 possible model years.
A separate check — not shown here — shows that the dataset has 6 empty values for the ‘horsepower’ feature.
Step 3a) plotting correlations as a Seaborn heatmap
Conclusions to draw from above?
Car weight and displacement have the strongest inverse correlation with mileage. Lines up well with intuition that the big Hummer isn’t the most efficient user of gasoline
Horsepower and number of cylinders are also strongly inversely correlated with mileage — again lines up well with the intuition that a fast sports car needs more gasoline than a sedan
Car origin and model year are categorical numerical variables — let’s visualize these using barplots.
For modeling purposes, I’ll first use all these features. However, I could drop either cylinders/displacement/car weight (given high correlation coefficients) if I wanted a more compact set of features to prevent any potential overfitting.
Step 3b) Let’s use barplots to learn more about the categorical numerical features:
Conclusions to draw from Figure 3 histograms: cars in origin 1 are far more represented, suggesting that mpg results are better suited to that origin — whatever origin may stand for e.g. country of manufacture. We notice that model years are distributed over 12 years, with 1970, 1976, 1982 more represented than others.
Should these numerical categorical variables be encoded?
Conclusions from Figure 4 barplots: there is marginal increase in mpg with car origin number. The correlation is less so, for model year, but for now, I won’t encode these variables. I’m fine with leaving these features in as-is.
Step 3c) The analysis above got me curious about the dependent variable i.e. the target i.e. what we’re trying to predict. Is that skewed in any direction? Figure 4 below shows right-skewness of the feature, suggesting that we might want to do a log transform of the feature data for use in modeling.
Step 4: in addition to doing some more data preparation and creating test/ train sets for modeling, I’ll also set up GridSearch CV
4a) imputing missing data and creating training and testing sets. Also encoding car make, dropping car model — since the latter is extraneous detail.
# The code below one-hot encodes car make and drops car model.Data['car make'] = Data['car name'] Data['car make'] = Data['car name'].apply(lambda x: x.split()[0])Data.drop(columns=['car name'],inplace=True)Data = pd.get_dummies(Data,columns=['car make'])# Next: creating x and y belowx_no_log = Data.drop(columns=['mpg'])y_no_log = Data['mpg']# Imputing missing car horsepower values.imp = SimpleImputer(missing_values=np.nan,strategy='median')x_no_log['horsepower'] = imp.fit(x_no_log['horsepower'].values.reshape(-1, 1)).transform(x_no_log['horsepower'].values.reshape(-1, 1))
4b) setting up GridSearchCV — this allows us to loop through hyperparameters to find the optimal combination per the selected scoring metric (mean square error in my case). The GitHub repo has the similar exercise for RandomForest.
xgb_params = {'nthread':[4], 'learning_rate': [.03, 0.05, .07], 'max_depth': [5, 6, 7], 'min_child_weight': [4], 'subsample': [0.7], 'colsample_bytree': [0.7], 'n_estimators': [500,1000]}
4c) setting up PyTorch — the code below imports the necessary packages, sets up the neural network with input dimensions, number of nodes in hidden layer, and output node, and then builds the model.
I’m also declaring mean squared error as the loss metric to optimize, same metric that I’ll use when evaluating XGBoost and RandomForest’s performance on test set.
Finally, setup the Adam optimization algorithm for maneuvering the gradient descent function as seen in Figure 6 below.
5) With all setup complete, time to actually run the models and evaluate results.
5a) I’ll first use GridCV and the previously setup hyperparameter grid to find the best performing XGBoost model (similar exercise for RandomForest is in GitHub repo) based on performance in the training set.
5b) I’ll then train the created PyTorch neural network
gsXGB = GridSearchCV(xgbr, xgb_params, cv = 7, scoring='neg_mean_squared_error', refit=True, n_jobs = 5, verbose=True)gsXGB.fit(xtrain,ytrain)XGB_best = gsXGB.best_estimator_train_error = []iters = 600Y_train_t = torch.FloatTensor(ytrain.values).reshape(-1,1) #Converting numpy array to torch tensorfor i in range(iters): X_train_t = torch.FloatTensor(xtrain.values) #Converting numpy array to torch tensor y_hat = torch_model(X_train_t) loss = loss_func(y_hat, Y_train_t) loss.backward() optimizer.step() optimizer.zero_grad()
5c) With model training complete, I can now evaluate performance on testing data.
# Evaluating best-performing XGBoost model on testing dataypred = XGB_best.predict(xtest)explained_variance_score(ytest,ypred)mean_absolute_error(ytest,ypred)mean_squared_error(ytest,ypred,squared=True)# Evaluating PyTorch model on testing dataX_test_t = torch.FloatTensor(xtest.values) #Converting numpy array to Torch Tensor.ypredict = torch_model(X_test_t)mean_squared_error(ytest,ypredict.detach().numpy(),squared=True)
Mean Squared Error of the XGBoost model arrived at through hyperparameter tuning is 0.0117 mpg. Given a mean of 23.5 mpg in original dataset, this can be interpreted as accuracy of 99.9%
Mean Squared Error of PyTorch neural network is 0.107 mpg. Using the approach above, this can be translated to an accuracy of 99.5%.
6) What have we accomplished for our client? We have a model that predicts fuel mileage for a variety of cars; our client can use this to plan for cars that achieve desired levels of fuel efficiency.
Additionally we can also inform our client that — per Figure 7 below — weight is the most influential variable in predicting mileage, with acceleration being second most. Horsepower, displacement, and acceleration are relatively close to each other in impact.
With this detail, our client can plan future car production or purchase plans.
As always, I welcome any feedback. | [
{
"code": null,
"e": 500,
"s": 171,
"text": "My previous posts focused on the application of machine learning and neural networks in datasets from the oil industry. These efforts gave me the confidence to successfully implement XGBoost and artificial neural networks to predict a major safety hazard at the oil refinery where I work. A major success that I’m very proud of!"
},
{
"code": null,
"e": 717,
"s": 500,
"text": "In order to exercise some versatility, I wanted to use PyTorch and GridSearchCV in this application and first wanted to practice on a simpler and smaller dataset — namely the Auto MPG dataset from the UCI repository."
},
{
"code": null,
"e": 798,
"s": 717,
"text": "As before, I’m laying out a step-wise approach to assure systematic application:"
},
{
"code": null,
"e": 872,
"s": 798,
"text": "Step 1 = Understand the goal and big picture before diving into modeling."
},
{
"code": null,
"e": 923,
"s": 872,
"text": "Step 2 = load and get high-level insight into data"
},
{
"code": null,
"e": 1035,
"s": 923,
"text": "Step 3 = further visualization to explore the data. Goal: get an early inkling of the most leveraging features."
},
{
"code": null,
"e": 1130,
"s": 1035,
"text": "Step 4 = plan for modeling. The key here is to get data ready for training and testing models."
},
{
"code": null,
"e": 1223,
"s": 1130,
"text": "Step 5 = execute modeling and evaluate performance. Complete sensitivity analysis as desired"
},
{
"code": null,
"e": 1283,
"s": 1223,
"text": "Step 6 = draw conclusions from work to benefit the end-user"
},
{
"code": null,
"e": 1341,
"s": 1283,
"text": "Snippets of code are below with full code in GitHub repo."
},
{
"code": null,
"e": 1544,
"s": 1341,
"text": "Step 1: our goal is to predict mileage for cars based on various characteristics. Through the modeling effort, we can understand what makes a car efficient and how to achieve target mileage consumption."
},
{
"code": null,
"e": 1762,
"s": 1544,
"text": "Step 2: reading the input data into Python and using .describe(), .head() functions to get the key statistics and a first look at the data. I also want to name the columns, since this wasn’t available in the raw data."
},
{
"code": null,
"e": 1784,
"s": 1762,
"text": "High-level takeaways:"
},
{
"code": null,
"e": 1911,
"s": 1784,
"text": "The dataset has variables covering a wide range of numbers; if we use algorithms like kNN, this suggests the need for scaling."
},
{
"code": null,
"e": 2053,
"s": 1911,
"text": "Seems that we have a mix of continuous and discrete variables, one of which is non-numeric. This suggests the need for some kind of encoding."
},
{
"code": null,
"e": 2151,
"s": 2053,
"text": "There are 398 entries with average mileage of 23 mpg, 3 possible origins, 5 possible model years."
},
{
"code": null,
"e": 2259,
"s": 2151,
"text": "A separate check — not shown here — shows that the dataset has 6 empty values for the ‘horsepower’ feature."
},
{
"code": null,
"e": 2311,
"s": 2259,
"text": "Step 3a) plotting correlations as a Seaborn heatmap"
},
{
"code": null,
"e": 2343,
"s": 2311,
"text": "Conclusions to draw from above?"
},
{
"code": null,
"e": 2515,
"s": 2343,
"text": "Car weight and displacement have the strongest inverse correlation with mileage. Lines up well with intuition that the big Hummer isn’t the most efficient user of gasoline"
},
{
"code": null,
"e": 2699,
"s": 2515,
"text": "Horsepower and number of cylinders are also strongly inversely correlated with mileage — again lines up well with the intuition that a fast sports car needs more gasoline than a sedan"
},
{
"code": null,
"e": 2801,
"s": 2699,
"text": "Car origin and model year are categorical numerical variables — let’s visualize these using barplots."
},
{
"code": null,
"e": 3041,
"s": 2801,
"text": "For modeling purposes, I’ll first use all these features. However, I could drop either cylinders/displacement/car weight (given high correlation coefficients) if I wanted a more compact set of features to prevent any potential overfitting."
},
{
"code": null,
"e": 3125,
"s": 3041,
"text": "Step 3b) Let’s use barplots to learn more about the categorical numerical features:"
},
{
"code": null,
"e": 3446,
"s": 3125,
"text": "Conclusions to draw from Figure 3 histograms: cars in origin 1 are far more represented, suggesting that mpg results are better suited to that origin — whatever origin may stand for e.g. country of manufacture. We notice that model years are distributed over 12 years, with 1970, 1976, 1982 more represented than others."
},
{
"code": null,
"e": 3503,
"s": 3446,
"text": "Should these numerical categorical variables be encoded?"
},
{
"code": null,
"e": 3733,
"s": 3503,
"text": "Conclusions from Figure 4 barplots: there is marginal increase in mpg with car origin number. The correlation is less so, for model year, but for now, I won’t encode these variables. I’m fine with leaving these features in as-is."
},
{
"code": null,
"e": 4034,
"s": 3733,
"text": "Step 3c) The analysis above got me curious about the dependent variable i.e. the target i.e. what we’re trying to predict. Is that skewed in any direction? Figure 4 below shows right-skewness of the feature, suggesting that we might want to do a log transform of the feature data for use in modeling."
},
{
"code": null,
"e": 4165,
"s": 4034,
"text": "Step 4: in addition to doing some more data preparation and creating test/ train sets for modeling, I’ll also set up GridSearch CV"
},
{
"code": null,
"e": 4315,
"s": 4165,
"text": "4a) imputing missing data and creating training and testing sets. Also encoding car make, dropping car model — since the latter is extraneous detail."
},
{
"code": null,
"e": 4895,
"s": 4315,
"text": "# The code below one-hot encodes car make and drops car model.Data['car make'] = Data['car name'] Data['car make'] = Data['car name'].apply(lambda x: x.split()[0])Data.drop(columns=['car name'],inplace=True)Data = pd.get_dummies(Data,columns=['car make'])# Next: creating x and y belowx_no_log = Data.drop(columns=['mpg'])y_no_log = Data['mpg']# Imputing missing car horsepower values.imp = SimpleImputer(missing_values=np.nan,strategy='median')x_no_log['horsepower'] = imp.fit(x_no_log['horsepower'].values.reshape(-1, 1)).transform(x_no_log['horsepower'].values.reshape(-1, 1))"
},
{
"code": null,
"e": 5127,
"s": 4895,
"text": "4b) setting up GridSearchCV — this allows us to loop through hyperparameters to find the optimal combination per the selected scoring metric (mean square error in my case). The GitHub repo has the similar exercise for RandomForest."
},
{
"code": null,
"e": 5395,
"s": 5127,
"text": "xgb_params = {'nthread':[4], 'learning_rate': [.03, 0.05, .07], 'max_depth': [5, 6, 7], 'min_child_weight': [4], 'subsample': [0.7], 'colsample_bytree': [0.7], 'n_estimators': [500,1000]}"
},
{
"code": null,
"e": 5594,
"s": 5395,
"text": "4c) setting up PyTorch — the code below imports the necessary packages, sets up the neural network with input dimensions, number of nodes in hidden layer, and output node, and then builds the model."
},
{
"code": null,
"e": 5758,
"s": 5594,
"text": "I’m also declaring mean squared error as the loss metric to optimize, same metric that I’ll use when evaluating XGBoost and RandomForest’s performance on test set."
},
{
"code": null,
"e": 5878,
"s": 5758,
"text": "Finally, setup the Adam optimization algorithm for maneuvering the gradient descent function as seen in Figure 6 below."
},
{
"code": null,
"e": 5960,
"s": 5878,
"text": "5) With all setup complete, time to actually run the models and evaluate results."
},
{
"code": null,
"e": 6169,
"s": 5960,
"text": "5a) I’ll first use GridCV and the previously setup hyperparameter grid to find the best performing XGBoost model (similar exercise for RandomForest is in GitHub repo) based on performance in the training set."
},
{
"code": null,
"e": 6224,
"s": 6169,
"text": "5b) I’ll then train the created PyTorch neural network"
},
{
"code": null,
"e": 6792,
"s": 6224,
"text": "gsXGB = GridSearchCV(xgbr, xgb_params, cv = 7, scoring='neg_mean_squared_error', refit=True, n_jobs = 5, verbose=True)gsXGB.fit(xtrain,ytrain)XGB_best = gsXGB.best_estimator_train_error = []iters = 600Y_train_t = torch.FloatTensor(ytrain.values).reshape(-1,1) #Converting numpy array to torch tensorfor i in range(iters): X_train_t = torch.FloatTensor(xtrain.values) #Converting numpy array to torch tensor y_hat = torch_model(X_train_t) loss = loss_func(y_hat, Y_train_t) loss.backward() optimizer.step() optimizer.zero_grad()"
},
{
"code": null,
"e": 6874,
"s": 6792,
"text": "5c) With model training complete, I can now evaluate performance on testing data."
},
{
"code": null,
"e": 7298,
"s": 6874,
"text": "# Evaluating best-performing XGBoost model on testing dataypred = XGB_best.predict(xtest)explained_variance_score(ytest,ypred)mean_absolute_error(ytest,ypred)mean_squared_error(ytest,ypred,squared=True)# Evaluating PyTorch model on testing dataX_test_t = torch.FloatTensor(xtest.values) #Converting numpy array to Torch Tensor.ypredict = torch_model(X_test_t)mean_squared_error(ytest,ypredict.detach().numpy(),squared=True)"
},
{
"code": null,
"e": 7485,
"s": 7298,
"text": "Mean Squared Error of the XGBoost model arrived at through hyperparameter tuning is 0.0117 mpg. Given a mean of 23.5 mpg in original dataset, this can be interpreted as accuracy of 99.9%"
},
{
"code": null,
"e": 7618,
"s": 7485,
"text": "Mean Squared Error of PyTorch neural network is 0.107 mpg. Using the approach above, this can be translated to an accuracy of 99.5%."
},
{
"code": null,
"e": 7818,
"s": 7618,
"text": "6) What have we accomplished for our client? We have a model that predicts fuel mileage for a variety of cars; our client can use this to plan for cars that achieve desired levels of fuel efficiency."
},
{
"code": null,
"e": 8078,
"s": 7818,
"text": "Additionally we can also inform our client that — per Figure 7 below — weight is the most influential variable in predicting mileage, with acceleration being second most. Horsepower, displacement, and acceleration are relatively close to each other in impact."
},
{
"code": null,
"e": 8157,
"s": 8078,
"text": "With this detail, our client can plan future car production or purchase plans."
}
] |
Install and run multiple Java versions on Linux and MacOS | by Md Kamaruzzaman | Towards Data Science | If you are a Java developer, you may need to install multiple Java versions on your machine. You may use Java8 or Java11 in your project, but want to learn newer versions of Java. Or maybe you are working on two different projects where two different versions of Java are used.
One way to achieve this is to install multiple Java versions and configure different Java versions manually. In that case, you have to modify a few environment variables when you need to switch your Java version. The other elegant and convenient way is to use the SDKMAN.
SDKMAN is a Software Development Kit Manager for managing parallel versions of multiple Software Development Kits on most Unix based systems. It allows us to install, remove, switch and list candidate versions of different SDKs including Java (e.g., JDK, Ant, Dotty, Gradle, Scala, and many more).
Here I will show how to manage multiple Java version on your UNIX based machine using SDKMAN. By reading this article, you will learn the following:
Install SDKMAN
List candidate JDKs using SDKMAN
Install multiple candidate JDKs using SDKMAN
Switch candidate JDKs using SDKMAN
Remove/Uninstall JDK using SDKMAN
The instructions are valid for most of the UNIX based operating systems including MacOS, any Linux OS (Ubuntu, Debian, MINT, Manjaro, OpenSUSE), FreeBSD, Solaris, Cygwin.
Open a new terminal and enter
curl -s “https://get.sdkman.io" | bash
Now, copy & paste the following in the terminal and enter
source "$HOME/.sdkman/bin/sdkman-init.sh"
It will install the SDKMAN in your machine. You can then check the version of the SDKMAN
sdk version
See the available Java versions offered by SDKMAN by giving the following command
sdk list java
It will show all the available JDK from different vendors with supported versions.
Install a particular JDK, e.g., JDK 15 Liberica from BellSoft
sdk install java 15.0.0-librcaInstalling: java 15.0.0-librcaDone installing!Do you want java 15.0.0-librca to be set as default? (Y/n):
You can now check the installed Java version with the following command
java -versionopenjdk version "15" 2020-09-15OpenJDK Runtime Environment (build 15+36)OpenJDK 64-Bit Server VM (build 15+36, mixed mode, sharing)
You can now install another JDK, e.g., JDK 8 Liberica from BellSoft
sdk install java 8.0.265-librcaInstalling: java 8.0.265-librcaDone installing!Do you want java 15.0.0-librca to be set as default? (Y/n):
If you now list available JDKs, you will see the installed JDKs marked as installed, as shown below.
sdk list java
You can then change the JDK with the following command
sdk use java 8.0.265-librcaUsing java version 8.0.265-librca in this shell.
You can check the installed JDK as follows
jdk -versionopenjdk version "1.8.0_265"OpenJDK Runtime Environment (build 1.8.0_265-b01)OpenJDK 64-Bit Server VM (build 25.265-b01, mixed mode)
You can uninstall a JDK using the following command
sdk uninstall java 15.0.0-librcaUninstalling java 15.0.0-librca...
In this article, I have shown how easily and elegantly you can manage Multiple Java version in your UNIX based operating system with SDKMAN. I am using NVM to manage multiple Node.js version in my local machine and I would put SDKMAN on par with NVM in terms of usefulness and developer friendliness. In fact, SDKMAN supports installing other JVM tools and SDKs like Groovy, Scala, Kotlin, Ceylon. Ant, Gradle, Grails, Maven, SBT, Spark, Spring Boot, Vert.x. If you work with Java and JVM, you should give SDKMAN a try. It will make your life easier to manage multiple Java and other JVM based SDK versions. | [
{
"code": null,
"e": 449,
"s": 171,
"text": "If you are a Java developer, you may need to install multiple Java versions on your machine. You may use Java8 or Java11 in your project, but want to learn newer versions of Java. Or maybe you are working on two different projects where two different versions of Java are used."
},
{
"code": null,
"e": 721,
"s": 449,
"text": "One way to achieve this is to install multiple Java versions and configure different Java versions manually. In that case, you have to modify a few environment variables when you need to switch your Java version. The other elegant and convenient way is to use the SDKMAN."
},
{
"code": null,
"e": 1019,
"s": 721,
"text": "SDKMAN is a Software Development Kit Manager for managing parallel versions of multiple Software Development Kits on most Unix based systems. It allows us to install, remove, switch and list candidate versions of different SDKs including Java (e.g., JDK, Ant, Dotty, Gradle, Scala, and many more)."
},
{
"code": null,
"e": 1168,
"s": 1019,
"text": "Here I will show how to manage multiple Java version on your UNIX based machine using SDKMAN. By reading this article, you will learn the following:"
},
{
"code": null,
"e": 1183,
"s": 1168,
"text": "Install SDKMAN"
},
{
"code": null,
"e": 1216,
"s": 1183,
"text": "List candidate JDKs using SDKMAN"
},
{
"code": null,
"e": 1261,
"s": 1216,
"text": "Install multiple candidate JDKs using SDKMAN"
},
{
"code": null,
"e": 1296,
"s": 1261,
"text": "Switch candidate JDKs using SDKMAN"
},
{
"code": null,
"e": 1330,
"s": 1296,
"text": "Remove/Uninstall JDK using SDKMAN"
},
{
"code": null,
"e": 1501,
"s": 1330,
"text": "The instructions are valid for most of the UNIX based operating systems including MacOS, any Linux OS (Ubuntu, Debian, MINT, Manjaro, OpenSUSE), FreeBSD, Solaris, Cygwin."
},
{
"code": null,
"e": 1531,
"s": 1501,
"text": "Open a new terminal and enter"
},
{
"code": null,
"e": 1570,
"s": 1531,
"text": "curl -s “https://get.sdkman.io\" | bash"
},
{
"code": null,
"e": 1628,
"s": 1570,
"text": "Now, copy & paste the following in the terminal and enter"
},
{
"code": null,
"e": 1670,
"s": 1628,
"text": "source \"$HOME/.sdkman/bin/sdkman-init.sh\""
},
{
"code": null,
"e": 1759,
"s": 1670,
"text": "It will install the SDKMAN in your machine. You can then check the version of the SDKMAN"
},
{
"code": null,
"e": 1771,
"s": 1759,
"text": "sdk version"
},
{
"code": null,
"e": 1853,
"s": 1771,
"text": "See the available Java versions offered by SDKMAN by giving the following command"
},
{
"code": null,
"e": 1867,
"s": 1853,
"text": "sdk list java"
},
{
"code": null,
"e": 1950,
"s": 1867,
"text": "It will show all the available JDK from different vendors with supported versions."
},
{
"code": null,
"e": 2012,
"s": 1950,
"text": "Install a particular JDK, e.g., JDK 15 Liberica from BellSoft"
},
{
"code": null,
"e": 2148,
"s": 2012,
"text": "sdk install java 15.0.0-librcaInstalling: java 15.0.0-librcaDone installing!Do you want java 15.0.0-librca to be set as default? (Y/n):"
},
{
"code": null,
"e": 2220,
"s": 2148,
"text": "You can now check the installed Java version with the following command"
},
{
"code": null,
"e": 2365,
"s": 2220,
"text": "java -versionopenjdk version \"15\" 2020-09-15OpenJDK Runtime Environment (build 15+36)OpenJDK 64-Bit Server VM (build 15+36, mixed mode, sharing)"
},
{
"code": null,
"e": 2433,
"s": 2365,
"text": "You can now install another JDK, e.g., JDK 8 Liberica from BellSoft"
},
{
"code": null,
"e": 2571,
"s": 2433,
"text": "sdk install java 8.0.265-librcaInstalling: java 8.0.265-librcaDone installing!Do you want java 15.0.0-librca to be set as default? (Y/n):"
},
{
"code": null,
"e": 2672,
"s": 2571,
"text": "If you now list available JDKs, you will see the installed JDKs marked as installed, as shown below."
},
{
"code": null,
"e": 2686,
"s": 2672,
"text": "sdk list java"
},
{
"code": null,
"e": 2741,
"s": 2686,
"text": "You can then change the JDK with the following command"
},
{
"code": null,
"e": 2817,
"s": 2741,
"text": "sdk use java 8.0.265-librcaUsing java version 8.0.265-librca in this shell."
},
{
"code": null,
"e": 2860,
"s": 2817,
"text": "You can check the installed JDK as follows"
},
{
"code": null,
"e": 3004,
"s": 2860,
"text": "jdk -versionopenjdk version \"1.8.0_265\"OpenJDK Runtime Environment (build 1.8.0_265-b01)OpenJDK 64-Bit Server VM (build 25.265-b01, mixed mode)"
},
{
"code": null,
"e": 3056,
"s": 3004,
"text": "You can uninstall a JDK using the following command"
},
{
"code": null,
"e": 3123,
"s": 3056,
"text": "sdk uninstall java 15.0.0-librcaUninstalling java 15.0.0-librca..."
}
] |
How to add new contacts in Android App using Kotlin? | This example demonstrates how to determine if network type (2G, 3G or 4G) in Android Kotlin.
Step 1 − Create a new project in Android Studio, go to File? New Project and fill all required details to create a new project.
Step 2 − Add the following code to res/layout/activity_main.xml.
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
android:padding="16dp"
tools:context=".MainActivity">
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginTop="50dp"
android:padding="8dp"
ndroid:text="Tutorials Point"
android:textAlignment="center"
android:textColor="@color/colorPrimaryDark"
android:textSize="48sp"
android:textStyle="bold" />
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginTop="20dp"
android:padding="8dp"
android:text="Add new contacts to phone.."
android:textAlignment="center"
android:textColor="@android:color/holo_blue_dark"
android:textSize="24sp"
android:textStyle="bold" />
<EditText
android:id="@+id/etName"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginTop="30dp"
android:inputType="text" />
<EditText
android:id="@+id/etNumber"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:inputType="number" />
<Button
android:id="@+id/buttonSave"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:onClick="addContact"
android:text="Save contact" />
</LinearLayout>
Step 3 − Add the following code to src/MainActivity.kt
import android.app.Activity
import android.content.Intent
import android.os.Bundle
import android.provider.ContactsContract
import android.view.View
import android.widget.EditText
import android.widget.Toast
import androidx.appcompat.app.AppCompatActivity
class MainActivity : AppCompatActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
title = "KotlinApp"
}
fun addContact(view: View) {
val etContactName: EditText = findViewById(R.id.etName)
val etContactNumber: EditText = findViewById(R.id.etNumber)
val name: String = etContactName.text.toString()
val phone = etContactNumber.text.toString()
val intent = Intent(ContactsContract.Intents.Insert.ACTION)
intent.setType(ContactsContract.RawContacts.CONTENT_TYPE)
intent.putExtra(ContactsContract.Intents.Insert.NAME, name)
intent.putExtra(ContactsContract.Intents.Insert.PHONE, phone)
startActivityForResult(intent, 1)
}
override fun onActivityResult(
requestCode: Int,
resultCode: Int,
intent: Intent?
) {
super.onActivityResult(requestCode, resultCode, intent)
if (requestCode == 1) {
if (resultCode == Activity.RESULT_OK) {
Toast.makeText(this, "Added Contact", Toast.LENGTH_SHORT).show()
}
if (resultCode == Activity.RESULT_CANCELED) {
Toast.makeText(this, "Cancelled Added Contact", Toast.LENGTH_SHORT).show()
}
}
}
}
Step 4 − Add the following code to androidManifest.xml
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android" package="app.com.myapplication">
<uses-permission android:name="android.permission.READ_PHONE_NUMBERS" />
<uses-permission android:name="android.permission.CALL_PHONE" />
<application
android:allowBackup="true"
android:icon="@mipmap/ic_launcher"
android:label="@string/app_name"
android:roundIcon="@mipmap/ic_launcher_round"
android:supportsRtl="true"
android:theme="@style/AppTheme">
<activity android:name=".MainActivity">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
</manifest>
Let's try to run your application. I assume you have connected your actual Android Mobile device with your computer. To run the app from android studio, open one of your project's activity files and click the Run icon from the toolbar. Select your mobile device as an option and then check your mobile device which will display your default screen | [
{
"code": null,
"e": 1155,
"s": 1062,
"text": "This example demonstrates how to determine if network type (2G, 3G or 4G) in Android Kotlin."
},
{
"code": null,
"e": 1283,
"s": 1155,
"text": "Step 1 − Create a new project in Android Studio, go to File? New Project and fill all required details to create a new project."
},
{
"code": null,
"e": 1348,
"s": 1283,
"text": "Step 2 − Add the following code to res/layout/activity_main.xml."
},
{
"code": null,
"e": 2991,
"s": 1348,
"text": "<?xml version=\"1.0\" encoding=\"utf-8\"?>\n<LinearLayout xmlns:android=\"http://schemas.android.com/apk/res/android\"\n xmlns:tools=\"http://schemas.android.com/tools\"\n android:layout_width=\"match_parent\"\n android:layout_height=\"match_parent\"\n android:orientation=\"vertical\"\n android:padding=\"16dp\"\n tools:context=\".MainActivity\">\n <TextView\n android:layout_width=\"match_parent\"\n android:layout_height=\"wrap_content\"\n android:layout_marginTop=\"50dp\"\n android:padding=\"8dp\"\n ndroid:text=\"Tutorials Point\"\n android:textAlignment=\"center\"\n android:textColor=\"@color/colorPrimaryDark\"\n android:textSize=\"48sp\"\n android:textStyle=\"bold\" />\n <TextView\n android:layout_width=\"match_parent\"\n android:layout_height=\"wrap_content\"\n android:layout_marginTop=\"20dp\"\n android:padding=\"8dp\"\n android:text=\"Add new contacts to phone..\"\n android:textAlignment=\"center\"\n android:textColor=\"@android:color/holo_blue_dark\"\n android:textSize=\"24sp\"\n android:textStyle=\"bold\" />\n <EditText\n android:id=\"@+id/etName\"\n android:layout_width=\"match_parent\"\n android:layout_height=\"wrap_content\"\n android:layout_marginTop=\"30dp\"\n android:inputType=\"text\" />\n <EditText\n android:id=\"@+id/etNumber\"\n android:layout_width=\"match_parent\"\n android:layout_height=\"wrap_content\"\n android:inputType=\"number\" />\n <Button\n android:id=\"@+id/buttonSave\"\n android:layout_width=\"match_parent\"\n android:layout_height=\"wrap_content\"\n android:onClick=\"addContact\"\n android:text=\"Save contact\" />\n</LinearLayout>"
},
{
"code": null,
"e": 3046,
"s": 2991,
"text": "Step 3 − Add the following code to src/MainActivity.kt"
},
{
"code": null,
"e": 4589,
"s": 3046,
"text": "import android.app.Activity\nimport android.content.Intent\nimport android.os.Bundle\nimport android.provider.ContactsContract\nimport android.view.View\nimport android.widget.EditText\nimport android.widget.Toast\nimport androidx.appcompat.app.AppCompatActivity\nclass MainActivity : AppCompatActivity() {\n override fun onCreate(savedInstanceState: Bundle?) {\n super.onCreate(savedInstanceState)\n setContentView(R.layout.activity_main)\n title = \"KotlinApp\"\n }\n fun addContact(view: View) {\n val etContactName: EditText = findViewById(R.id.etName)\n val etContactNumber: EditText = findViewById(R.id.etNumber)\n val name: String = etContactName.text.toString()\n val phone = etContactNumber.text.toString()\n val intent = Intent(ContactsContract.Intents.Insert.ACTION)\n intent.setType(ContactsContract.RawContacts.CONTENT_TYPE)\n intent.putExtra(ContactsContract.Intents.Insert.NAME, name)\n intent.putExtra(ContactsContract.Intents.Insert.PHONE, phone)\n startActivityForResult(intent, 1)\n }\n override fun onActivityResult(\n requestCode: Int,\n resultCode: Int,\n intent: Intent?\n ) {\n super.onActivityResult(requestCode, resultCode, intent)\n if (requestCode == 1) {\n if (resultCode == Activity.RESULT_OK) {\n Toast.makeText(this, \"Added Contact\", Toast.LENGTH_SHORT).show()\n } \n if (resultCode == Activity.RESULT_CANCELED) {\n Toast.makeText(this, \"Cancelled Added Contact\", Toast.LENGTH_SHORT).show()\n }\n }\n }\n}"
},
{
"code": null,
"e": 4644,
"s": 4589,
"text": "Step 4 − Add the following code to androidManifest.xml"
},
{
"code": null,
"e": 5459,
"s": 4644,
"text": "<?xml version=\"1.0\" encoding=\"utf-8\"?>\n<manifest xmlns:android=\"http://schemas.android.com/apk/res/android\" package=\"app.com.myapplication\">\n<uses-permission android:name=\"android.permission.READ_PHONE_NUMBERS\" />\n<uses-permission android:name=\"android.permission.CALL_PHONE\" />\n <application\n android:allowBackup=\"true\"\n android:icon=\"@mipmap/ic_launcher\"\n android:label=\"@string/app_name\"\n android:roundIcon=\"@mipmap/ic_launcher_round\"\n android:supportsRtl=\"true\"\n android:theme=\"@style/AppTheme\">\n <activity android:name=\".MainActivity\">\n <intent-filter>\n <action android:name=\"android.intent.action.MAIN\" />\n <category android:name=\"android.intent.category.LAUNCHER\" />\n </intent-filter>\n </activity>\n </application>\n</manifest>"
},
{
"code": null,
"e": 5807,
"s": 5459,
"text": "Let's try to run your application. I assume you have connected your actual Android Mobile device with your computer. To run the app from android studio, open one of your project's activity files and click the Run icon from the toolbar. Select your mobile device as an option and then check your mobile device which will display your default screen"
}
] |
Type Inference in C++ (auto and decltype) | In this tutorial, we will be discussing a program to understand Type interference in C++ (auto and decltype).
In case of auto keyword, the type of the variable is defined from the type of its initializer. Further with decltype, it lets you extract the type of variable from the called element.
Live Demo
#include <bits/stdc++.h>
using namespace std;
int main(){
auto x = 4;
auto y = 3.37;
auto ptr = &x;
cout << typeid(x).name() << endl
<< typeid(y).name() << endl
<< typeid(ptr).name() << endl;
return 0;
}
i
d
Pi
Live Demo
#include <bits/stdc++.h>
using namespace std;
int fun1() { return 10; }
char fun2() { return 'g'; }
int main(){
decltype(fun1()) x;
decltype(fun2()) y;
cout << typeid(x).name() << endl;
cout << typeid(y).name() << endl;
return 0;
}
i
c | [
{
"code": null,
"e": 1172,
"s": 1062,
"text": "In this tutorial, we will be discussing a program to understand Type interference in C++ (auto and decltype)."
},
{
"code": null,
"e": 1356,
"s": 1172,
"text": "In case of auto keyword, the type of the variable is defined from the type of its initializer. Further with decltype, it lets you extract the type of variable from the called element."
},
{
"code": null,
"e": 1367,
"s": 1356,
"text": " Live Demo"
},
{
"code": null,
"e": 1598,
"s": 1367,
"text": "#include <bits/stdc++.h>\nusing namespace std;\nint main(){\n auto x = 4;\n auto y = 3.37;\n auto ptr = &x;\n cout << typeid(x).name() << endl\n << typeid(y).name() << endl\n << typeid(ptr).name() << endl;\n return 0;\n}"
},
{
"code": null,
"e": 1605,
"s": 1598,
"text": "i\nd\nPi"
},
{
"code": null,
"e": 1616,
"s": 1605,
"text": " Live Demo"
},
{
"code": null,
"e": 1863,
"s": 1616,
"text": "#include <bits/stdc++.h>\nusing namespace std;\nint fun1() { return 10; }\nchar fun2() { return 'g'; }\nint main(){\n decltype(fun1()) x;\n decltype(fun2()) y;\n cout << typeid(x).name() << endl;\n cout << typeid(y).name() << endl;\n return 0;\n}"
},
{
"code": null,
"e": 1867,
"s": 1863,
"text": "i\nc"
}
] |
Scala - Functions Call-by-Name | Typically, parameters to functions are by-value parameters; that is, the value of the parameter is determined before it is passed to the function. But what if we need to write a function that accepts as a parameter an expression that we don't want evaluated until it's called within our function? For this circumstance, Scala offers call-by-name parameters.
A call-by-name mechanism passes a code block to the call and each time the call accesses the parameter, the code block is executed and the value is calculated. Here, delayed prints a message demonstrating that the method has been entered. Next, delayed prints a message with its value. Finally, delayed returns ‘t’.
The following program shows how to implement call–by–name.
object Demo {
def main(args: Array[String]) {
delayed(time());
}
def time() = {
println("Getting time in nano seconds")
System.nanoTime
}
def delayed( t: => Long ) = {
println("In delayed method")
println("Param: " + t)
}
}
Save the above program in Demo.scala. The following commands are used to compile and execute this program.
\>scalac Demo.scala
\>scala Demo
In delayed method
Getting time in nano seconds
Param: 2027245119786400
82 Lectures
7 hours
Arnab Chakraborty
23 Lectures
1.5 hours
Mukund Kumar Mishra
52 Lectures
1.5 hours
Bigdata Engineer
76 Lectures
5.5 hours
Bigdata Engineer
69 Lectures
7.5 hours
Bigdata Engineer
46 Lectures
4.5 hours
Stone River ELearning
Print
Add Notes
Bookmark this page | [
{
"code": null,
"e": 2356,
"s": 1998,
"text": "Typically, parameters to functions are by-value parameters; that is, the value of the parameter is determined before it is passed to the function. But what if we need to write a function that accepts as a parameter an expression that we don't want evaluated until it's called within our function? For this circumstance, Scala offers call-by-name parameters."
},
{
"code": null,
"e": 2672,
"s": 2356,
"text": "A call-by-name mechanism passes a code block to the call and each time the call accesses the parameter, the code block is executed and the value is calculated. Here, delayed prints a message demonstrating that the method has been entered. Next, delayed prints a message with its value. Finally, delayed returns ‘t’."
},
{
"code": null,
"e": 2731,
"s": 2672,
"text": "The following program shows how to implement call–by–name."
},
{
"code": null,
"e": 3006,
"s": 2731,
"text": "object Demo {\n def main(args: Array[String]) {\n delayed(time());\n }\n\n def time() = {\n println(\"Getting time in nano seconds\")\n System.nanoTime\n }\n def delayed( t: => Long ) = {\n println(\"In delayed method\")\n println(\"Param: \" + t)\n }\n}"
},
{
"code": null,
"e": 3113,
"s": 3006,
"text": "Save the above program in Demo.scala. The following commands are used to compile and execute this program."
},
{
"code": null,
"e": 3147,
"s": 3113,
"text": "\\>scalac Demo.scala\n\\>scala Demo\n"
},
{
"code": null,
"e": 3331,
"s": 3147,
"text": "In delayed method \nGetting time in nano seconds \nParam: 2027245119786400 \n"
},
{
"code": null,
"e": 3364,
"s": 3331,
"text": "\n 82 Lectures \n 7 hours \n"
},
{
"code": null,
"e": 3383,
"s": 3364,
"text": " Arnab Chakraborty"
},
{
"code": null,
"e": 3418,
"s": 3383,
"text": "\n 23 Lectures \n 1.5 hours \n"
},
{
"code": null,
"e": 3439,
"s": 3418,
"text": " Mukund Kumar Mishra"
},
{
"code": null,
"e": 3474,
"s": 3439,
"text": "\n 52 Lectures \n 1.5 hours \n"
},
{
"code": null,
"e": 3492,
"s": 3474,
"text": " Bigdata Engineer"
},
{
"code": null,
"e": 3527,
"s": 3492,
"text": "\n 76 Lectures \n 5.5 hours \n"
},
{
"code": null,
"e": 3545,
"s": 3527,
"text": " Bigdata Engineer"
},
{
"code": null,
"e": 3580,
"s": 3545,
"text": "\n 69 Lectures \n 7.5 hours \n"
},
{
"code": null,
"e": 3598,
"s": 3580,
"text": " Bigdata Engineer"
},
{
"code": null,
"e": 3633,
"s": 3598,
"text": "\n 46 Lectures \n 4.5 hours \n"
},
{
"code": null,
"e": 3656,
"s": 3633,
"text": " Stone River ELearning"
},
{
"code": null,
"e": 3663,
"s": 3656,
"text": " Print"
},
{
"code": null,
"e": 3674,
"s": 3663,
"text": " Add Notes"
}
] |
Statistical - TRIMMEAN Function | The TRIMMEAN function returns the mean of the interior of a data set. TRIMMEAN calculates the mean taken by excluding a percentage of data points from the top and bottom tails of a data set. You can use this function when you wish to exclude outlying data from your analysis.
TRIMMEAN (array, percent)
TRIMMEAN rounds the number of excluded data points down to the nearest multiple of 2. If percent = 0.1, 10 percent of 30 data points equals 3 points. For symmetry, TRIMMEAN excludes a single value from the top and bottom of the data set.
TRIMMEAN rounds the number of excluded data points down to the nearest multiple of 2. If percent = 0.1, 10 percent of 30 data points equals 3 points. For symmetry, TRIMMEAN excludes a single value from the top and bottom of the data set.
If percent < 0 or percent > 1, TRIMMEAN returns the #NUM! error value.
If percent < 0 or percent > 1, TRIMMEAN returns the #NUM! error value.
If the supplied array is empty, TRIMMEAN returns the #NUM! error value.
If the supplied array is empty, TRIMMEAN returns the #NUM! error value.
If the percent is non-numeric, TRIMMEAN returns the #VALUE! error value.
If the percent is non-numeric, TRIMMEAN returns the #VALUE! error value.
Excel 2007, Excel 2010, Excel 2013, Excel 2016
296 Lectures
146 hours
Arun Motoori
56 Lectures
5.5 hours
Pavan Lalwani
120 Lectures
6.5 hours
Inf Sid
134 Lectures
8.5 hours
Yoda Learning
46 Lectures
7.5 hours
William Fiset
25 Lectures
1.5 hours
Sasha Miller
Print
Add Notes
Bookmark this page | [
{
"code": null,
"e": 2130,
"s": 1854,
"text": "The TRIMMEAN function returns the mean of the interior of a data set. TRIMMEAN calculates the mean taken by excluding a percentage of data points from the top and bottom tails of a data set. You can use this function when you wish to exclude outlying data from your analysis."
},
{
"code": null,
"e": 2157,
"s": 2130,
"text": "TRIMMEAN (array, percent)\n"
},
{
"code": null,
"e": 2395,
"s": 2157,
"text": "TRIMMEAN rounds the number of excluded data points down to the nearest multiple of 2. If percent = 0.1, 10 percent of 30 data points equals 3 points. For symmetry, TRIMMEAN excludes a single value from the top and bottom of the data set."
},
{
"code": null,
"e": 2633,
"s": 2395,
"text": "TRIMMEAN rounds the number of excluded data points down to the nearest multiple of 2. If percent = 0.1, 10 percent of 30 data points equals 3 points. For symmetry, TRIMMEAN excludes a single value from the top and bottom of the data set."
},
{
"code": null,
"e": 2704,
"s": 2633,
"text": "If percent < 0 or percent > 1, TRIMMEAN returns the #NUM! error value."
},
{
"code": null,
"e": 2775,
"s": 2704,
"text": "If percent < 0 or percent > 1, TRIMMEAN returns the #NUM! error value."
},
{
"code": null,
"e": 2847,
"s": 2775,
"text": "If the supplied array is empty, TRIMMEAN returns the #NUM! error value."
},
{
"code": null,
"e": 2919,
"s": 2847,
"text": "If the supplied array is empty, TRIMMEAN returns the #NUM! error value."
},
{
"code": null,
"e": 2992,
"s": 2919,
"text": "If the percent is non-numeric, TRIMMEAN returns the #VALUE! error value."
},
{
"code": null,
"e": 3065,
"s": 2992,
"text": "If the percent is non-numeric, TRIMMEAN returns the #VALUE! error value."
},
{
"code": null,
"e": 3112,
"s": 3065,
"text": "Excel 2007, Excel 2010, Excel 2013, Excel 2016"
},
{
"code": null,
"e": 3148,
"s": 3112,
"text": "\n 296 Lectures \n 146 hours \n"
},
{
"code": null,
"e": 3162,
"s": 3148,
"text": " Arun Motoori"
},
{
"code": null,
"e": 3197,
"s": 3162,
"text": "\n 56 Lectures \n 5.5 hours \n"
},
{
"code": null,
"e": 3212,
"s": 3197,
"text": " Pavan Lalwani"
},
{
"code": null,
"e": 3248,
"s": 3212,
"text": "\n 120 Lectures \n 6.5 hours \n"
},
{
"code": null,
"e": 3257,
"s": 3248,
"text": " Inf Sid"
},
{
"code": null,
"e": 3293,
"s": 3257,
"text": "\n 134 Lectures \n 8.5 hours \n"
},
{
"code": null,
"e": 3308,
"s": 3293,
"text": " Yoda Learning"
},
{
"code": null,
"e": 3343,
"s": 3308,
"text": "\n 46 Lectures \n 7.5 hours \n"
},
{
"code": null,
"e": 3358,
"s": 3343,
"text": " William Fiset"
},
{
"code": null,
"e": 3393,
"s": 3358,
"text": "\n 25 Lectures \n 1.5 hours \n"
},
{
"code": null,
"e": 3407,
"s": 3393,
"text": " Sasha Miller"
},
{
"code": null,
"e": 3414,
"s": 3407,
"text": " Print"
},
{
"code": null,
"e": 3425,
"s": 3414,
"text": " Add Notes"
}
] |
How many ways can we read data from the keyboard in Java? | The java.io package provides various classes to read write data from various sources and destinations.
You can read data from user (keyboard) using various classes such as, Scanner, BufferedReader, InputStreamReader, Console etc.
From Java 1.5 Scanner class was introduced. This class accepts a File, InputStream, Path and, String objects, reads all the primitive data types and Strings (from the given source) token by token using regular expressions. By default, whitespace is considered as the delimiter (to break the data into tokens).
To read data from keyboard you need to use standard input as source (System.in). For each datatype a nextXXX() is provided namely, nextInt(), nextShort(), nextFloat(), nextLong(), nextBigDecimal(), nextBigInteger(), nextLong(), nextShort(), nextDouble(), nextByte(), nextFloat(), next().
Following Java program reads data from user using the Scanner class.
import java.util.Scanner;
class Student{
String name;
int age;
float percent;
boolean isLocal;
char grade;
Student(String name, int age, float percent, boolean isLocal, char grade){
this.name = name;
this.age = age;
this.percent = percent;
this.isLocal = isLocal;
this.grade = grade;
}
public void displayDetails(){
System.out.println("Details..............");
System.out.println("Name: "+this.name);
System.out.println("Age: "+this.age);
System.out.println("Percent: "+this.percent);
if(this.isLocal) {
System.out.println("Nationality: Indian");
}else {
System.out.println("Nationality: Foreigner");
}
System.out.println("Grade: "+this.grade);
}
}
public class ReadData {
public static void main(String args[]) {
Scanner sc =new Scanner(System.in);
System.out.println("Enter your name: ");
String name = sc.next();
System.out.println("Enter your age: ");
int age = sc.nextInt();
System.out.println("Enter your percent: ");
float percent = sc.nextFloat();
System.out.println("Are you local (enter true or false): ");
boolean isLocal = sc.nextBoolean();
System.out.println("Enter your grade(enter A, or, B or, C or, D): ");
char grade = sc.next().toCharArray()[0];
Student std = new Student(name, age, percent, isLocal, grade);
std.displayDetails();
}
}
Enter your name:
Krishna
Enter your age:
25
Enter your percent:
86
Are you local (enter true or false):
true
Enter your grade(enter A, or, B or, C or, D):
A
Details..............
Name: Krishna
Age: 25
Percent: 86.0
Nationality: Indian
Grade: A
The BufferedReader class of Java is used to read stream of characters from the specified source (character-input stream). The constructor of this class accepts an InputStream object as a parameter, you can to pass an InputStreamReader.
Following Java program reads data from user using the BufferedReader class.
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
class Student{
String name;
int age;
float percent;
boolean isLocal;
char grade;
Student(String name, int age, float percent, boolean isLocal, char grade){
this.name = name;
this.age = age;
this.percent = percent;
this.isLocal = isLocal;
this.grade = grade;
}
public void displayDetails(){
System.out.println("Details..............");
System.out.println("Name: "+this.name);
System.out.println("Age: "+this.age);
System.out.println("Percent: "+this.percent);
if(this.isLocal) {
System.out.println("Nationality: Indian");
}else {
System.out.println("Nationality: Foreigner");
}
System.out.println("Grade: "+this.grade);
}
}
public class ReadData {
public static void main(String args[]) throws IOException {
BufferedReader reader =new BufferedReader(new InputStreamReader(System.in));
System.out.println("Enter your name: ");
String name = reader.readLine();
System.out.println("Enter your age: ");
int age = Integer.parseInt(reader.readLine());
System.out.println("Enter your percent: ");
float percent = Float.parseFloat(reader.readLine());
System.out.println("Are you local (enter true or false): ");
boolean isLocal = Boolean.parseBoolean(reader.readLine());
System.out.println("Enter your grade(enter A, or, B or, C or, D): ");
char grade = (char) reader.read();
Student std = new Student(name, age, percent, isLocal, grade);
std.displayDetails();
}
}
Enter your name:
Krishna
Enter your age:
25
Enter your percent:
86
Are you local (enter true or false):
true
Enter your grade(enter A, or, B or, C or, D):
A
Details..............
Name: Krishna
Age: 25
Percent: 86.0
Nationality: Indian
Grade: A
This class is used to write/read data from the console (keyboard/screen) devices. It provides a readLine() method which reads a line from the key-board. You can get an object of the Console class using the console() method.
Note − If you try to execute this program in a non-interactive environment like IDE it doesn’t work.
Following Java program reads data from user using the Console class.
import java.io.BufferedReader;
import java.io.Console;
import java.io.IOException;
import java.io.InputStreamReader;
class Student{
String name;
int age;
float percent;
boolean isLocal;
char grade;
Student(String name, int age, float percent, boolean isLocal, char grade){
this.name = name;
this.age = age;
this.percent = percent;
this.isLocal = isLocal;
this.grade = grade;
}
public void displayDetails(){
System.out.println("Details..............");
System.out.println("Name: "+this.name);
System.out.println("Age: "+this.age);
System.out.println("Percent: "+this.percent);
if(this.isLocal) {
System.out.println("Nationality: Indian");
}else {
System.out.println("Nationality: Foreigner");
}
System.out.println("Grade: "+this.grade);
}
}
public class ReadData {
public static void main(String args[]) throws IOException {
Console console = System.console();
if (console == null) {
System.out.println("Console is not supported");
System.exit(1);
}
System.out.println("Enter your name: ");
String name = console.readLine();
System.out.println("Enter your age: ");
int age = Integer.parseInt(console.readLine());
System.out.println("Enter your percent: ");
float percent = Float.parseFloat(console.readLine());
System.out.println("Are you local (enter true or false): ");
boolean isLocal = Boolean.parseBoolean(console.readLine());
System.out.println("Enter your grade(enter A, or, B or, C or, D): ");
char grade = console.readLine().toCharArray()[0];
Student std = new Student(name, age, percent, isLocal, grade);
std.displayDetails();
}
}
Enter your name:
Krishna
Enter your age:
26
Enter your percent:
86
Are you local (enter true or false):
true
Enter your grade(enter A, or, B or, C or, D):
A
Details..............
Name: Krishna
Age: 26
Percent: 86.0
Nationality: Indian
Grade: A | [
{
"code": null,
"e": 1165,
"s": 1062,
"text": "The java.io package provides various classes to read write data from various sources and destinations."
},
{
"code": null,
"e": 1292,
"s": 1165,
"text": "You can read data from user (keyboard) using various classes such as, Scanner, BufferedReader, InputStreamReader, Console etc."
},
{
"code": null,
"e": 1602,
"s": 1292,
"text": "From Java 1.5 Scanner class was introduced. This class accepts a File, InputStream, Path and, String objects, reads all the primitive data types and Strings (from the given source) token by token using regular expressions. By default, whitespace is considered as the delimiter (to break the data into tokens)."
},
{
"code": null,
"e": 1890,
"s": 1602,
"text": "To read data from keyboard you need to use standard input as source (System.in). For each datatype a nextXXX() is provided namely, nextInt(), nextShort(), nextFloat(), nextLong(), nextBigDecimal(), nextBigInteger(), nextLong(), nextShort(), nextDouble(), nextByte(), nextFloat(), next()."
},
{
"code": null,
"e": 1959,
"s": 1890,
"text": "Following Java program reads data from user using the Scanner class."
},
{
"code": null,
"e": 3419,
"s": 1959,
"text": "import java.util.Scanner;\nclass Student{\n String name;\n int age;\n float percent;\n boolean isLocal;\n char grade;\n Student(String name, int age, float percent, boolean isLocal, char grade){\n this.name = name;\n this.age = age;\n this.percent = percent;\n this.isLocal = isLocal;\n this.grade = grade;\n }\n public void displayDetails(){\n System.out.println(\"Details..............\");\n System.out.println(\"Name: \"+this.name);\n System.out.println(\"Age: \"+this.age);\n System.out.println(\"Percent: \"+this.percent);\n if(this.isLocal) {\n System.out.println(\"Nationality: Indian\");\n }else {\n System.out.println(\"Nationality: Foreigner\");\n }\n System.out.println(\"Grade: \"+this.grade);\n }\n}\npublic class ReadData {\n public static void main(String args[]) {\n Scanner sc =new Scanner(System.in);\n System.out.println(\"Enter your name: \");\n String name = sc.next();\n System.out.println(\"Enter your age: \");\n int age = sc.nextInt();\n System.out.println(\"Enter your percent: \");\n float percent = sc.nextFloat();\n System.out.println(\"Are you local (enter true or false): \");\n boolean isLocal = sc.nextBoolean();\n System.out.println(\"Enter your grade(enter A, or, B or, C or, D): \");\n char grade = sc.next().toCharArray()[0];\n Student std = new Student(name, age, percent, isLocal, grade);\n std.displayDetails();\n }\n}"
},
{
"code": null,
"e": 3663,
"s": 3419,
"text": "Enter your name:\nKrishna\nEnter your age:\n25\nEnter your percent:\n86\nAre you local (enter true or false):\ntrue\nEnter your grade(enter A, or, B or, C or, D):\nA\nDetails..............\nName: Krishna\nAge: 25\nPercent: 86.0\nNationality: Indian\nGrade: A"
},
{
"code": null,
"e": 3899,
"s": 3663,
"text": "The BufferedReader class of Java is used to read stream of characters from the specified source (character-input stream). The constructor of this class accepts an InputStream object as a parameter, you can to pass an InputStreamReader."
},
{
"code": null,
"e": 3975,
"s": 3899,
"text": "Following Java program reads data from user using the BufferedReader class."
},
{
"code": null,
"e": 5631,
"s": 3975,
"text": "import java.io.BufferedReader;\nimport java.io.IOException;\nimport java.io.InputStreamReader;\nclass Student{\n String name;\n int age;\n float percent;\n boolean isLocal;\n char grade;\n Student(String name, int age, float percent, boolean isLocal, char grade){\n this.name = name;\n this.age = age;\n this.percent = percent;\n this.isLocal = isLocal;\n this.grade = grade;\n }\n public void displayDetails(){\n System.out.println(\"Details..............\");\n System.out.println(\"Name: \"+this.name);\n System.out.println(\"Age: \"+this.age);\n System.out.println(\"Percent: \"+this.percent);\n if(this.isLocal) {\n System.out.println(\"Nationality: Indian\");\n }else {\n System.out.println(\"Nationality: Foreigner\");\n }\n System.out.println(\"Grade: \"+this.grade);\n }\n}\npublic class ReadData {\n public static void main(String args[]) throws IOException {\n BufferedReader reader =new BufferedReader(new InputStreamReader(System.in));\n System.out.println(\"Enter your name: \");\n String name = reader.readLine();\n System.out.println(\"Enter your age: \");\n int age = Integer.parseInt(reader.readLine());\n System.out.println(\"Enter your percent: \");\n float percent = Float.parseFloat(reader.readLine());\n System.out.println(\"Are you local (enter true or false): \");\n boolean isLocal = Boolean.parseBoolean(reader.readLine());\n System.out.println(\"Enter your grade(enter A, or, B or, C or, D): \");\n char grade = (char) reader.read();\n Student std = new Student(name, age, percent, isLocal, grade);\n std.displayDetails();\n }\n}"
},
{
"code": null,
"e": 5875,
"s": 5631,
"text": "Enter your name:\nKrishna\nEnter your age:\n25\nEnter your percent:\n86\nAre you local (enter true or false):\ntrue\nEnter your grade(enter A, or, B or, C or, D):\nA\nDetails..............\nName: Krishna\nAge: 25\nPercent: 86.0\nNationality: Indian\nGrade: A"
},
{
"code": null,
"e": 6099,
"s": 5875,
"text": "This class is used to write/read data from the console (keyboard/screen) devices. It provides a readLine() method which reads a line from the key-board. You can get an object of the Console class using the console() method."
},
{
"code": null,
"e": 6200,
"s": 6099,
"text": "Note − If you try to execute this program in a non-interactive environment like IDE it doesn’t work."
},
{
"code": null,
"e": 6269,
"s": 6200,
"text": "Following Java program reads data from user using the Console class."
},
{
"code": null,
"e": 8046,
"s": 6269,
"text": "import java.io.BufferedReader;\nimport java.io.Console;\nimport java.io.IOException;\nimport java.io.InputStreamReader;\nclass Student{\n String name;\n int age;\n float percent;\n boolean isLocal;\n char grade;\n Student(String name, int age, float percent, boolean isLocal, char grade){\n this.name = name;\n this.age = age;\n this.percent = percent;\n this.isLocal = isLocal;\n this.grade = grade;\n }\n public void displayDetails(){\n System.out.println(\"Details..............\");\n System.out.println(\"Name: \"+this.name);\n System.out.println(\"Age: \"+this.age);\n System.out.println(\"Percent: \"+this.percent);\n if(this.isLocal) {\n System.out.println(\"Nationality: Indian\");\n }else {\n System.out.println(\"Nationality: Foreigner\");\n }\n System.out.println(\"Grade: \"+this.grade);\n }\n}\npublic class ReadData {\n public static void main(String args[]) throws IOException {\n Console console = System.console();\n if (console == null) {\n System.out.println(\"Console is not supported\");\n System.exit(1);\n }\n System.out.println(\"Enter your name: \");\n String name = console.readLine();\n System.out.println(\"Enter your age: \");\n int age = Integer.parseInt(console.readLine());\n System.out.println(\"Enter your percent: \");\n float percent = Float.parseFloat(console.readLine());\n System.out.println(\"Are you local (enter true or false): \");\n boolean isLocal = Boolean.parseBoolean(console.readLine());\n System.out.println(\"Enter your grade(enter A, or, B or, C or, D): \");\n char grade = console.readLine().toCharArray()[0];\n Student std = new Student(name, age, percent, isLocal, grade);\n std.displayDetails();\n }\n}"
},
{
"code": null,
"e": 8290,
"s": 8046,
"text": "Enter your name:\nKrishna\nEnter your age:\n26\nEnter your percent:\n86\nAre you local (enter true or false):\ntrue\nEnter your grade(enter A, or, B or, C or, D):\nA\nDetails..............\nName: Krishna\nAge: 26\nPercent: 86.0\nNationality: Indian\nGrade: A"
}
] |
Count of subarrays having product as a perfect cube - GeeksforGeeks | 01 Nov, 2021
Given an array arr[] consisting of N positive integers, the task is to count the number of subarrays with product of its elements equal to a perfect cube.
Examples:
Input: arr[] = {1, 8, 4, 2}Output: 6Explanation:The subarrays with product of elements equal to a perfect cube are:
{1}. Therefore, product of subarray = 1 (= (1)3).
{1, 8}. Therefore, product of subarray = 8 ( = 23).
{8}. Therefore, product of subarray = 8 = (23).
{4, 2}. Therefore, product of subarray = 8 (= 23).
{8, 4, 2}. Therefore, product of subarray = 64 (= 43).
{1, 8, 4, 2}. Therefore, product of subarray = 64 (= 43).
Therefore, the total count is 6.
Input: arr[] = {10, 10,10}Output: 1
Naive Approach: The simplest approach is to generate all possible subarrays from the given array and count those subarrays whose product of subarray elements is a perfect cube. After checking for all the subarrays, print the count obtained.
Below is the implementation of the above approach:
C++
Java
Python3
C#
Javascript
// C++ program for the above approach#include <bits/stdc++.h>using namespace std; // Function to check if a number// is perfect cube or notbool perfectCube(int N){ int cube_root; // Find the cube_root cube_root = (int)round(pow(N, 1.0 / 3.0)); // If cube of cube_root is // same as N, then return true if (cube_root * cube_root * cube_root == N) { return true; } // Otherwise return false;} // Function to count subarrays// whose product is a perfect cubevoid countSubarrays(int a[], int n){ // Store the required result int ans = 0; // Traverse all the subarrays for (int i = 0; i < n; i++) { int prod = 1; for (int j = i; j < n; j++) { prod = prod * a[j]; // If product of the current // subarray is a perfect cube if (perfectCube(prod)) // Increment count ans++; } } // Print the result cout << ans;} // Driver Codeint main(){ int arr[] = { 1, 8, 4, 2 }; int N = sizeof(arr) / sizeof(arr[0]); countSubarrays(arr, N); return 0;}
import java.util.*;public class GFG{ public static void main(String args[]) { int arr[] = { 1, 8, 4, 2 }; int N = arr.length; countSubarrays(arr, N); } // Function to count subarrays // whose product is a perfect cube static void countSubarrays(int a[], int n) { // Store the required result int ans = 0; // Traverse all the subarrays for (int i = 0; i < n; i++) { int prod = 1; for (int j = i; j < n; j++) { prod = prod * a[j]; // If product of the current // subarray is a perfect cube if (perfectCube(prod)) // Increment count ans++; } } // Print the result System.out.println(ans); } // Function to check if a number // is perfect cube or not static boolean perfectCube(int N) { int cube_root; // Find the cube_root cube_root = (int)Math.round(Math.pow(N, 1.0 / 3.0)); // If cube of cube_root is // same as N, then return true if (cube_root * cube_root * cube_root == N) { return true; } // Otherwise return false; }} // This code is contributed by abhinavjain194.
# Python 3 program for the above approach # Function to check if a number# is perfect cube or notdef perfectCube(N): # Find the cube_root cube_root = round(pow(N, 1 / 3)) # If cube of cube_root is # same as N, then return true if (cube_root * cube_root * cube_root == N): return True # Otherwise return False # Function to count subarrays# whose product is a perfect cubedef countSubarrays(a, n): # Store the required result ans = 0 # Traverse all the subarrays for i in range(n): prod = 1 for j in range(i, n): prod = prod * a[j] # If product of the current # subarray is a perfect cube if (perfectCube(prod)): # Increment count ans += 1 # Print the result print(ans) # Driver Codeif __name__ == "__main__": arr = [1, 8, 4, 2] N = len(arr) countSubarrays(arr, N) # This code is contributed by ukasp.
// C# program to implement// the above approachusing System;public class GFG{ // Driver Codepublic static void Main(String[] args){ int[] arr = { 1, 8, 4, 2 }; int N = arr.Length; countSubarrays(arr, N);} // Function to count subarrays // whose product is a perfect cube static void countSubarrays(int[] a, int n) { // Store the required result int ans = 0; // Traverse all the subarrays for (int i = 0; i < n; i++) { int prod = 1; for (int j = i; j < n; j++) { prod = prod * a[j]; // If product of the current // subarray is a perfect cube if (perfectCube(prod)) // Increment count ans++; } } // Print the result Console.Write(ans); } // Function to check if a number // is perfect cube or not static bool perfectCube(int N) { int cube_root; // Find the cube_root cube_root = (int)Math.Round(Math.Pow(N, 1.0 / 3.0)); // If cube of cube_root is // same as N, then return true if (cube_root * cube_root * cube_root == N) { return true; } // Otherwise return false; }} // This code is contributed by souravghosh0416.
<script> // Function to count subarrays // whose product is a perfect cube function countSubarrays(a , n) { // Store the required result var ans = 0; // Traverse all the subarrays for (i = 0; i < n; i++) { var prod = 1; for (j = i; j < n; j++) { prod = prod * a[j]; // If product of the current // subarray is a perfect cube if (perfectCube(prod)) // Increment count ans++; } } // Print the result document.write(ans); } // Function to check if a number // is perfect cube or not function perfectCube(N) { var cube_root; // Find the cube_root cube_root = parseInt(Math.round(Math.pow(N, 1.0 / 3.0))); // If cube of cube_root is // same as N, then return true if (cube_root * cube_root * cube_root == N) { return true; } // Otherwise return false; } var arr = [ 1, 8, 4, 2 ]; var N = arr.length; countSubarrays(arr, N); // This code is contributed by 29AjayKumar</script>
6
Time Complexity: O(N2)Auxiliary Space: O(1)
Efficient Approach: The above approach can also be optimized by storing the number of prime factors modulo 3 in a HashMap while traversing the array and count perfect cubes accordingly. Follow the steps below to solve the problem:
Initialize a variable, say ans, to store the required result, and an array V with 0s to store the frequency of prime factors mod 3 for every element in the given array arr[].
Initialize a Hashmap, say M, to store the frequency of the current state of prime factors and increment V by 1 in the HashMap.
Traverse the array arr[] using the variable i perform the following steps:Store the frequency of prime factors mod 3 of arr[i] in V.Increment the value of ans by frequency of V in M and then increment the value of V in M.
Store the frequency of prime factors mod 3 of arr[i] in V.
Increment the value of ans by frequency of V in M and then increment the value of V in M.
After completing the above steps. print the value of ans as the result.
Below is the implementation of the above approach:
C++14
Java
// C++ program for the above approach#include <bits/stdc++.h>using namespace std;#define MAX 1e5 // Function to store the prime// factorization of a numbervoid primeFactors(vector<int>& v, int n){ for (int i = 2; i * i <= n; i++) { // If N is divisible by i while (n % i == 0) { // Increment v[i] by 1 and // calculate it modulo by 3 v[i]++; v[i] %= 3; // Divide the number by i n /= i; } } // If the number is not equal to 1 if (n != 1) { // Increment v[n] by 1 v[n]++; // Calculate it modulo 3 v[n] %= 3; }} // Function to count the number of// subarrays whose product is a perfect cubevoid countSubarrays(int arr[], int n){ // Store the required result int ans = 0; // Stores the prime // factors modulo 3 vector<int> v(MAX, 0); // Stores the occurrences // of the prime factors map<vector<int>, int> mp; mp[v]++; // Traverse the array, arr[] for (int i = 0; i < n; i++) { // Store the prime factors // and update the vector v primeFactors(v, arr[i]); // Update the answer ans += mp[v]; // Increment current state // of the prime factors by 1 mp[v]++; } // Print the result cout << ans;} // Driver Codeint main(){ int arr[] = { 1, 8, 4, 2 }; int N = sizeof(arr) / sizeof(arr[0]); countSubarrays(arr, N); return 0;}
// Java program for the above approachimport java.io.*;import java.lang.*;import java.util.*; class GFG{ static int MAX = (int)(1e5); // To store the arr as a Key in mapstatic class Key{ int arr[]; Key(int arr[]) { this.arr = arr; } @Override public int hashCode() { return 31 + Arrays.hashCode(arr); } @Override public boolean equals(Object obj) { if (this == obj) return true; if (obj == null || (getClass() != obj.getClass())) return false; Key other = (Key)obj; if (!Arrays.equals(arr, other.arr)) return false; return true; }} // Function to store the prime// factorization of a numberstatic void primeFactors(int v[], int n){ for(int i = 2; i * i <= n; i++) { // If N is divisible by i while (n % i == 0) { // Increment v[i] by 1 and // calculate it modulo by 3 v[i]++; v[i] %= 3; // Divide the number by i n /= i; } } // If the number is not equal to 1 if (n != 1) { // Increment v[n] by 1 v[n]++; // Calculate it modulo 3 v[n] %= 3; }} // Function to count the number of// subarrays whose product is a perfect cubestatic void countSubarrays(int arr[], int n){ // Store the required result int ans = 0; // Stores the prime // factors modulo 3 int v[] = new int[MAX]; // Stores the occurrences // of the prime factors HashMap<Key, Integer> mp = new HashMap<>(); mp.put(new Key(v), 1); // Traverse the array, arr[] for(int i = 0; i < n; i++) { // Store the prime factors // and update the vector v primeFactors(v, arr[i]); // Update the answer ans += mp.getOrDefault(new Key(v), 0); // Increment current state // of the prime factors by 1 Key vv = new Key(v); mp.put(vv, mp.getOrDefault(vv, 0) + 1); } // Print the result System.out.println(ans);} // Driver Codepublic static void main(String[] args){ int arr[] = { 1, 8, 4, 2 }; int N = arr.length; countSubarrays(arr, N);}} // This code is contributed by Kingash
6
Time Complexity: O(N3/2)Auxiliary Space: O(N)
ukasp
abhinavjain194
souravghosh0416
Kingash
29AjayKumar
ankita_saini
maths-perfect-cube
subarray
Technical Scripter 2020
Arrays
Mathematical
Searching
Technical Scripter
Arrays
Searching
Mathematical
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Window Sliding Technique
Program to find sum of elements in a given array
Reversal algorithm for array rotation
Trapping Rain Water
Move all negative numbers to beginning and positive to end with constant extra space
Program for Fibonacci numbers
C++ Data Types
Write a program to print all permutations of a given string
Set in C++ Standard Template Library (STL)
Program to find GCD or HCF of two numbers | [
{
"code": null,
"e": 24820,
"s": 24792,
"text": "\n01 Nov, 2021"
},
{
"code": null,
"e": 24975,
"s": 24820,
"text": "Given an array arr[] consisting of N positive integers, the task is to count the number of subarrays with product of its elements equal to a perfect cube."
},
{
"code": null,
"e": 24985,
"s": 24975,
"text": "Examples:"
},
{
"code": null,
"e": 25101,
"s": 24985,
"text": "Input: arr[] = {1, 8, 4, 2}Output: 6Explanation:The subarrays with product of elements equal to a perfect cube are:"
},
{
"code": null,
"e": 25151,
"s": 25101,
"text": "{1}. Therefore, product of subarray = 1 (= (1)3)."
},
{
"code": null,
"e": 25203,
"s": 25151,
"text": "{1, 8}. Therefore, product of subarray = 8 ( = 23)."
},
{
"code": null,
"e": 25251,
"s": 25203,
"text": "{8}. Therefore, product of subarray = 8 = (23)."
},
{
"code": null,
"e": 25302,
"s": 25251,
"text": "{4, 2}. Therefore, product of subarray = 8 (= 23)."
},
{
"code": null,
"e": 25357,
"s": 25302,
"text": "{8, 4, 2}. Therefore, product of subarray = 64 (= 43)."
},
{
"code": null,
"e": 25415,
"s": 25357,
"text": "{1, 8, 4, 2}. Therefore, product of subarray = 64 (= 43)."
},
{
"code": null,
"e": 25448,
"s": 25415,
"text": "Therefore, the total count is 6."
},
{
"code": null,
"e": 25484,
"s": 25448,
"text": "Input: arr[] = {10, 10,10}Output: 1"
},
{
"code": null,
"e": 25725,
"s": 25484,
"text": "Naive Approach: The simplest approach is to generate all possible subarrays from the given array and count those subarrays whose product of subarray elements is a perfect cube. After checking for all the subarrays, print the count obtained."
},
{
"code": null,
"e": 25776,
"s": 25725,
"text": "Below is the implementation of the above approach:"
},
{
"code": null,
"e": 25780,
"s": 25776,
"text": "C++"
},
{
"code": null,
"e": 25785,
"s": 25780,
"text": "Java"
},
{
"code": null,
"e": 25793,
"s": 25785,
"text": "Python3"
},
{
"code": null,
"e": 25796,
"s": 25793,
"text": "C#"
},
{
"code": null,
"e": 25807,
"s": 25796,
"text": "Javascript"
},
{
"code": "// C++ program for the above approach#include <bits/stdc++.h>using namespace std; // Function to check if a number// is perfect cube or notbool perfectCube(int N){ int cube_root; // Find the cube_root cube_root = (int)round(pow(N, 1.0 / 3.0)); // If cube of cube_root is // same as N, then return true if (cube_root * cube_root * cube_root == N) { return true; } // Otherwise return false;} // Function to count subarrays// whose product is a perfect cubevoid countSubarrays(int a[], int n){ // Store the required result int ans = 0; // Traverse all the subarrays for (int i = 0; i < n; i++) { int prod = 1; for (int j = i; j < n; j++) { prod = prod * a[j]; // If product of the current // subarray is a perfect cube if (perfectCube(prod)) // Increment count ans++; } } // Print the result cout << ans;} // Driver Codeint main(){ int arr[] = { 1, 8, 4, 2 }; int N = sizeof(arr) / sizeof(arr[0]); countSubarrays(arr, N); return 0;}",
"e": 26910,
"s": 25807,
"text": null
},
{
"code": "import java.util.*;public class GFG{ public static void main(String args[]) { int arr[] = { 1, 8, 4, 2 }; int N = arr.length; countSubarrays(arr, N); } // Function to count subarrays // whose product is a perfect cube static void countSubarrays(int a[], int n) { // Store the required result int ans = 0; // Traverse all the subarrays for (int i = 0; i < n; i++) { int prod = 1; for (int j = i; j < n; j++) { prod = prod * a[j]; // If product of the current // subarray is a perfect cube if (perfectCube(prod)) // Increment count ans++; } } // Print the result System.out.println(ans); } // Function to check if a number // is perfect cube or not static boolean perfectCube(int N) { int cube_root; // Find the cube_root cube_root = (int)Math.round(Math.pow(N, 1.0 / 3.0)); // If cube of cube_root is // same as N, then return true if (cube_root * cube_root * cube_root == N) { return true; } // Otherwise return false; }} // This code is contributed by abhinavjain194.",
"e": 28041,
"s": 26910,
"text": null
},
{
"code": "# Python 3 program for the above approach # Function to check if a number# is perfect cube or notdef perfectCube(N): # Find the cube_root cube_root = round(pow(N, 1 / 3)) # If cube of cube_root is # same as N, then return true if (cube_root * cube_root * cube_root == N): return True # Otherwise return False # Function to count subarrays# whose product is a perfect cubedef countSubarrays(a, n): # Store the required result ans = 0 # Traverse all the subarrays for i in range(n): prod = 1 for j in range(i, n): prod = prod * a[j] # If product of the current # subarray is a perfect cube if (perfectCube(prod)): # Increment count ans += 1 # Print the result print(ans) # Driver Codeif __name__ == \"__main__\": arr = [1, 8, 4, 2] N = len(arr) countSubarrays(arr, N) # This code is contributed by ukasp.",
"e": 29000,
"s": 28041,
"text": null
},
{
"code": "// C# program to implement// the above approachusing System;public class GFG{ // Driver Codepublic static void Main(String[] args){ int[] arr = { 1, 8, 4, 2 }; int N = arr.Length; countSubarrays(arr, N);} // Function to count subarrays // whose product is a perfect cube static void countSubarrays(int[] a, int n) { // Store the required result int ans = 0; // Traverse all the subarrays for (int i = 0; i < n; i++) { int prod = 1; for (int j = i; j < n; j++) { prod = prod * a[j]; // If product of the current // subarray is a perfect cube if (perfectCube(prod)) // Increment count ans++; } } // Print the result Console.Write(ans); } // Function to check if a number // is perfect cube or not static bool perfectCube(int N) { int cube_root; // Find the cube_root cube_root = (int)Math.Round(Math.Pow(N, 1.0 / 3.0)); // If cube of cube_root is // same as N, then return true if (cube_root * cube_root * cube_root == N) { return true; } // Otherwise return false; }} // This code is contributed by souravghosh0416.",
"e": 30174,
"s": 29000,
"text": null
},
{
"code": "<script> // Function to count subarrays // whose product is a perfect cube function countSubarrays(a , n) { // Store the required result var ans = 0; // Traverse all the subarrays for (i = 0; i < n; i++) { var prod = 1; for (j = i; j < n; j++) { prod = prod * a[j]; // If product of the current // subarray is a perfect cube if (perfectCube(prod)) // Increment count ans++; } } // Print the result document.write(ans); } // Function to check if a number // is perfect cube or not function perfectCube(N) { var cube_root; // Find the cube_root cube_root = parseInt(Math.round(Math.pow(N, 1.0 / 3.0))); // If cube of cube_root is // same as N, then return true if (cube_root * cube_root * cube_root == N) { return true; } // Otherwise return false; } var arr = [ 1, 8, 4, 2 ]; var N = arr.length; countSubarrays(arr, N); // This code is contributed by 29AjayKumar</script>",
"e": 31198,
"s": 30174,
"text": null
},
{
"code": null,
"e": 31200,
"s": 31198,
"text": "6"
},
{
"code": null,
"e": 31246,
"s": 31202,
"text": "Time Complexity: O(N2)Auxiliary Space: O(1)"
},
{
"code": null,
"e": 31478,
"s": 31246,
"text": "Efficient Approach: The above approach can also be optimized by storing the number of prime factors modulo 3 in a HashMap while traversing the array and count perfect cubes accordingly. Follow the steps below to solve the problem: "
},
{
"code": null,
"e": 31653,
"s": 31478,
"text": "Initialize a variable, say ans, to store the required result, and an array V with 0s to store the frequency of prime factors mod 3 for every element in the given array arr[]."
},
{
"code": null,
"e": 31780,
"s": 31653,
"text": "Initialize a Hashmap, say M, to store the frequency of the current state of prime factors and increment V by 1 in the HashMap."
},
{
"code": null,
"e": 32002,
"s": 31780,
"text": "Traverse the array arr[] using the variable i perform the following steps:Store the frequency of prime factors mod 3 of arr[i] in V.Increment the value of ans by frequency of V in M and then increment the value of V in M."
},
{
"code": null,
"e": 32061,
"s": 32002,
"text": "Store the frequency of prime factors mod 3 of arr[i] in V."
},
{
"code": null,
"e": 32151,
"s": 32061,
"text": "Increment the value of ans by frequency of V in M and then increment the value of V in M."
},
{
"code": null,
"e": 32223,
"s": 32151,
"text": "After completing the above steps. print the value of ans as the result."
},
{
"code": null,
"e": 32275,
"s": 32223,
"text": "Below is the implementation of the above approach: "
},
{
"code": null,
"e": 32281,
"s": 32275,
"text": "C++14"
},
{
"code": null,
"e": 32286,
"s": 32281,
"text": "Java"
},
{
"code": "// C++ program for the above approach#include <bits/stdc++.h>using namespace std;#define MAX 1e5 // Function to store the prime// factorization of a numbervoid primeFactors(vector<int>& v, int n){ for (int i = 2; i * i <= n; i++) { // If N is divisible by i while (n % i == 0) { // Increment v[i] by 1 and // calculate it modulo by 3 v[i]++; v[i] %= 3; // Divide the number by i n /= i; } } // If the number is not equal to 1 if (n != 1) { // Increment v[n] by 1 v[n]++; // Calculate it modulo 3 v[n] %= 3; }} // Function to count the number of// subarrays whose product is a perfect cubevoid countSubarrays(int arr[], int n){ // Store the required result int ans = 0; // Stores the prime // factors modulo 3 vector<int> v(MAX, 0); // Stores the occurrences // of the prime factors map<vector<int>, int> mp; mp[v]++; // Traverse the array, arr[] for (int i = 0; i < n; i++) { // Store the prime factors // and update the vector v primeFactors(v, arr[i]); // Update the answer ans += mp[v]; // Increment current state // of the prime factors by 1 mp[v]++; } // Print the result cout << ans;} // Driver Codeint main(){ int arr[] = { 1, 8, 4, 2 }; int N = sizeof(arr) / sizeof(arr[0]); countSubarrays(arr, N); return 0;}",
"e": 33759,
"s": 32286,
"text": null
},
{
"code": "// Java program for the above approachimport java.io.*;import java.lang.*;import java.util.*; class GFG{ static int MAX = (int)(1e5); // To store the arr as a Key in mapstatic class Key{ int arr[]; Key(int arr[]) { this.arr = arr; } @Override public int hashCode() { return 31 + Arrays.hashCode(arr); } @Override public boolean equals(Object obj) { if (this == obj) return true; if (obj == null || (getClass() != obj.getClass())) return false; Key other = (Key)obj; if (!Arrays.equals(arr, other.arr)) return false; return true; }} // Function to store the prime// factorization of a numberstatic void primeFactors(int v[], int n){ for(int i = 2; i * i <= n; i++) { // If N is divisible by i while (n % i == 0) { // Increment v[i] by 1 and // calculate it modulo by 3 v[i]++; v[i] %= 3; // Divide the number by i n /= i; } } // If the number is not equal to 1 if (n != 1) { // Increment v[n] by 1 v[n]++; // Calculate it modulo 3 v[n] %= 3; }} // Function to count the number of// subarrays whose product is a perfect cubestatic void countSubarrays(int arr[], int n){ // Store the required result int ans = 0; // Stores the prime // factors modulo 3 int v[] = new int[MAX]; // Stores the occurrences // of the prime factors HashMap<Key, Integer> mp = new HashMap<>(); mp.put(new Key(v), 1); // Traverse the array, arr[] for(int i = 0; i < n; i++) { // Store the prime factors // and update the vector v primeFactors(v, arr[i]); // Update the answer ans += mp.getOrDefault(new Key(v), 0); // Increment current state // of the prime factors by 1 Key vv = new Key(v); mp.put(vv, mp.getOrDefault(vv, 0) + 1); } // Print the result System.out.println(ans);} // Driver Codepublic static void main(String[] args){ int arr[] = { 1, 8, 4, 2 }; int N = arr.length; countSubarrays(arr, N);}} // This code is contributed by Kingash",
"e": 36054,
"s": 33759,
"text": null
},
{
"code": null,
"e": 36056,
"s": 36054,
"text": "6"
},
{
"code": null,
"e": 36104,
"s": 36058,
"text": "Time Complexity: O(N3/2)Auxiliary Space: O(N)"
},
{
"code": null,
"e": 36112,
"s": 36106,
"text": "ukasp"
},
{
"code": null,
"e": 36127,
"s": 36112,
"text": "abhinavjain194"
},
{
"code": null,
"e": 36143,
"s": 36127,
"text": "souravghosh0416"
},
{
"code": null,
"e": 36151,
"s": 36143,
"text": "Kingash"
},
{
"code": null,
"e": 36163,
"s": 36151,
"text": "29AjayKumar"
},
{
"code": null,
"e": 36176,
"s": 36163,
"text": "ankita_saini"
},
{
"code": null,
"e": 36195,
"s": 36176,
"text": "maths-perfect-cube"
},
{
"code": null,
"e": 36204,
"s": 36195,
"text": "subarray"
},
{
"code": null,
"e": 36228,
"s": 36204,
"text": "Technical Scripter 2020"
},
{
"code": null,
"e": 36235,
"s": 36228,
"text": "Arrays"
},
{
"code": null,
"e": 36248,
"s": 36235,
"text": "Mathematical"
},
{
"code": null,
"e": 36258,
"s": 36248,
"text": "Searching"
},
{
"code": null,
"e": 36277,
"s": 36258,
"text": "Technical Scripter"
},
{
"code": null,
"e": 36284,
"s": 36277,
"text": "Arrays"
},
{
"code": null,
"e": 36294,
"s": 36284,
"text": "Searching"
},
{
"code": null,
"e": 36307,
"s": 36294,
"text": "Mathematical"
},
{
"code": null,
"e": 36405,
"s": 36307,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 36414,
"s": 36405,
"text": "Comments"
},
{
"code": null,
"e": 36427,
"s": 36414,
"text": "Old Comments"
},
{
"code": null,
"e": 36452,
"s": 36427,
"text": "Window Sliding Technique"
},
{
"code": null,
"e": 36501,
"s": 36452,
"text": "Program to find sum of elements in a given array"
},
{
"code": null,
"e": 36539,
"s": 36501,
"text": "Reversal algorithm for array rotation"
},
{
"code": null,
"e": 36559,
"s": 36539,
"text": "Trapping Rain Water"
},
{
"code": null,
"e": 36644,
"s": 36559,
"text": "Move all negative numbers to beginning and positive to end with constant extra space"
},
{
"code": null,
"e": 36674,
"s": 36644,
"text": "Program for Fibonacci numbers"
},
{
"code": null,
"e": 36689,
"s": 36674,
"text": "C++ Data Types"
},
{
"code": null,
"e": 36749,
"s": 36689,
"text": "Write a program to print all permutations of a given string"
},
{
"code": null,
"e": 36792,
"s": 36749,
"text": "Set in C++ Standard Template Library (STL)"
}
] |
Why do we use import statement in Java? Where it should be included in the class? | The import statement can be used to import an entire package or sometimes import certain classes and interfaces inside the package. The import statement is written before the class definition and after the package statement(if there is any). Also, the import statement is optional.
A program that demonstrates this in Java is given as follows:
Live Demo
import java.util.LinkedList;
public class Demo {
public static void main(String[] args) {
LinkedList<String> l = new LinkedList<String>();
l.add("Apple");
l.add("Mango");
l.add("Cherry");
l.add("Orange");
l.add("Pear");
System.out.println("The LinkedList is: " + l);
}
}
The LinkedList is: [Apple, Mango, Cherry, Orange, Pear]
Now let us understand the above program.
The LinkedList class is available in the java.util package. The import statement is used to import it. Then LinkedList l is created. LinkedList.add() is used to add a elements to the LinkedList. Then the LinkedList is displayed. A code snippet which demonstrates this is as follows:
LinkedList<String> l = new LinkedList<String>();
l.add("Apple");
l.add("Mango");
l.add("Cherry");
l.add("Orange");
l.add("Pear");
System.out.println("The LinkedList is: " + l); | [
{
"code": null,
"e": 1344,
"s": 1062,
"text": "The import statement can be used to import an entire package or sometimes import certain classes and interfaces inside the package. The import statement is written before the class definition and after the package statement(if there is any). Also, the import statement is optional."
},
{
"code": null,
"e": 1406,
"s": 1344,
"text": "A program that demonstrates this in Java is given as follows:"
},
{
"code": null,
"e": 1417,
"s": 1406,
"text": " Live Demo"
},
{
"code": null,
"e": 1737,
"s": 1417,
"text": "import java.util.LinkedList;\n\npublic class Demo {\n public static void main(String[] args) {\n LinkedList<String> l = new LinkedList<String>();\n l.add(\"Apple\");\n l.add(\"Mango\");\n l.add(\"Cherry\");\n l.add(\"Orange\");\n l.add(\"Pear\");\n System.out.println(\"The LinkedList is: \" + l);\n }\n}"
},
{
"code": null,
"e": 1793,
"s": 1737,
"text": "The LinkedList is: [Apple, Mango, Cherry, Orange, Pear]"
},
{
"code": null,
"e": 1834,
"s": 1793,
"text": "Now let us understand the above program."
},
{
"code": null,
"e": 2117,
"s": 1834,
"text": "The LinkedList class is available in the java.util package. The import statement is used to import it. Then LinkedList l is created. LinkedList.add() is used to add a elements to the LinkedList. Then the LinkedList is displayed. A code snippet which demonstrates this is as follows:"
},
{
"code": null,
"e": 2294,
"s": 2117,
"text": "LinkedList<String> l = new LinkedList<String>();\nl.add(\"Apple\");\nl.add(\"Mango\");\nl.add(\"Cherry\");\nl.add(\"Orange\");\nl.add(\"Pear\");\nSystem.out.println(\"The LinkedList is: \" + l);"
}
] |
How to find the inner height and inner width of a browser window in JavaScript? | Javascript window object simply represents the browser window. This method is supported by all browsers. To get the inner height and inner width this method has provided some properties such as window.innerHeight and window.innerwidth respectively. Using these properties, it is easy to find the height and width of a browser window. Let's discuss them individually.
In the following example, using the property window.innerWidth, the inner width of the browser window is found out and the result is displayed in the output. It gives the result in pixels.
Live Demo
<html>
<body>
<p id="width"></p>
<script>
var w = window.innerWidth
var x = document.getElementById("width");
x.innerHTML = "Browser inner window width: " + w ;
</script>
</body>
</html>
Browser inner window width: 598
In the following example, using the property window.innerheight, the inner height of the browser window is found out and the result is displayed in the output. It gives the result in pixels.
Live Demo
<html>
<body>
<p id="height"></p>
<script>
var h = window.innerHeight
var x = document.getElementById("height");
x.innerHTML = "Browser inner window height: " + h ;
</script>
</body>
</html>
Browser inner window height: 477; | [
{
"code": null,
"e": 1429,
"s": 1062,
"text": "Javascript window object simply represents the browser window. This method is supported by all browsers. To get the inner height and inner width this method has provided some properties such as window.innerHeight and window.innerwidth respectively. Using these properties, it is easy to find the height and width of a browser window. Let's discuss them individually."
},
{
"code": null,
"e": 1618,
"s": 1429,
"text": "In the following example, using the property window.innerWidth, the inner width of the browser window is found out and the result is displayed in the output. It gives the result in pixels."
},
{
"code": null,
"e": 1628,
"s": 1618,
"text": "Live Demo"
},
{
"code": null,
"e": 1824,
"s": 1628,
"text": "<html>\n<body>\n<p id=\"width\"></p>\n<script>\n var w = window.innerWidth\n var x = document.getElementById(\"width\");\n x.innerHTML = \"Browser inner window width: \" + w ;\n</script>\n</body>\n</html>"
},
{
"code": null,
"e": 1856,
"s": 1824,
"text": "Browser inner window width: 598"
},
{
"code": null,
"e": 2047,
"s": 1856,
"text": "In the following example, using the property window.innerheight, the inner height of the browser window is found out and the result is displayed in the output. It gives the result in pixels."
},
{
"code": null,
"e": 2058,
"s": 2047,
"text": " Live Demo"
},
{
"code": null,
"e": 2258,
"s": 2058,
"text": "<html>\n<body>\n<p id=\"height\"></p>\n<script>\n var h = window.innerHeight\n var x = document.getElementById(\"height\");\n x.innerHTML = \"Browser inner window height: \" + h ;\n</script>\n</body>\n</html>"
},
{
"code": null,
"e": 2292,
"s": 2258,
"text": "Browser inner window height: 477;"
}
] |
Android Notification Example with Vibration, Sound, Action and Big View Styles | This example demonstrate about Android Notification Example with Vibration, Sound, Action and Big View Styles
Step 1 − Create a new project in Android Studio, go to File ⇒ New Project and fill all required details to create a new project.
Step 2 − Add the following code to res/layout/activity_main.xml.
<? xml version= "1.0" encoding= "utf-8" ?>
<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"
android :padding= "16dp"
tools :context= ".MainActivity" >
<Button
android :id = "@+id/btnCreateNotification"
android :layout_width= "0dp"
android :layout_height= "wrap_content"
android :text = "Create notification"
app :layout_constraintBottom_toBottomOf= "parent"
app :layout_constraintEnd_toEndOf= "parent"
app :layout_constraintStart_toStartOf= "parent"
app :layout_constraintTop_toTopOf= "parent" />
</android.support.constraint.ConstraintLayout>
Step 3 − Add the following code to src/MainActivity.java
package app.tutorialspoint.com.notifyme;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.content.Context;
import android.content.Intent;
import android.support.v4.app.NotificationCompat;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
public class MainActivity extends AppCompatActivity {
private final static String default_notification_channel_id = "default";
@Override
protected void onCreate (Bundle savedInstanceState) {
super .onCreate(savedInstanceState);
setContentView(R.layout. activity_main );
Button btnCreateNotification = findViewById(R.id. btnCreateNotification );
btnCreateNotification.setOnClickListener( new View.OnClickListener() {
@Override
public void onClick (View v) {
Intent intent = new Intent(getApplicationContext(), MainActivity. class );
final PendingIntent resultPendingIntent =
PendingIntent. getActivity (
MainActivity. this,
0,
intent,
PendingIntent. FLAG_CANCEL_CURRENT
);
NotificationCompat.Builder mBuilder =
new NotificationCompat.Builder(MainActivity. this,
default_notification_channel_id )
.setSmallIcon(R.drawable. ic_launcher_foreground )
.setContentTitle( "Test" )
.addAction(R.drawable. ic_launcher_foreground, "Add", resultPendingIntent)
.setContentIntent(resultPendingIntent)
.setStyle( new NotificationCompat.BigTextStyle().bigText( "Big View Styles" ))
.setContentText( "Hello! This is my first push notification" );
NotificationManager mNotificationManager = (NotificationManager)
getSystemService(Context. NOTIFICATION_SERVICE );
mNotificationManager.notify(( int ) System. currentTimeMillis (), mBuilder.build()) ;
}
});
}
}
Step 4 − Add the following code to androidManifest.xml
<? xml version= "1.0" encoding= "utf-8" ?>
<manifest xmlns: android = "http://schemas.android.com/apk/res/android"
package= "app.tutorialspoint.com.notifyme" >
<uses-permission android :name= "android.permission.VIBRATE" />
<application
android :allowBackup= "true"
android :icon= "@mipmap/ic_launcher"
android :label= "@string/app_name"
android :roundIcon= "@mipmap/ic_launcher_round"
android :supportsRtl= "true"
android :theme= "@style/AppTheme" >
<activity android :name= ".MainActivity" >
<intent-filter>
<action android :name= "android.intent.action.MAIN" />
<category android :name= "android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<service
android :name= ".MyFirebaseMessagingService"
android :exported= "false" >
<intent-filter>
<action android :name= "com.google.firebase.MESSAGING_EVENT" />
</intent-filter>
</service>
</application>
</manifest>
Let's try to run your application. I assume you have connected your actual Android Mobile device with your computer. To run the app from android studio, open one of your project's activity files and click Run icon from the toolbar. Select your mobile device as an option and then check your mobile device which will display your default screen – | [
{
"code": null,
"e": 1172,
"s": 1062,
"text": "This example demonstrate about Android Notification Example with Vibration, Sound, Action and Big View Styles"
},
{
"code": null,
"e": 1301,
"s": 1172,
"text": "Step 1 − Create a new project in Android Studio, go to File ⇒ New Project and fill all required details to create a new project."
},
{
"code": null,
"e": 1366,
"s": 1301,
"text": "Step 2 − Add the following code to res/layout/activity_main.xml."
},
{
"code": null,
"e": 2222,
"s": 1366,
"text": "<? xml version= \"1.0\" encoding= \"utf-8\" ?>\n<android.support.constraint.ConstraintLayout\n xmlns: android = \"http://schemas.android.com/apk/res/android\"\n xmlns: app = \"http://schemas.android.com/apk/res-auto\"\n xmlns: tools = \"http://schemas.android.com/tools\"\n android :layout_width= \"match_parent\"\n android :layout_height= \"match_parent\"\n android :padding= \"16dp\"\n tools :context= \".MainActivity\" >\n <Button\n android :id = \"@+id/btnCreateNotification\"\n android :layout_width= \"0dp\"\n android :layout_height= \"wrap_content\"\n android :text = \"Create notification\"\n app :layout_constraintBottom_toBottomOf= \"parent\"\n app :layout_constraintEnd_toEndOf= \"parent\"\n app :layout_constraintStart_toStartOf= \"parent\"\n app :layout_constraintTop_toTopOf= \"parent\" />\n</android.support.constraint.ConstraintLayout>"
},
{
"code": null,
"e": 2279,
"s": 2222,
"text": "Step 3 − Add the following code to src/MainActivity.java"
},
{
"code": null,
"e": 4327,
"s": 2279,
"text": "package app.tutorialspoint.com.notifyme;\nimport android.app.NotificationManager;\nimport android.app.PendingIntent;\nimport android.content.Context;\nimport android.content.Intent;\nimport android.support.v4.app.NotificationCompat;\nimport android.support.v7.app.AppCompatActivity;\nimport android.os.Bundle;\nimport android.view.View;\nimport android.widget.Button;\npublic class MainActivity extends AppCompatActivity {\n private final static String default_notification_channel_id = \"default\";\n @Override\n protected void onCreate (Bundle savedInstanceState) {\n super .onCreate(savedInstanceState);\n setContentView(R.layout. activity_main );\n Button btnCreateNotification = findViewById(R.id. btnCreateNotification );\n btnCreateNotification.setOnClickListener( new View.OnClickListener() {\n @Override\n public void onClick (View v) {\n Intent intent = new Intent(getApplicationContext(), MainActivity. class );\n final PendingIntent resultPendingIntent =\n PendingIntent. getActivity (\n MainActivity. this,\n 0,\n intent,\n PendingIntent. FLAG_CANCEL_CURRENT\n );\n NotificationCompat.Builder mBuilder =\n new NotificationCompat.Builder(MainActivity. this,\n default_notification_channel_id )\n .setSmallIcon(R.drawable. ic_launcher_foreground )\n .setContentTitle( \"Test\" )\n .addAction(R.drawable. ic_launcher_foreground, \"Add\", resultPendingIntent)\n .setContentIntent(resultPendingIntent)\n .setStyle( new NotificationCompat.BigTextStyle().bigText( \"Big View Styles\" ))\n .setContentText( \"Hello! This is my first push notification\" );\n NotificationManager mNotificationManager = (NotificationManager)\n getSystemService(Context. NOTIFICATION_SERVICE );\n mNotificationManager.notify(( int ) System. currentTimeMillis (), mBuilder.build()) ;\n }\n });\n }\n}"
},
{
"code": null,
"e": 4382,
"s": 4327,
"text": "Step 4 − Add the following code to androidManifest.xml"
},
{
"code": null,
"e": 5419,
"s": 4382,
"text": "<? xml version= \"1.0\" encoding= \"utf-8\" ?>\n<manifest xmlns: android = \"http://schemas.android.com/apk/res/android\"\n package= \"app.tutorialspoint.com.notifyme\" >\n <uses-permission android :name= \"android.permission.VIBRATE\" />\n <application\n android :allowBackup= \"true\"\n android :icon= \"@mipmap/ic_launcher\"\n android :label= \"@string/app_name\"\n android :roundIcon= \"@mipmap/ic_launcher_round\"\n android :supportsRtl= \"true\"\n android :theme= \"@style/AppTheme\" >\n <activity android :name= \".MainActivity\" >\n <intent-filter>\n <action android :name= \"android.intent.action.MAIN\" />\n <category android :name= \"android.intent.category.LAUNCHER\" />\n </intent-filter>\n </activity>\n <service\n android :name= \".MyFirebaseMessagingService\"\n android :exported= \"false\" >\n <intent-filter>\n <action android :name= \"com.google.firebase.MESSAGING_EVENT\" />\n </intent-filter>\n </service>\n </application>\n</manifest>"
},
{
"code": null,
"e": 5766,
"s": 5419,
"text": "Let's try to run your application. I assume you have connected your actual Android Mobile device with your computer. To run the app from android studio, open one of your project's activity files and click Run icon from the toolbar. Select your mobile device as an option and then check your mobile device which will display your default screen –"
}
] |
C# Properties (Get and Set) | Before we start to explain properties, you should have a basic understanding of "Encapsulation".
The meaning of Encapsulation, is to make sure that "sensitive" data is hidden
from users. To achieve this, you must:
declare fields/variables as private
provide public get
and set methods, through properties, to access and update the value of a private
field
You learned from the previous chapter that private variables can only be
accessed within the same class (an outside class has no access to it). However,
sometimes we need to access them - and it can be done with properties.
A property is like a combination of a variable and a method, and it has two methods: a get and a set method:
class Person
{
private string name; // field
public string Name // property
{
get { return name; } // get method
set { name = value; } // set method
}
}
The Name property is associated with the name field. It is a good practice to use the same name for both the property and the private field, but with an uppercase first letter.
The get method returns the value of the variable name.
The set method assigns a value to the
name variable. The value keyword represents the value we assign to the property.
If you don't fully understand it, take a look at the example below.
Now we can use the Name property to access and update the private field of the Person class:
class Person
{
private string name; // field
public string Name // property
{
get { return name; }
set { name = value; }
}
}
class Program
{
static void Main(string[] args)
{
Person myObj = new Person();
myObj.Name = "Liam";
Console.WriteLine(myObj.Name);
}
}
The output will be:
Try it Yourself »
C# also provides a way to use short-hand / automatic properties, where you do
not have to define the field for the property, and you only have to write get;
and set; inside the property.
The following example will produce the same result as the example above. The only difference is that there is less code:
Using automatic properties:
class Person
{
public string Name // property
{ get; set; }
}
class Program
{
static void Main(string[] args)
{
Person myObj = new Person();
myObj.Name = "Liam";
Console.WriteLine(myObj.Name);
}
}
The output will be:
Try it Yourself »
Better control of class members (reduce the possibility of yourself (or others) to mess up the code)
Fields can be made read-only (if you only use the get method), or write-only (if you only use the set method)
Flexible: the programmer can change one part of the code without affecting other parts
Increased security of data
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": 97,
"s": 0,
"text": "Before we start to explain properties, you should have a basic understanding of \"Encapsulation\"."
},
{
"code": null,
"e": 216,
"s": 97,
"text": "The meaning of Encapsulation, is to make sure that \"sensitive\" data is hidden \nfrom users. To achieve this, you must:\n"
},
{
"code": null,
"e": 252,
"s": 216,
"text": "declare fields/variables as private"
},
{
"code": null,
"e": 360,
"s": 252,
"text": "provide public get \nand set methods, through properties, to access and update the value of a private \nfield"
},
{
"code": null,
"e": 586,
"s": 360,
"text": "You learned from the previous chapter that private variables can only be \naccessed within the same class (an outside class has no access to it). However, \nsometimes we need to access them - and it can be done with properties."
},
{
"code": null,
"e": 695,
"s": 586,
"text": "A property is like a combination of a variable and a method, and it has two methods: a get and a set method:"
},
{
"code": null,
"e": 876,
"s": 695,
"text": "class Person\n{\n private string name; // field\n\n public string Name // property\n {\n get { return name; } // get method\n set { name = value; } // set method\n }\n} \n \n \n"
},
{
"code": null,
"e": 1053,
"s": 876,
"text": "The Name property is associated with the name field. It is a good practice to use the same name for both the property and the private field, but with an uppercase first letter."
},
{
"code": null,
"e": 1108,
"s": 1053,
"text": "The get method returns the value of the variable name."
},
{
"code": null,
"e": 1227,
"s": 1108,
"text": "The set method assigns a value to the\nname variable. The value keyword represents the value we assign to the property."
},
{
"code": null,
"e": 1295,
"s": 1227,
"text": "If you don't fully understand it, take a look at the example below."
},
{
"code": null,
"e": 1388,
"s": 1295,
"text": "Now we can use the Name property to access and update the private field of the Person class:"
},
{
"code": null,
"e": 1696,
"s": 1388,
"text": "class Person\n{\n private string name; // field\n public string Name // property\n {\n get { return name; }\n set { name = value; }\n }\n}\n\nclass Program\n{\n static void Main(string[] args)\n {\n Person myObj = new Person();\n myObj.Name = \"Liam\";\n Console.WriteLine(myObj.Name);\n }\n}\n \n \n \n \n \n"
},
{
"code": null,
"e": 1716,
"s": 1696,
"text": "The output will be:"
},
{
"code": null,
"e": 1736,
"s": 1716,
"text": "\nTry it Yourself »\n"
},
{
"code": null,
"e": 1925,
"s": 1736,
"text": "C# also provides a way to use short-hand / automatic properties, where you do \nnot have to define the field for the property, and you only have to write get; \nand set; inside the property."
},
{
"code": null,
"e": 2046,
"s": 1925,
"text": "The following example will produce the same result as the example above. The only difference is that there is less code:"
},
{
"code": null,
"e": 2074,
"s": 2046,
"text": "Using automatic properties:"
},
{
"code": null,
"e": 2300,
"s": 2074,
"text": "class Person\n{\n public string Name // property\n { get; set; }\n}\n\nclass Program\n{\n static void Main(string[] args)\n {\n Person myObj = new Person();\n myObj.Name = \"Liam\";\n Console.WriteLine(myObj.Name);\n }\n}\n \n \n"
},
{
"code": null,
"e": 2320,
"s": 2300,
"text": "The output will be:"
},
{
"code": null,
"e": 2340,
"s": 2320,
"text": "\nTry it Yourself »\n"
},
{
"code": null,
"e": 2441,
"s": 2340,
"text": "Better control of class members (reduce the possibility of yourself (or others) to mess up the code)"
},
{
"code": null,
"e": 2551,
"s": 2441,
"text": "Fields can be made read-only (if you only use the get method), or write-only (if you only use the set method)"
},
{
"code": null,
"e": 2638,
"s": 2551,
"text": "Flexible: the programmer can change one part of the code without affecting other parts"
},
{
"code": null,
"e": 2665,
"s": 2638,
"text": "Increased security of data"
},
{
"code": null,
"e": 2698,
"s": 2665,
"text": "We just launchedW3Schools videos"
},
{
"code": null,
"e": 2740,
"s": 2698,
"text": "Get certifiedby completinga course today!"
},
{
"code": null,
"e": 2847,
"s": 2740,
"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": 2866,
"s": 2847,
"text": "[email protected]"
}
] |
How to overlay two images in Android to set an ImageView? | This example demonstrates how do I overlay two images In Android to set an ImageView.
Step 1 − Create a new project in Android Studio, go to File ⇒ New Project and fill all required details to create a new project.
Step 2 − Add the following code to res/layout/activity_main.xml.
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:padding="16dp"
tools:context=".MainActivity">
<Button
android:onClick="OverLayImage"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerHorizontal="true"
android:layout_marginTop="10dp"
android:id="@+id/btnOverlay"
android:text="Overlay Image"/>
<ImageView
android:id="@+id/imageView"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_below="@+id/btnOverlay"/>
</RelativeLayout>
Step 3 − Copy and paste two images which you want to overlay(Merge) in the res/drawable Then Create a drawable resource file (layer.xml) and add the following code,
<?xml version="1.0" encoding="utf-8"?>
<layer-list xmlns:android="http://schemas.android.com/apk/res/android">
<item android:drawable="@drawable/image" />
<item android:drawable="@drawable/image1" />
</layer-list>
Step 3 − Add the following code to src/MainActivity.java
import androidx.appcompat.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.ImageView;
public class MainActivity extends AppCompatActivity {
ImageView imageView;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
imageView = findViewById(R.id.imageView);
}
public void OverLayImage(View view) {
imageView.setImageDrawable(getResources().getDrawable(R.drawable.layer));
}
}
Step 4 − Add the following code to androidManifest.xml
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android" package="app.com.sample">
<application
android:allowBackup="true"
android:icon="@mipmap/ic_launcher"
android:label="@string/app_name"
android:roundIcon="@mipmap/ic_launcher_round"
android:supportsRtl="true"
android:theme="@style/AppTheme">
<activity android:name=".MainActivity">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
</manifest>
Let's try to run your application. I assume you have connected your actual Android Mobile device with your computer. To run the app from android studio, open one of your project's activity files and click Run icon from the toolbar. Select your mobile device as an option and then check your mobile device which will display your default screen −
Click here to download the project code. | [
{
"code": null,
"e": 1148,
"s": 1062,
"text": "This example demonstrates how do I overlay two images In Android to set an ImageView."
},
{
"code": null,
"e": 1277,
"s": 1148,
"text": "Step 1 − Create a new project in Android Studio, go to File ⇒ New Project and fill all required details to create a new project."
},
{
"code": null,
"e": 1342,
"s": 1277,
"text": "Step 2 − Add the following code to res/layout/activity_main.xml."
},
{
"code": null,
"e": 2131,
"s": 1342,
"text": "<?xml version=\"1.0\" encoding=\"utf-8\"?>\n<RelativeLayout xmlns:android=\"http://schemas.android.com/apk/res/android\"\n xmlns:tools=\"http://schemas.android.com/tools\"\n android:layout_width=\"match_parent\"\n android:layout_height=\"match_parent\"\n android:padding=\"16dp\"\n tools:context=\".MainActivity\">\n <Button\n android:onClick=\"OverLayImage\"\n android:layout_width=\"wrap_content\"\n android:layout_height=\"wrap_content\"\n android:layout_centerHorizontal=\"true\"\n android:layout_marginTop=\"10dp\"\n android:id=\"@+id/btnOverlay\"\n android:text=\"Overlay Image\"/>\n <ImageView\n android:id=\"@+id/imageView\"\n android:layout_width=\"match_parent\"\n android:layout_height=\"match_parent\"\n android:layout_below=\"@+id/btnOverlay\"/>\n</RelativeLayout>"
},
{
"code": null,
"e": 2296,
"s": 2131,
"text": "Step 3 − Copy and paste two images which you want to overlay(Merge) in the res/drawable Then Create a drawable resource file (layer.xml) and add the following code,"
},
{
"code": null,
"e": 2516,
"s": 2296,
"text": "<?xml version=\"1.0\" encoding=\"utf-8\"?>\n<layer-list xmlns:android=\"http://schemas.android.com/apk/res/android\">\n <item android:drawable=\"@drawable/image\" />\n <item android:drawable=\"@drawable/image1\" />\n</layer-list>"
},
{
"code": null,
"e": 2573,
"s": 2516,
"text": "Step 3 − Add the following code to src/MainActivity.java"
},
{
"code": null,
"e": 3123,
"s": 2573,
"text": "import androidx.appcompat.app.AppCompatActivity;\nimport android.os.Bundle;\nimport android.view.View;\nimport android.widget.ImageView;\npublic class MainActivity extends AppCompatActivity {\n ImageView imageView;\n @Override\n protected void onCreate(Bundle savedInstanceState) {\n super.onCreate(savedInstanceState);\n setContentView(R.layout.activity_main);\n imageView = findViewById(R.id.imageView);\n }\n public void OverLayImage(View view) {\n imageView.setImageDrawable(getResources().getDrawable(R.drawable.layer));\n }\n}"
},
{
"code": null,
"e": 3178,
"s": 3123,
"text": "Step 4 − Add the following code to androidManifest.xml"
},
{
"code": null,
"e": 3848,
"s": 3178,
"text": "<?xml version=\"1.0\" encoding=\"utf-8\"?>\n<manifest xmlns:android=\"http://schemas.android.com/apk/res/android\" package=\"app.com.sample\">\n <application\n android:allowBackup=\"true\"\n android:icon=\"@mipmap/ic_launcher\"\n android:label=\"@string/app_name\"\n android:roundIcon=\"@mipmap/ic_launcher_round\"\n android:supportsRtl=\"true\"\n android:theme=\"@style/AppTheme\">\n <activity android:name=\".MainActivity\">\n <intent-filter>\n <action android:name=\"android.intent.action.MAIN\" />\n <category android:name=\"android.intent.category.LAUNCHER\" />\n </intent-filter>\n </activity>\n </application>\n</manifest>"
},
{
"code": null,
"e": 4195,
"s": 3848,
"text": "Let's try to run your application. I assume you have connected your actual Android Mobile device with your computer. To run the app from android studio, open one of your project's activity files and click Run icon from the toolbar. Select your mobile device as an option and then check your mobile device which will display your default screen −"
},
{
"code": null,
"e": 4236,
"s": 4195,
"text": "Click here to download the project code."
}
] |
MATLAB - Algebra - GeeksforGeeks | 09 Feb, 2021
Algebra is all about the study of mathematical symbols and rules for manipulating these symbols. Here variables are used to store/represent quantities. In MATLAB, there are certain in-built methods to solve algebra equations. Roots of equations, solving for x, simplifying an expression are some things we can perform in MATLAB.
Following are some functions of MATLAB to solve algebra:
solve()
roots()
expand()
simplify()
factor()
Solving Equations: To solve an equation for finding x value or if the equation contains multiple variables, we can solve for a particular variable.
Syntax: solve(equation,variable)
Here default variable will be x.
Example 1: This example illustrates the solve() function for the latest versions of MATLAB.
MATLAB
% MATLAB program to illustrate% solve() function syms x % Below eqn is nothing but% x-28 = 0eqn = x-28 == 0;S = solve(eqn,x); disp(S)
Output:
28
Example 2:
MATLAB
% MATLAB program to illustrate% solve() function syms x y z% Here solving the equation for yeqn = solve(x-y+28*z^2,y);disp(eqn)
Output:
y =
28*z^2 + x
Finding Roots: Using roots() and solve() functions, one can find roots using an equation or coefficients of a variable in a particular equation. Let’s see an example to get a better understanding
Syntax: roots(p)
where p = column vector
Example 1:
MATLAB
% MATLAB program to find roots% of a quadratic equation % Finding roots for the equation 'x-28=0'roots([1,-28]) % Finding roots for the equation 'x^2-7*x+12=0'roots([1,-7,12])
Output:
ans =
28
ans =
4
3
Example 2:
MATLAB
% MATLAB program to find roots% using solve function syms x a = solve(x-28)b = solve(x^2 -7*x + 12) % The solve function can also% higher order equationsc = solve((x-3)^2*(x-7)==0)
Output:
a =
28
b =
3
4
c =
3
3
7
Factorization and Simplification: To find factors of an expression, factor() function is used. And to simplify an expression, simplify() function is used. When you work with many symbolic functions, you should declare that your variables are symbolic.
factor Syntax:
factor(expression)
or
factor(integer)
simplify Syntax:
simplify(expression)
If an expression is passed into factor() function, then it returns an array of factors. If an integer is passed into factor() function, then it returns prime factorization of the given integer.
Example 1:
MATLAB
% MATLAB program to illustrate% factor function to find factors syms xsyms y % Finding prime factorization of% given integerfactor(28) % Finding factors of% given expressionsfactor(x^3-y^3)factor(x^6-1)
Output:
ans =
2 2 7
ans =
(x - y)*(x^2 + x*y + y^2)
ans =
(x - 1)*(x + 1)*(x^2 + x + 1)*(x^2 - x + 1)
Example 2: The simplify() function performs algebraic simplification of the given expression.
MATLAB
% MATLAB program to illustrate% factor function a = simplify(sin(x)^2 + cos(x)^2) b = simplify((x^4-16)/(x^2-4))
Output:
a =
1
b =
x^2 + 4
Expand Function: Using the expand() function, we can expand given expressions and simplify inputs of functions using identities.
Syntax:
expand(expression)
Example:
MATLAB
% MATLAB function to illustrate expand()% function and expand the given polynomials expand((x - 2)*(x - 4)) % Simplifying inputs of functions% by using identitiesexpand(cos(x + y))expand(sin(2*x))
Output:
ans =
x^2 - 6*x + 8
ans =
cos(x)*cos(y) - sin(x)*sin(y)
ans =
2*cos(x)*sin(x)
Note:
For the latest versions of MATLAB, solve() function parameter should not be a string. Instead, use symbolic variables in equations.
In the latest versions of MATLAB, equation parameter of solve() should be like x-28==0 instead of x-28=0. We should use conditional operator (i.e ==) instead of assignment operator (i.e =)
In MATLAB editor, we don’t need to write print functions unless you put a semicolon(;) at the end of a command.
While working with numerous symbolic functions, we must declare symbolic variables.
While solving polynomials default solving variable will be x, unless you specify any other variable.
arorakashish0911
MATLAB
Advanced Computer Subject
Programming Language
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
ML | Linear Regression
Decision Tree
Copying Files to and from Docker Containers
System Design Tutorial
Python | Decision tree implementation
Arrow operator -> in C/C++ with Examples
Modulo Operator (%) in C/C++ with Examples
Structures in C++
Differences between Procedural and Object Oriented Programming
Top 10 Programming Languages to Learn in 2022 | [
{
"code": null,
"e": 24486,
"s": 24458,
"text": "\n09 Feb, 2021"
},
{
"code": null,
"e": 24815,
"s": 24486,
"text": "Algebra is all about the study of mathematical symbols and rules for manipulating these symbols. Here variables are used to store/represent quantities. In MATLAB, there are certain in-built methods to solve algebra equations. Roots of equations, solving for x, simplifying an expression are some things we can perform in MATLAB."
},
{
"code": null,
"e": 24872,
"s": 24815,
"text": "Following are some functions of MATLAB to solve algebra:"
},
{
"code": null,
"e": 24880,
"s": 24872,
"text": "solve()"
},
{
"code": null,
"e": 24888,
"s": 24880,
"text": "roots()"
},
{
"code": null,
"e": 24897,
"s": 24888,
"text": "expand()"
},
{
"code": null,
"e": 24908,
"s": 24897,
"text": "simplify()"
},
{
"code": null,
"e": 24917,
"s": 24908,
"text": "factor()"
},
{
"code": null,
"e": 25065,
"s": 24917,
"text": "Solving Equations: To solve an equation for finding x value or if the equation contains multiple variables, we can solve for a particular variable."
},
{
"code": null,
"e": 25098,
"s": 25065,
"text": "Syntax: solve(equation,variable)"
},
{
"code": null,
"e": 25131,
"s": 25098,
"text": "Here default variable will be x."
},
{
"code": null,
"e": 25223,
"s": 25131,
"text": "Example 1: This example illustrates the solve() function for the latest versions of MATLAB."
},
{
"code": null,
"e": 25230,
"s": 25223,
"text": "MATLAB"
},
{
"code": "% MATLAB program to illustrate% solve() function syms x % Below eqn is nothing but% x-28 = 0eqn = x-28 == 0;S = solve(eqn,x); disp(S)",
"e": 25364,
"s": 25230,
"text": null
},
{
"code": null,
"e": 25376,
"s": 25364,
"text": " Output: "
},
{
"code": null,
"e": 25379,
"s": 25376,
"text": "28"
},
{
"code": null,
"e": 25393,
"s": 25379,
"text": " Example 2: "
},
{
"code": null,
"e": 25400,
"s": 25393,
"text": "MATLAB"
},
{
"code": "% MATLAB program to illustrate% solve() function syms x y z% Here solving the equation for yeqn = solve(x-y+28*z^2,y);disp(eqn)",
"e": 25528,
"s": 25400,
"text": null
},
{
"code": null,
"e": 25538,
"s": 25528,
"text": " Output: "
},
{
"code": null,
"e": 25554,
"s": 25538,
"text": "y = \n28*z^2 + x"
},
{
"code": null,
"e": 25752,
"s": 25554,
"text": "Finding Roots: Using roots() and solve() functions, one can find roots using an equation or coefficients of a variable in a particular equation. Let’s see an example to get a better understanding "
},
{
"code": null,
"e": 25793,
"s": 25752,
"text": "Syntax: roots(p)\nwhere p = column vector"
},
{
"code": null,
"e": 25806,
"s": 25793,
"text": "Example 1: "
},
{
"code": null,
"e": 25813,
"s": 25806,
"text": "MATLAB"
},
{
"code": "% MATLAB program to find roots% of a quadratic equation % Finding roots for the equation 'x-28=0'roots([1,-28]) % Finding roots for the equation 'x^2-7*x+12=0'roots([1,-7,12])",
"e": 25989,
"s": 25813,
"text": null
},
{
"code": null,
"e": 25999,
"s": 25989,
"text": " Output: "
},
{
"code": null,
"e": 26039,
"s": 25999,
"text": "ans =\n\n 28\n \nans =\n\n 4\n 3"
},
{
"code": null,
"e": 26051,
"s": 26039,
"text": "Example 2: "
},
{
"code": null,
"e": 26058,
"s": 26051,
"text": "MATLAB"
},
{
"code": "% MATLAB program to find roots% using solve function syms x a = solve(x-28)b = solve(x^2 -7*x + 12) % The solve function can also% higher order equationsc = solve((x-3)^2*(x-7)==0)",
"e": 26239,
"s": 26058,
"text": null
},
{
"code": null,
"e": 26249,
"s": 26239,
"text": " Output: "
},
{
"code": null,
"e": 26291,
"s": 26249,
"text": "a =\n \n28\n \n \nb =\n \n 3\n 4\n \nc =\n \n 3\n 3\n 7"
},
{
"code": null,
"e": 26546,
"s": 26291,
"text": " Factorization and Simplification: To find factors of an expression, factor() function is used. And to simplify an expression, simplify() function is used. When you work with many symbolic functions, you should declare that your variables are symbolic. "
},
{
"code": null,
"e": 26647,
"s": 26546,
"text": "factor Syntax:\nfactor(expression)\n or\nfactor(integer)\n\n \nsimplify Syntax:\nsimplify(expression)"
},
{
"code": null,
"e": 26841,
"s": 26647,
"text": "If an expression is passed into factor() function, then it returns an array of factors. If an integer is passed into factor() function, then it returns prime factorization of the given integer."
},
{
"code": null,
"e": 26853,
"s": 26841,
"text": "Example 1: "
},
{
"code": null,
"e": 26860,
"s": 26853,
"text": "MATLAB"
},
{
"code": "% MATLAB program to illustrate% factor function to find factors syms xsyms y % Finding prime factorization of% given integerfactor(28) % Finding factors of% given expressionsfactor(x^3-y^3)factor(x^6-1)",
"e": 27063,
"s": 26860,
"text": null
},
{
"code": null,
"e": 27074,
"s": 27063,
"text": " Output: "
},
{
"code": null,
"e": 27193,
"s": 27074,
"text": "ans =\n\n 2 2 7\n \nans =\n \n(x - y)*(x^2 + x*y + y^2)\n\nans =\n \n(x - 1)*(x + 1)*(x^2 + x + 1)*(x^2 - x + 1)"
},
{
"code": null,
"e": 27288,
"s": 27193,
"text": "Example 2: The simplify() function performs algebraic simplification of the given expression. "
},
{
"code": null,
"e": 27295,
"s": 27288,
"text": "MATLAB"
},
{
"code": "% MATLAB program to illustrate% factor function a = simplify(sin(x)^2 + cos(x)^2) b = simplify((x^4-16)/(x^2-4))",
"e": 27410,
"s": 27295,
"text": null
},
{
"code": null,
"e": 27420,
"s": 27410,
"text": " Output: "
},
{
"code": null,
"e": 27444,
"s": 27420,
"text": "a =\n \n1\n \nb =\n \nx^2 + 4"
},
{
"code": null,
"e": 27574,
"s": 27444,
"text": " Expand Function: Using the expand() function, we can expand given expressions and simplify inputs of functions using identities."
},
{
"code": null,
"e": 27602,
"s": 27574,
"text": "Syntax:\nexpand(expression) "
},
{
"code": null,
"e": 27612,
"s": 27602,
"text": "Example: "
},
{
"code": null,
"e": 27619,
"s": 27612,
"text": "MATLAB"
},
{
"code": "% MATLAB function to illustrate expand()% function and expand the given polynomials expand((x - 2)*(x - 4)) % Simplifying inputs of functions% by using identitiesexpand(cos(x + y))expand(sin(2*x))",
"e": 27816,
"s": 27619,
"text": null
},
{
"code": null,
"e": 27825,
"s": 27816,
"text": " Output:"
},
{
"code": null,
"e": 27917,
"s": 27825,
"text": "ans =\n \nx^2 - 6*x + 8\n \n \nans =\n \ncos(x)*cos(y) - sin(x)*sin(y)\n \n \nans =\n \n2*cos(x)*sin(x)"
},
{
"code": null,
"e": 27924,
"s": 27917,
"text": "Note: "
},
{
"code": null,
"e": 28056,
"s": 27924,
"text": "For the latest versions of MATLAB, solve() function parameter should not be a string. Instead, use symbolic variables in equations."
},
{
"code": null,
"e": 28245,
"s": 28056,
"text": "In the latest versions of MATLAB, equation parameter of solve() should be like x-28==0 instead of x-28=0. We should use conditional operator (i.e ==) instead of assignment operator (i.e =)"
},
{
"code": null,
"e": 28357,
"s": 28245,
"text": "In MATLAB editor, we don’t need to write print functions unless you put a semicolon(;) at the end of a command."
},
{
"code": null,
"e": 28441,
"s": 28357,
"text": "While working with numerous symbolic functions, we must declare symbolic variables."
},
{
"code": null,
"e": 28542,
"s": 28441,
"text": "While solving polynomials default solving variable will be x, unless you specify any other variable."
},
{
"code": null,
"e": 28561,
"s": 28544,
"text": "arorakashish0911"
},
{
"code": null,
"e": 28568,
"s": 28561,
"text": "MATLAB"
},
{
"code": null,
"e": 28594,
"s": 28568,
"text": "Advanced Computer Subject"
},
{
"code": null,
"e": 28615,
"s": 28594,
"text": "Programming Language"
},
{
"code": null,
"e": 28713,
"s": 28615,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 28736,
"s": 28713,
"text": "ML | Linear Regression"
},
{
"code": null,
"e": 28750,
"s": 28736,
"text": "Decision Tree"
},
{
"code": null,
"e": 28794,
"s": 28750,
"text": "Copying Files to and from Docker Containers"
},
{
"code": null,
"e": 28817,
"s": 28794,
"text": "System Design Tutorial"
},
{
"code": null,
"e": 28855,
"s": 28817,
"text": "Python | Decision tree implementation"
},
{
"code": null,
"e": 28896,
"s": 28855,
"text": "Arrow operator -> in C/C++ with Examples"
},
{
"code": null,
"e": 28939,
"s": 28896,
"text": "Modulo Operator (%) in C/C++ with Examples"
},
{
"code": null,
"e": 28957,
"s": 28939,
"text": "Structures in C++"
},
{
"code": null,
"e": 29020,
"s": 28957,
"text": "Differences between Procedural and Object Oriented Programming"
}
] |
Split a number into individual digits using JavaScript | 24 Jan, 2022
In this article, we will get some input from user by using <input> element and the task is to split the given number into the individual digits with the help of JavaScript. There two approaches that are discussed below:Approach 1: First take the element from input element in string format (No need to convert it to Number) and declare an empty array(var res). Visit every character of the string in a loop on the length of the string and push the character in the array(res) by using push() method.
Example: This example implements the above approach.
html
<!DOCTYPE HTML><html> <head> <title> Split a number into individual digits using JavaScript </title> <style> body { text-align: center; } h1 { color: green; } #geeks { color: green; font-size: 29px; font-weight: bold; } </style></head> <body> <h1>GeeksforGeeks</h1> <p> Type the number and click on the button to perform the operation. </p> Type here:<input id = "input" /> <br><br> <button onclick = "GFG_Fun();"> click here </button> <p id = "geeks"></p> <script> var down = document.getElementById('geeks'); function GFG_Fun() { var str = document.getElementById('input').value; res = []; for (var i = 0, len = str.length; i < len; i += 1) { res.push(+str.charAt(i)); } down.innerHTML = "[" + res + "]"; } </script></body> </html>
Output:
Approach 2: First take the element from input element in string format (No need to convert it to Number) and declare an empty array(var res). Split the string by using split() method on (”) and store the splitted result in the array(str).
Example: This example implements the above approach.
html
<!DOCTYPE HTML><html> <head> <title> Split a number into individual digits </title> <style> body { text-align: center; } h1 { color: green; } #geeks { color: green; font-size: 29px; font-weight: bold; } </style></head> <body> <h1>GeeksforGeeks</h1> <p> Type the number and click on the button to perform the operation. </p> Type here: <input id="input" /> <br><br> <button onclick="GFG_Fun();"> click here </button> <p id="geeks"></p> <script> var down = document.getElementById('geeks'); function GFG_Fun() { var n = document.getElementById('input').value; var str = n.split(''); down.innerHTML = "[" + str + "]"; } </script></body> </html>
Output:
saurabh1990aror
JavaScript-Misc
JavaScript-Numbers
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
Differences between Functional Components and Class Components in React
Remove elements from a JavaScript Array
Roadmap to Learn JavaScript For Beginners
Difference Between PUT and PATCH Request
Installation of Node.js on Linux
Top 10 Projects For Beginners To Practice HTML and CSS Skills
Difference between var, let and const keywords in JavaScript
How to insert spaces/tabs in text using HTML/CSS?
How to fetch data from an API in ReactJS ? | [
{
"code": null,
"e": 52,
"s": 24,
"text": "\n24 Jan, 2022"
},
{
"code": null,
"e": 553,
"s": 52,
"text": "In this article, we will get some input from user by using <input> element and the task is to split the given number into the individual digits with the help of JavaScript. There two approaches that are discussed below:Approach 1: First take the element from input element in string format (No need to convert it to Number) and declare an empty array(var res). Visit every character of the string in a loop on the length of the string and push the character in the array(res) by using push() method. "
},
{
"code": null,
"e": 607,
"s": 553,
"text": "Example: This example implements the above approach. "
},
{
"code": null,
"e": 612,
"s": 607,
"text": "html"
},
{
"code": "<!DOCTYPE HTML><html> <head> <title> Split a number into individual digits using JavaScript </title> <style> body { text-align: center; } h1 { color: green; } #geeks { color: green; font-size: 29px; font-weight: bold; } </style></head> <body> <h1>GeeksforGeeks</h1> <p> Type the number and click on the button to perform the operation. </p> Type here:<input id = \"input\" /> <br><br> <button onclick = \"GFG_Fun();\"> click here </button> <p id = \"geeks\"></p> <script> var down = document.getElementById('geeks'); function GFG_Fun() { var str = document.getElementById('input').value; res = []; for (var i = 0, len = str.length; i < len; i += 1) { res.push(+str.charAt(i)); } down.innerHTML = \"[\" + res + \"]\"; } </script></body> </html> ",
"e": 1706,
"s": 612,
"text": null
},
{
"code": null,
"e": 1715,
"s": 1706,
"text": "Output: "
},
{
"code": null,
"e": 1955,
"s": 1715,
"text": "Approach 2: First take the element from input element in string format (No need to convert it to Number) and declare an empty array(var res). Split the string by using split() method on (”) and store the splitted result in the array(str). "
},
{
"code": null,
"e": 2009,
"s": 1955,
"text": "Example: This example implements the above approach. "
},
{
"code": null,
"e": 2014,
"s": 2009,
"text": "html"
},
{
"code": "<!DOCTYPE HTML><html> <head> <title> Split a number into individual digits </title> <style> body { text-align: center; } h1 { color: green; } #geeks { color: green; font-size: 29px; font-weight: bold; } </style></head> <body> <h1>GeeksforGeeks</h1> <p> Type the number and click on the button to perform the operation. </p> Type here: <input id=\"input\" /> <br><br> <button onclick=\"GFG_Fun();\"> click here </button> <p id=\"geeks\"></p> <script> var down = document.getElementById('geeks'); function GFG_Fun() { var n = document.getElementById('input').value; var str = n.split(''); down.innerHTML = \"[\" + str + \"]\"; } </script></body> </html>",
"e": 2931,
"s": 2014,
"text": null
},
{
"code": null,
"e": 2940,
"s": 2931,
"text": "Output: "
},
{
"code": null,
"e": 2956,
"s": 2940,
"text": "saurabh1990aror"
},
{
"code": null,
"e": 2972,
"s": 2956,
"text": "JavaScript-Misc"
},
{
"code": null,
"e": 2991,
"s": 2972,
"text": "JavaScript-Numbers"
},
{
"code": null,
"e": 3002,
"s": 2991,
"text": "JavaScript"
},
{
"code": null,
"e": 3019,
"s": 3002,
"text": "Web Technologies"
},
{
"code": null,
"e": 3046,
"s": 3019,
"text": "Web technologies Questions"
},
{
"code": null,
"e": 3144,
"s": 3046,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 3205,
"s": 3144,
"text": "Difference between var, let and const keywords in JavaScript"
},
{
"code": null,
"e": 3277,
"s": 3205,
"text": "Differences between Functional Components and Class Components in React"
},
{
"code": null,
"e": 3317,
"s": 3277,
"text": "Remove elements from a JavaScript Array"
},
{
"code": null,
"e": 3359,
"s": 3317,
"text": "Roadmap to Learn JavaScript For Beginners"
},
{
"code": null,
"e": 3400,
"s": 3359,
"text": "Difference Between PUT and PATCH Request"
},
{
"code": null,
"e": 3433,
"s": 3400,
"text": "Installation of Node.js on Linux"
},
{
"code": null,
"e": 3495,
"s": 3433,
"text": "Top 10 Projects For Beginners To Practice HTML and CSS Skills"
},
{
"code": null,
"e": 3556,
"s": 3495,
"text": "Difference between var, let and const keywords in JavaScript"
},
{
"code": null,
"e": 3606,
"s": 3556,
"text": "How to insert spaces/tabs in text using HTML/CSS?"
}
] |
HTML | <button> name Attribute | 18 May, 2019
The <button> name attribute is used to specify the name attribute of <button> element. It is used to reference the form-data after submitting the form or to reference the element in a JavaScript.
Syntax:
<button name="name">
Attribute Values: It contains a single value name which describes the name of the <button> element.
Example:
<!DOCTYPE html> <html> <head> <title> HTML button name Attribute </title> </head> <body> <h1>GeeksforGeeks</h1> <h3>HTML button name Attribute</h3> <form action="#" method="get"> Username: <input type="text" name="uname"> <br><br> Password: <input type="password" name="pwd"> <br><br> <button type="submit" value="submit"> Submit </button> </form> </body> </html>
Output:
Supported Browsers: The browser supported by HTML <button> name attribute are listed below:
Google Chrome
Internet Explorer
Firefox
Safari
Opera
HTML-Attributes
HTML
Web Technologies
HTML
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to update Node.js and NPM to next version ?
REST API (Introduction)
Types of CSS (Cascading Style Sheet)
HTTP headers | Content-Type
Design a Tribute Page using HTML & CSS
Installation of Node.js on Linux
Difference between var, let and const keywords in JavaScript
How to fetch data from an API in ReactJS ?
Differences between Functional Components and Class Components in React
Remove elements from a JavaScript Array | [
{
"code": null,
"e": 28,
"s": 0,
"text": "\n18 May, 2019"
},
{
"code": null,
"e": 224,
"s": 28,
"text": "The <button> name attribute is used to specify the name attribute of <button> element. It is used to reference the form-data after submitting the form or to reference the element in a JavaScript."
},
{
"code": null,
"e": 232,
"s": 224,
"text": "Syntax:"
},
{
"code": null,
"e": 253,
"s": 232,
"text": "<button name=\"name\">"
},
{
"code": null,
"e": 353,
"s": 253,
"text": "Attribute Values: It contains a single value name which describes the name of the <button> element."
},
{
"code": null,
"e": 362,
"s": 353,
"text": "Example:"
},
{
"code": "<!DOCTYPE html> <html> <head> <title> HTML button name Attribute </title> </head> <body> <h1>GeeksforGeeks</h1> <h3>HTML button name Attribute</h3> <form action=\"#\" method=\"get\"> Username: <input type=\"text\" name=\"uname\"> <br><br> Password: <input type=\"password\" name=\"pwd\"> <br><br> <button type=\"submit\" value=\"submit\"> Submit </button> </form> </body> </html> ",
"e": 979,
"s": 362,
"text": null
},
{
"code": null,
"e": 987,
"s": 979,
"text": "Output:"
},
{
"code": null,
"e": 1079,
"s": 987,
"text": "Supported Browsers: The browser supported by HTML <button> name attribute are listed below:"
},
{
"code": null,
"e": 1093,
"s": 1079,
"text": "Google Chrome"
},
{
"code": null,
"e": 1111,
"s": 1093,
"text": "Internet Explorer"
},
{
"code": null,
"e": 1119,
"s": 1111,
"text": "Firefox"
},
{
"code": null,
"e": 1126,
"s": 1119,
"text": "Safari"
},
{
"code": null,
"e": 1132,
"s": 1126,
"text": "Opera"
},
{
"code": null,
"e": 1148,
"s": 1132,
"text": "HTML-Attributes"
},
{
"code": null,
"e": 1153,
"s": 1148,
"text": "HTML"
},
{
"code": null,
"e": 1170,
"s": 1153,
"text": "Web Technologies"
},
{
"code": null,
"e": 1175,
"s": 1170,
"text": "HTML"
},
{
"code": null,
"e": 1273,
"s": 1175,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 1321,
"s": 1273,
"text": "How to update Node.js and NPM to next version ?"
},
{
"code": null,
"e": 1345,
"s": 1321,
"text": "REST API (Introduction)"
},
{
"code": null,
"e": 1382,
"s": 1345,
"text": "Types of CSS (Cascading Style Sheet)"
},
{
"code": null,
"e": 1410,
"s": 1382,
"text": "HTTP headers | Content-Type"
},
{
"code": null,
"e": 1449,
"s": 1410,
"text": "Design a Tribute Page using HTML & CSS"
},
{
"code": null,
"e": 1482,
"s": 1449,
"text": "Installation of Node.js on Linux"
},
{
"code": null,
"e": 1543,
"s": 1482,
"text": "Difference between var, let and const keywords in JavaScript"
},
{
"code": null,
"e": 1586,
"s": 1543,
"text": "How to fetch data from an API in ReactJS ?"
},
{
"code": null,
"e": 1658,
"s": 1586,
"text": "Differences between Functional Components and Class Components in React"
}
] |
Shortest Superstring Problem | Set 2 (Using Set Cover) | 29 Feb, 2016
Given a set of n strings S, find the smallest string that contains each string in the given set as substring. We may assume that no string in arr[] is substring of another string.
Examples:
Input: S = {"001", "01101", "010"}
Output: 0011010
Input: S = {"geeks", "quiz", "for"}
Output: geeksquizfor
Input: S = {"catg", "ctaagt", "gcta", "ttca", "atgcatc"}
Output: gctaagttcatgcatc
In the previous post, we have discussed a solution that is proved to be 4 approximate (conjectured as 2 approximate).In this post, a solution is discussed that can be proved as 2Hn approximate. where Hn = 1 + 1/2 + 1/3 + ... 1/n. The idea is to transform Shortest Superstring problem into Set Cover problem (The Set cover problem is given some subsets of a universe and every give subset has an associated cost. The task is to find the lowest cost set of given subsets such that all elements of universe are covered). For a Set Cover problem, we need to have a universe and subsets of universe with their associated costs.
Below are steps to transform Shortest Superstring into Set Cover.
1) Let S be the set of given strings.
S = {s1, s2, ... sn}
2) Universe for Set Cover problem is S (We need
to find a superstring that has every string
as substring)
3) Let us initialize subsets to be considered for universe as
Subsets = {{s1}, {s2}, ... {sn}}
Cost of every subset is length of string in it.
3) For all pairs of strings si and sj in S,
If si and sj overlap
a) Construct a string rijk where k is
the maximum overlap between the two.
b) Add the set represented by rijk to Subsets,
i.e., Subsets = Subsets U Set(rijk)
The set represented by rijk is the set
of all strings which are substring of it.
Cost of the subset is length of rijk.
4) Now problem is transformed to Set Cover, we can
run Greedy Set Cover approximate algorithm to find
set cover of S using Subsets. Cost of every element in
Subsets is length of string in it.
Example:
S = {s1, s2, s3}.
s1 = "001"
s2 = "01101"
s3 = "010"
[Combination of s1 and s2 with 2 overlapping characters]
r122 = 001101
[Combination of s1 and s3 with 2 overlapping characters]
r132 = 0010
Similarly,
r232 = 011010
r311 = 01001
r321 = 0101101
Now set cover problem becomes as following:
Universe to cover is {s1, s2, s3}
Subsets of the universe and their costs :
{s1}, cost 3 (length of s1)
{s2}, cost 5 (length of s2)
{s3}, cost 5 (length of s3)
set(r122), cost 6 (length of r122)
The set r122 represents all strings which are
substrings of r122.
Therefore set(r122) = {s1, s2}
set(r132), cost 3 (length of r132)
The subset r132 represents all strings which are
substrings of r132
Therefore set(r132) = {s1, s3}
Similarly there are more subsets for set(r232),
set(r311), and set(r321).
So we have a set cover problem with universe and subsets
of universe with costs associated with every subset.
We have discussed that an instance of Shortest Superstring problem can be transformed into an instance of Set Cover problem in polynomial time.
Refer this for proof of the fact that Set Cover based algorithm is 2Hn approximate.
Reference:http://www.cs.dartmouth.edu/~ac/Teach/CS105-Winter05/Notes/wan-ba-notes.pdfhttp://fileadmin.cs.lth.se/cs/Personal/Andrzej_Lingas/superstring.pdfhttp://math.mit.edu/~goemans/18434S06/superstring-lele.pdf
This article is contributed Dheeraj Gupta. Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above
Algorithms
Algorithms
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
DSA Sheet by Love Babbar
SDE SHEET - A Complete Guide for SDE Preparation
What is Hashing | A Complete Tutorial
Understanding Time Complexity with Simple Examples
Find if there is a path between two vertices in an undirected graph
What is Algorithm | Introduction to Algorithms
Analysis of Algorithms | Set 2 (Worst, Average and Best Cases)
Analysis of Algorithms | Set 3 (Asymptotic Notations)
Recursive Practice Problems with Solutions
How to Start Learning DSA? | [
{
"code": null,
"e": 52,
"s": 24,
"text": "\n29 Feb, 2016"
},
{
"code": null,
"e": 232,
"s": 52,
"text": "Given a set of n strings S, find the smallest string that contains each string in the given set as substring. We may assume that no string in arr[] is substring of another string."
},
{
"code": null,
"e": 242,
"s": 232,
"text": "Examples:"
},
{
"code": null,
"e": 439,
"s": 242,
"text": "Input: S = {\"001\", \"01101\", \"010\"}\nOutput: 0011010 \n\nInput: S = {\"geeks\", \"quiz\", \"for\"}\nOutput: geeksquizfor\n\nInput: S = {\"catg\", \"ctaagt\", \"gcta\", \"ttca\", \"atgcatc\"}\nOutput: gctaagttcatgcatc"
},
{
"code": null,
"e": 1062,
"s": 439,
"text": "In the previous post, we have discussed a solution that is proved to be 4 approximate (conjectured as 2 approximate).In this post, a solution is discussed that can be proved as 2Hn approximate. where Hn = 1 + 1/2 + 1/3 + ... 1/n. The idea is to transform Shortest Superstring problem into Set Cover problem (The Set cover problem is given some subsets of a universe and every give subset has an associated cost. The task is to find the lowest cost set of given subsets such that all elements of universe are covered). For a Set Cover problem, we need to have a universe and subsets of universe with their associated costs."
},
{
"code": null,
"e": 1128,
"s": 1062,
"text": "Below are steps to transform Shortest Superstring into Set Cover."
},
{
"code": null,
"e": 2069,
"s": 1128,
"text": "1) Let S be the set of given strings.\n S = {s1, s2, ... sn}\n\n2) Universe for Set Cover problem is S (We need\n to find a superstring that has every string\n as substring)\n\n3) Let us initialize subsets to be considered for universe as\n Subsets = {{s1}, {s2}, ... {sn}}\n Cost of every subset is length of string in it.\n\n3) For all pairs of strings si and sj in S,\n If si and sj overlap\n a) Construct a string rijk where k is\n the maximum overlap between the two.\n b) Add the set represented by rijk to Subsets,\n i.e., Subsets = Subsets U Set(rijk)\n The set represented by rijk is the set \n of all strings which are substring of it.\n Cost of the subset is length of rijk.\n\n4) Now problem is transformed to Set Cover, we can \n run Greedy Set Cover approximate algorithm to find\n set cover of S using Subsets. Cost of every element in\n Subsets is length of string in it.\n"
},
{
"code": null,
"e": 2078,
"s": 2069,
"text": "Example:"
},
{
"code": null,
"e": 2994,
"s": 2078,
"text": "S = {s1, s2, s3}.\ns1 = \"001\"\ns2 = \"01101\"\ns3 = \"010\"\n\n[Combination of s1 and s2 with 2 overlapping characters]\nr122 = 001101 \n\n[Combination of s1 and s3 with 2 overlapping characters]\nr132 = 0010 \n\nSimilarly,\nr232 = 011010\nr311 = 01001\nr321 = 0101101\n\nNow set cover problem becomes as following:\n\nUniverse to cover is {s1, s2, s3}\n\nSubsets of the universe and their costs :\n\n{s1}, cost 3 (length of s1)\n{s2}, cost 5 (length of s2)\n{s3}, cost 5 (length of s3)\n\nset(r122), cost 6 (length of r122)\nThe set r122 represents all strings which are\nsubstrings of r122. \nTherefore set(r122) = {s1, s2}\n\nset(r132), cost 3 (length of r132)\nThe subset r132 represents all strings which are\nsubstrings of r132\nTherefore set(r132) = {s1, s3}\n\nSimilarly there are more subsets for set(r232), \nset(r311), and set(r321).\n\nSo we have a set cover problem with universe and subsets\nof universe with costs associated with every subset.\n"
},
{
"code": null,
"e": 3138,
"s": 2994,
"text": "We have discussed that an instance of Shortest Superstring problem can be transformed into an instance of Set Cover problem in polynomial time."
},
{
"code": null,
"e": 3222,
"s": 3138,
"text": "Refer this for proof of the fact that Set Cover based algorithm is 2Hn approximate."
},
{
"code": null,
"e": 3435,
"s": 3222,
"text": "Reference:http://www.cs.dartmouth.edu/~ac/Teach/CS105-Winter05/Notes/wan-ba-notes.pdfhttp://fileadmin.cs.lth.se/cs/Personal/Andrzej_Lingas/superstring.pdfhttp://math.mit.edu/~goemans/18434S06/superstring-lele.pdf"
},
{
"code": null,
"e": 3602,
"s": 3435,
"text": "This article is contributed Dheeraj Gupta. Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above"
},
{
"code": null,
"e": 3613,
"s": 3602,
"text": "Algorithms"
},
{
"code": null,
"e": 3624,
"s": 3613,
"text": "Algorithms"
},
{
"code": null,
"e": 3722,
"s": 3624,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 3747,
"s": 3722,
"text": "DSA Sheet by Love Babbar"
},
{
"code": null,
"e": 3796,
"s": 3747,
"text": "SDE SHEET - A Complete Guide for SDE Preparation"
},
{
"code": null,
"e": 3834,
"s": 3796,
"text": "What is Hashing | A Complete Tutorial"
},
{
"code": null,
"e": 3885,
"s": 3834,
"text": "Understanding Time Complexity with Simple Examples"
},
{
"code": null,
"e": 3953,
"s": 3885,
"text": "Find if there is a path between two vertices in an undirected graph"
},
{
"code": null,
"e": 4000,
"s": 3953,
"text": "What is Algorithm | Introduction to Algorithms"
},
{
"code": null,
"e": 4063,
"s": 4000,
"text": "Analysis of Algorithms | Set 2 (Worst, Average and Best Cases)"
},
{
"code": null,
"e": 4117,
"s": 4063,
"text": "Analysis of Algorithms | Set 3 (Asymptotic Notations)"
},
{
"code": null,
"e": 4160,
"s": 4117,
"text": "Recursive Practice Problems with Solutions"
}
] |
Partition array into two subarrays with every element in the right subarray strictly greater than every element in left subarray | 11 Jun, 2021
Given an array arr[] consisting of N integers, the task is to partition the array into two non-empty subarrays such that every element present in the right subarray is strictly greater than every element present in the left subarray. If it is possible to do so, then print the two resultant subarrays. Otherwise, print “Impossible”.
Examples:
Input: arr[] = {5, 3, 2, 7, 9}Output:5 3 2 7 9Explanation:One of the possible partition is {5, 3, 2} and {7, 9}.The minimum of 2nd subarray {7} is greater than the maximum of the first subarray (5).
Input: arr[] = {1,1,1,1,1}Output: ImpossibleExplanation: There is no partition possible for this array.
Naive Approach: The simplest approach is to traverse the array and for every index, check if the maximum of the first subarray is less than the minimum of the second subarray or not. If found to be true, then print the two subarrays.Time Complexity: O(N2)Auxiliary Space: O(N)
Efficient Approach: The above approach can be optimized by calculating the prefix maximum array and suffix minimum array which results in the constant time calculation of the maximum of the first subarray and minimum of 2nd subarray. Follow the steps below to solve the problem:
Initialize an array, say min[], to store the minimum suffix array.
Initialize 3 variables, say ind, mini and maxi, to store the index of partition, minimum of the suffix, and a maximum of the prefix respectively.
Traverse the array in reverse and update mini as mini = min (mini, arr[i]). Assign mini to min[i].
Now, traverse the array arr[] and perform the following operations:Update maxi as maxi =max(maxi, arr[i]).If i+1 < N as well as maxi < min[i+1], then print the partition made at index i and break.
Update maxi as maxi =max(maxi, arr[i]).
If i+1 < N as well as maxi < min[i+1], then print the partition made at index i and break.
After completing the above steps, if none of the above cases are satisfied, then print “Impossible”.
Below is the implementation of the above approach:
C++
Java
Python3
C#
Javascript
// C++ program of the above approach#include <bits/stdc++.h>using namespace std; // Function to partition the array// into two non-empty subarrays// which satisfies the given conditionvoid partitionArray(int *a, int n){ // Stores the suffix Min array int *Min = new int[n]; // Stores the Minimum of a suffix int Mini = INT_MAX; // Traverse the array in reverse for (int i = n - 1; i >= 0; i--) { // Update Minimum Mini = min(Mini, a[i]); // Store the Minimum Min[i] = Mini; } // Stores the Maximum value of a prefix int Maxi = INT_MIN; // Stores the index of the partition int ind = -1; for (int i = 0; i < n - 1; i++) { // Update Max Maxi = max(Maxi, a[i]); // If Max is less than Min[i+1] if (Maxi < Min[i + 1]) { // Store the index // of partition ind = i; // break break; } } // If ind is not -1 if (ind != -1) { // Print the first subarray for (int i = 0; i <= ind; i++) cout << a[i] << " "; cout << endl; // Print the second subarray for (int i = ind + 1; i < n; i++) cout << a[i] << " "; } // Otherwise else cout << "Impossible";} // Driver Codeint main(){ int arr[] = { 5, 3, 2, 7, 9 }; int N = 5; partitionArray(arr, N); return 0;} // This code is contributed by Shubhamsingh10
// Java program of the above approach import java.util.*; class GFG { // Function to partition the array // into two non-empty subarrays // which satisfies the given condition static void partitionArray(int a[], int n) { // Stores the suffix min array int min[] = new int[n]; // Stores the minimum of a suffix int mini = Integer.MAX_VALUE; // Traverse the array in reverse for (int i = n - 1; i >= 0; i--) { // Update minimum mini = Math.min(mini, a[i]); // Store the minimum min[i] = mini; } // Stores the maximum value of a prefix int maxi = Integer.MIN_VALUE; // Stores the index of the partition int ind = -1; for (int i = 0; i < n - 1; i++) { // Update max maxi = Math.max(maxi, a[i]); // If max is less than min[i+1] if (maxi < min[i + 1]) { // Store the index // of partition ind = i; // break break; } } // If ind is not -1 if (ind != -1) { // Print the first subarray for (int i = 0; i <= ind; i++) System.out.print(a[i] + " "); System.out.println(); // Print the second subarray for (int i = ind + 1; i < n; i++) System.out.print(a[i] + " "); } // Otherwise else System.out.println("Impossible"); } // Driver Code public static void main(String[] args) { int arr[] = { 5, 3, 2, 7, 9 }; int N = arr.length; partitionArray(arr, N); }}
# Python3 program for the above approachimport sys # Function to partition the array# into two non-empty subarrays# which satisfies the given conditiondef partitionArray(a, n) : # Stores the suffix Min array Min = [0] * n # Stores the Minimum of a suffix Mini = sys.maxsize # Traverse the array in reverse for i in range(n - 1, -1, -1): # Update Minimum Mini = min(Mini, a[i]) # Store the Minimum Min[i] = Mini # Stores the Maximum value of a prefix Maxi = -sys.maxsize - 1 # Stores the index of the partition ind = -1 for i in range(n - 1): # Update Max Maxi = max(Maxi, a[i]) # If Max is less than Min[i+1] if (Maxi < Min[i + 1]) : # Store the index # of partition ind = i # break break # If ind is not -1 if (ind != -1) : # Print first subarray for i in range(ind + 1): print(a[i], end = " ") print() # Print second subarray for i in range(ind + 1 , n , 1): print(a[i], end = " ") # Otherwise else : print("Impossible") # Driver Codearr = [ 5, 3, 2, 7, 9 ]N = 5partitionArray(arr, N) # This code is contributed by sanjoy_62.
// C# program of the above approachusing System; class GFG { // Function to partition the array // into two non-empty subarrays // which satisfies the given condition static void partitionArray(int[] a, int n) { // Stores the suffix min array int[] min = new int[n]; // Stores the minimum of a suffix int mini = Int32.MaxValue; // Traverse the array in reverse for (int i = n - 1; i >= 0; i--) { // Update minimum mini = Math.Min(mini, a[i]); // Store the minimum min[i] = mini; } // Stores the maximum value of a prefix int maxi = Int32.MinValue; // Stores the index of the partition int ind = -1; for (int i = 0; i < n - 1; i++) { // Update max maxi = Math.Max(maxi, a[i]); // If max is less than min[i+1] if (maxi < min[i + 1]) { // Store the index // of partition ind = i; // break break; } } // If ind is not -1 if (ind != -1) { // Print the first subarray for (int i = 0; i <= ind; i++) Console.Write(a[i] + " "); Console.WriteLine(); // Print the second subarray for (int i = ind + 1; i < n; i++) Console.Write(a[i] + " "); } // Otherwise else Console.Write("Impossible"); } // Driver Code public static void Main(string[] args) { int[] arr = { 5, 3, 2, 7, 9 }; int N = arr.Length; partitionArray(arr, N); }} // This code is contributed by ukasp.
<script> // javascript program of the above approach // Function to partition the array// into two non-empty subarrays// which satisfies the given condition function partitionArray(a , n) { // Stores the suffix min array var min = Array(n).fill(0); // Stores the minimum of a suffix var mini = Number.MAX_VALUE; // Traverse the array in reverse for (i = n - 1; i >= 0; i--) { // Update minimum mini = Math.min(mini, a[i]); // Store the minimum min[i] = mini; } // Stores the maximum value of a prefix var maxi = Number.MIN_VALUE; // Stores the index of the partition var ind = -1; for (i = 0; i < n - 1; i++) { // Update max maxi = Math.max(maxi, a[i]); // If max is less than min[i+1] if (maxi < min[i + 1]) { // Store the index // of partition ind = i; // break break; } } // If ind is not -1 if (ind != -1) { // Print the first subarray for (i = 0; i <= ind; i++) document.write(a[i] + " "); document.write("<br/>"); // Print the second subarray for (i = ind + 1; i < n; i++) document.write(a[i] + " "); } // Otherwise else document.write("Impossible"); } // Driver Code var arr = [ 5, 3, 2, 7, 9 ]; var N = arr.length; partitionArray(arr, N); // This code contributed by Rajput-Ji </script>
5 3 2
7 9
Time Complexity: O(N)Auxiliary Space: O(N)
ukasp
SHUBHAMSINGH10
sanjoy_62
Rajput-Ji
khushboogoyal499
bunnyram19
partition
subarray
Technical Scripter 2020
Arrays
Mathematical
Technical Scripter
Arrays
Mathematical
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Introduction to Data Structures
Window Sliding Technique
Search, insert and delete in an unsorted array
What is Data Structure: Types, Classifications and Applications
Chocolate Distribution Problem
Program for Fibonacci numbers
Set in C++ Standard Template Library (STL)
Write a program to print all permutations of a given string
C++ Data Types
Coin Change | DP-7 | [
{
"code": null,
"e": 54,
"s": 26,
"text": "\n11 Jun, 2021"
},
{
"code": null,
"e": 387,
"s": 54,
"text": "Given an array arr[] consisting of N integers, the task is to partition the array into two non-empty subarrays such that every element present in the right subarray is strictly greater than every element present in the left subarray. If it is possible to do so, then print the two resultant subarrays. Otherwise, print “Impossible”."
},
{
"code": null,
"e": 397,
"s": 387,
"text": "Examples:"
},
{
"code": null,
"e": 596,
"s": 397,
"text": "Input: arr[] = {5, 3, 2, 7, 9}Output:5 3 2 7 9Explanation:One of the possible partition is {5, 3, 2} and {7, 9}.The minimum of 2nd subarray {7} is greater than the maximum of the first subarray (5)."
},
{
"code": null,
"e": 700,
"s": 596,
"text": "Input: arr[] = {1,1,1,1,1}Output: ImpossibleExplanation: There is no partition possible for this array."
},
{
"code": null,
"e": 977,
"s": 700,
"text": "Naive Approach: The simplest approach is to traverse the array and for every index, check if the maximum of the first subarray is less than the minimum of the second subarray or not. If found to be true, then print the two subarrays.Time Complexity: O(N2)Auxiliary Space: O(N)"
},
{
"code": null,
"e": 1256,
"s": 977,
"text": "Efficient Approach: The above approach can be optimized by calculating the prefix maximum array and suffix minimum array which results in the constant time calculation of the maximum of the first subarray and minimum of 2nd subarray. Follow the steps below to solve the problem:"
},
{
"code": null,
"e": 1323,
"s": 1256,
"text": "Initialize an array, say min[], to store the minimum suffix array."
},
{
"code": null,
"e": 1469,
"s": 1323,
"text": "Initialize 3 variables, say ind, mini and maxi, to store the index of partition, minimum of the suffix, and a maximum of the prefix respectively."
},
{
"code": null,
"e": 1568,
"s": 1469,
"text": "Traverse the array in reverse and update mini as mini = min (mini, arr[i]). Assign mini to min[i]."
},
{
"code": null,
"e": 1765,
"s": 1568,
"text": "Now, traverse the array arr[] and perform the following operations:Update maxi as maxi =max(maxi, arr[i]).If i+1 < N as well as maxi < min[i+1], then print the partition made at index i and break."
},
{
"code": null,
"e": 1805,
"s": 1765,
"text": "Update maxi as maxi =max(maxi, arr[i])."
},
{
"code": null,
"e": 1896,
"s": 1805,
"text": "If i+1 < N as well as maxi < min[i+1], then print the partition made at index i and break."
},
{
"code": null,
"e": 1997,
"s": 1896,
"text": "After completing the above steps, if none of the above cases are satisfied, then print “Impossible”."
},
{
"code": null,
"e": 2048,
"s": 1997,
"text": "Below is the implementation of the above approach:"
},
{
"code": null,
"e": 2052,
"s": 2048,
"text": "C++"
},
{
"code": null,
"e": 2057,
"s": 2052,
"text": "Java"
},
{
"code": null,
"e": 2065,
"s": 2057,
"text": "Python3"
},
{
"code": null,
"e": 2068,
"s": 2065,
"text": "C#"
},
{
"code": null,
"e": 2079,
"s": 2068,
"text": "Javascript"
},
{
"code": "// C++ program of the above approach#include <bits/stdc++.h>using namespace std; // Function to partition the array// into two non-empty subarrays// which satisfies the given conditionvoid partitionArray(int *a, int n){ // Stores the suffix Min array int *Min = new int[n]; // Stores the Minimum of a suffix int Mini = INT_MAX; // Traverse the array in reverse for (int i = n - 1; i >= 0; i--) { // Update Minimum Mini = min(Mini, a[i]); // Store the Minimum Min[i] = Mini; } // Stores the Maximum value of a prefix int Maxi = INT_MIN; // Stores the index of the partition int ind = -1; for (int i = 0; i < n - 1; i++) { // Update Max Maxi = max(Maxi, a[i]); // If Max is less than Min[i+1] if (Maxi < Min[i + 1]) { // Store the index // of partition ind = i; // break break; } } // If ind is not -1 if (ind != -1) { // Print the first subarray for (int i = 0; i <= ind; i++) cout << a[i] << \" \"; cout << endl; // Print the second subarray for (int i = ind + 1; i < n; i++) cout << a[i] << \" \"; } // Otherwise else cout << \"Impossible\";} // Driver Codeint main(){ int arr[] = { 5, 3, 2, 7, 9 }; int N = 5; partitionArray(arr, N); return 0;} // This code is contributed by Shubhamsingh10",
"e": 3385,
"s": 2079,
"text": null
},
{
"code": "// Java program of the above approach import java.util.*; class GFG { // Function to partition the array // into two non-empty subarrays // which satisfies the given condition static void partitionArray(int a[], int n) { // Stores the suffix min array int min[] = new int[n]; // Stores the minimum of a suffix int mini = Integer.MAX_VALUE; // Traverse the array in reverse for (int i = n - 1; i >= 0; i--) { // Update minimum mini = Math.min(mini, a[i]); // Store the minimum min[i] = mini; } // Stores the maximum value of a prefix int maxi = Integer.MIN_VALUE; // Stores the index of the partition int ind = -1; for (int i = 0; i < n - 1; i++) { // Update max maxi = Math.max(maxi, a[i]); // If max is less than min[i+1] if (maxi < min[i + 1]) { // Store the index // of partition ind = i; // break break; } } // If ind is not -1 if (ind != -1) { // Print the first subarray for (int i = 0; i <= ind; i++) System.out.print(a[i] + \" \"); System.out.println(); // Print the second subarray for (int i = ind + 1; i < n; i++) System.out.print(a[i] + \" \"); } // Otherwise else System.out.println(\"Impossible\"); } // Driver Code public static void main(String[] args) { int arr[] = { 5, 3, 2, 7, 9 }; int N = arr.length; partitionArray(arr, N); }}",
"e": 5093,
"s": 3385,
"text": null
},
{
"code": "# Python3 program for the above approachimport sys # Function to partition the array# into two non-empty subarrays# which satisfies the given conditiondef partitionArray(a, n) : # Stores the suffix Min array Min = [0] * n # Stores the Minimum of a suffix Mini = sys.maxsize # Traverse the array in reverse for i in range(n - 1, -1, -1): # Update Minimum Mini = min(Mini, a[i]) # Store the Minimum Min[i] = Mini # Stores the Maximum value of a prefix Maxi = -sys.maxsize - 1 # Stores the index of the partition ind = -1 for i in range(n - 1): # Update Max Maxi = max(Maxi, a[i]) # If Max is less than Min[i+1] if (Maxi < Min[i + 1]) : # Store the index # of partition ind = i # break break # If ind is not -1 if (ind != -1) : # Print first subarray for i in range(ind + 1): print(a[i], end = \" \") print() # Print second subarray for i in range(ind + 1 , n , 1): print(a[i], end = \" \") # Otherwise else : print(\"Impossible\") # Driver Codearr = [ 5, 3, 2, 7, 9 ]N = 5partitionArray(arr, N) # This code is contributed by sanjoy_62.",
"e": 6236,
"s": 5093,
"text": null
},
{
"code": "// C# program of the above approachusing System; class GFG { // Function to partition the array // into two non-empty subarrays // which satisfies the given condition static void partitionArray(int[] a, int n) { // Stores the suffix min array int[] min = new int[n]; // Stores the minimum of a suffix int mini = Int32.MaxValue; // Traverse the array in reverse for (int i = n - 1; i >= 0; i--) { // Update minimum mini = Math.Min(mini, a[i]); // Store the minimum min[i] = mini; } // Stores the maximum value of a prefix int maxi = Int32.MinValue; // Stores the index of the partition int ind = -1; for (int i = 0; i < n - 1; i++) { // Update max maxi = Math.Max(maxi, a[i]); // If max is less than min[i+1] if (maxi < min[i + 1]) { // Store the index // of partition ind = i; // break break; } } // If ind is not -1 if (ind != -1) { // Print the first subarray for (int i = 0; i <= ind; i++) Console.Write(a[i] + \" \"); Console.WriteLine(); // Print the second subarray for (int i = ind + 1; i < n; i++) Console.Write(a[i] + \" \"); } // Otherwise else Console.Write(\"Impossible\"); } // Driver Code public static void Main(string[] args) { int[] arr = { 5, 3, 2, 7, 9 }; int N = arr.Length; partitionArray(arr, N); }} // This code is contributed by ukasp.",
"e": 7705,
"s": 6236,
"text": null
},
{
"code": "<script> // javascript program of the above approach // Function to partition the array// into two non-empty subarrays// which satisfies the given condition function partitionArray(a , n) { // Stores the suffix min array var min = Array(n).fill(0); // Stores the minimum of a suffix var mini = Number.MAX_VALUE; // Traverse the array in reverse for (i = n - 1; i >= 0; i--) { // Update minimum mini = Math.min(mini, a[i]); // Store the minimum min[i] = mini; } // Stores the maximum value of a prefix var maxi = Number.MIN_VALUE; // Stores the index of the partition var ind = -1; for (i = 0; i < n - 1; i++) { // Update max maxi = Math.max(maxi, a[i]); // If max is less than min[i+1] if (maxi < min[i + 1]) { // Store the index // of partition ind = i; // break break; } } // If ind is not -1 if (ind != -1) { // Print the first subarray for (i = 0; i <= ind; i++) document.write(a[i] + \" \"); document.write(\"<br/>\"); // Print the second subarray for (i = ind + 1; i < n; i++) document.write(a[i] + \" \"); } // Otherwise else document.write(\"Impossible\"); } // Driver Code var arr = [ 5, 3, 2, 7, 9 ]; var N = arr.length; partitionArray(arr, N); // This code contributed by Rajput-Ji </script>",
"e": 9354,
"s": 7705,
"text": null
},
{
"code": null,
"e": 9365,
"s": 9354,
"text": "5 3 2 \n7 9"
},
{
"code": null,
"e": 9411,
"s": 9367,
"text": "Time Complexity: O(N)Auxiliary Space: O(N) "
},
{
"code": null,
"e": 9417,
"s": 9411,
"text": "ukasp"
},
{
"code": null,
"e": 9432,
"s": 9417,
"text": "SHUBHAMSINGH10"
},
{
"code": null,
"e": 9442,
"s": 9432,
"text": "sanjoy_62"
},
{
"code": null,
"e": 9452,
"s": 9442,
"text": "Rajput-Ji"
},
{
"code": null,
"e": 9469,
"s": 9452,
"text": "khushboogoyal499"
},
{
"code": null,
"e": 9480,
"s": 9469,
"text": "bunnyram19"
},
{
"code": null,
"e": 9490,
"s": 9480,
"text": "partition"
},
{
"code": null,
"e": 9499,
"s": 9490,
"text": "subarray"
},
{
"code": null,
"e": 9523,
"s": 9499,
"text": "Technical Scripter 2020"
},
{
"code": null,
"e": 9530,
"s": 9523,
"text": "Arrays"
},
{
"code": null,
"e": 9543,
"s": 9530,
"text": "Mathematical"
},
{
"code": null,
"e": 9562,
"s": 9543,
"text": "Technical Scripter"
},
{
"code": null,
"e": 9569,
"s": 9562,
"text": "Arrays"
},
{
"code": null,
"e": 9582,
"s": 9569,
"text": "Mathematical"
},
{
"code": null,
"e": 9680,
"s": 9582,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 9712,
"s": 9680,
"text": "Introduction to Data Structures"
},
{
"code": null,
"e": 9737,
"s": 9712,
"text": "Window Sliding Technique"
},
{
"code": null,
"e": 9784,
"s": 9737,
"text": "Search, insert and delete in an unsorted array"
},
{
"code": null,
"e": 9848,
"s": 9784,
"text": "What is Data Structure: Types, Classifications and Applications"
},
{
"code": null,
"e": 9879,
"s": 9848,
"text": "Chocolate Distribution Problem"
},
{
"code": null,
"e": 9909,
"s": 9879,
"text": "Program for Fibonacci numbers"
},
{
"code": null,
"e": 9952,
"s": 9909,
"text": "Set in C++ Standard Template Library (STL)"
},
{
"code": null,
"e": 10012,
"s": 9952,
"text": "Write a program to print all permutations of a given string"
},
{
"code": null,
"e": 10027,
"s": 10012,
"text": "C++ Data Types"
}
] |
JavaScript Date UTC() Method | 21 Oct, 2021
Below is the example of Date UTC() method.
Example:<script> var gfg = Date.UTC(2020, 07, 03); document.write("Output : " + gfg);</script>
<script> var gfg = Date.UTC(2020, 07, 03); document.write("Output : " + gfg);</script>
Output:Output : 1596412800000
Output : 1596412800000
The Date.UTC() method in JavaScript is used to return the number of milliseconds in a Date object since January 1, 1970, 00:00:00, universal time.The UTC() method differs from the Date constructor in two ways:
Date.UTC() uses universal time instead of the local time.
Date.UTC() returns a time value as a number instead of creating a Date object.
Syntax:
Date.UTC(year, month, day, hour, minute, second, millisecond)
Parameters: This method accepts seven parameters as mentioned above and described below:
year: To specify a year after 1900.
month: To specify an integer between 0 and 11 representing the month.Other values which are allowed are:-1 will represent the last month of the previous year.12 will represent the first month of the next year.13 will represent the second month of the next year.
-1 will represent the last month of the previous year.
12 will represent the first month of the next year.
13 will represent the second month of the next year.
day: It is an optional parameter. It is used to specify an integer between 1 and 31 representing the day of the month. Other values which are allowed are:0 will represent the last hour of the previous month.-1 will represent the hour before the last hour of the previous month.If the month has 31 days then 32 will represent the first day of the next month.If the month has 30 days then 32 will represent the second day of the next month.
0 will represent the last hour of the previous month.
-1 will represent the hour before the last hour of the previous month.
If the month has 31 days then 32 will represent the first day of the next month.
If the month has 30 days then 32 will represent the second day of the next month.
hour: It is an optional parameter. It is used to specify an integer between 0 and 23 representing the hours.Other values which are allowed are :-1 will represent the last hour of the previous day.24 will represent the first hour of the next day.
-1 will represent the last hour of the previous day.
24 will represent the first hour of the next day.
minute: It is an optional parameter. It is used to specify an integer between 0 and 59 representing the minutes.Other values which are allowed are :-1 will represent the last minute of the previous hour.60 will represent the first minute of the next hour.
-1 will represent the last minute of the previous hour.
60 will represent the first minute of the next hour.
second: It is an optional parameter. It is used to specify an integer between 0 and 59 representing the seconds.Other values which are allowed are:-1 will represent the last second of the previous minute.60 will represent the first second of the next minute.
-1 will represent the last second of the previous minute.
60 will represent the first second of the next minute.
millisecond: It is an optional parameter. It is used to specify an integer between 0 and 999 representing the milliseconds.Other values which are allowed are :-1 will represent the last millisecond of the previous second.1000 will represent the first millisecond of the next second.
-1 will represent the last millisecond of the previous second.
1000 will represent the first millisecond of the next second.
Return value: The Date.UTC() method returns a number representing the number of milliseconds in the given Date object since January 1, 1970, 00:00:00, universal time.
Below Examples illustrate the method in JavaScript:
Example 1: In this example three parameters are passed in the Date.UTC() method represents the year, month, and day respectively. The method returns the number of milliseconds between the date specified as parameter and midnight of January 1, 1970.Date.UTC(2010, 01, 28)Output:1267315200000
Date.UTC(2010, 01, 28)
Output:
1267315200000
Example 2: In this example three parameters are passed in the Date.UTC() method which represent year, month, and day respectively, and a data object “new date” is created. The method returns the UTC time for the passed parameters.new Date(Date.UTC(2010, 01, 28))Output:Sun Feb 28 2010 05:30:00 GMT+0530 (IST)
new Date(Date.UTC(2010, 01, 28))
Output:
Sun Feb 28 2010 05:30:00 GMT+0530 (IST)
More codes for the above method are as follows:
Program 1: In this program returning the number of milliseconds between a specified date and midnight January 1, 1970.
<script> var test = Date.UTC(2010, 01, 28); document.write("Output : " + test);</script>
Output:
Output : 1267315200000
Program 2: In this program creating a date object using UTC time instead of local time.
<script>var test = new Date(Date.UTC(2010, 01, 28));document.write("Output : " + test);</script>
Output:
Output : Sun Feb 28 2010 05:30:00 GMT+0530 (IST)
Supported Browsers: The browsers supported by JavaScript Date UTC() Method are listed below:
Google Chrome 1 and above
Edge 12 and above
Firefox 1 and above
Internet Explorer 3 and above
Opera 3 and above
Safari 1 and above
ysachin2314
date-time-program
javascript-date
JavaScript-Methods
JavaScript
Web Technologies
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Difference between var, let and const keywords in JavaScript
Differences between Functional Components and Class Components in React
Remove elements from a JavaScript Array
Difference Between PUT and PATCH Request
How to append HTML code to a div using JavaScript ?
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": "\n21 Oct, 2021"
},
{
"code": null,
"e": 71,
"s": 28,
"text": "Below is the example of Date UTC() method."
},
{
"code": null,
"e": 170,
"s": 71,
"text": "Example:<script> var gfg = Date.UTC(2020, 07, 03); document.write(\"Output : \" + gfg);</script>"
},
{
"code": "<script> var gfg = Date.UTC(2020, 07, 03); document.write(\"Output : \" + gfg);</script>",
"e": 261,
"s": 170,
"text": null
},
{
"code": null,
"e": 291,
"s": 261,
"text": "Output:Output : 1596412800000"
},
{
"code": null,
"e": 314,
"s": 291,
"text": "Output : 1596412800000"
},
{
"code": null,
"e": 524,
"s": 314,
"text": "The Date.UTC() method in JavaScript is used to return the number of milliseconds in a Date object since January 1, 1970, 00:00:00, universal time.The UTC() method differs from the Date constructor in two ways:"
},
{
"code": null,
"e": 582,
"s": 524,
"text": "Date.UTC() uses universal time instead of the local time."
},
{
"code": null,
"e": 661,
"s": 582,
"text": "Date.UTC() returns a time value as a number instead of creating a Date object."
},
{
"code": null,
"e": 669,
"s": 661,
"text": "Syntax:"
},
{
"code": null,
"e": 731,
"s": 669,
"text": "Date.UTC(year, month, day, hour, minute, second, millisecond)"
},
{
"code": null,
"e": 820,
"s": 731,
"text": "Parameters: This method accepts seven parameters as mentioned above and described below:"
},
{
"code": null,
"e": 856,
"s": 820,
"text": "year: To specify a year after 1900."
},
{
"code": null,
"e": 1118,
"s": 856,
"text": "month: To specify an integer between 0 and 11 representing the month.Other values which are allowed are:-1 will represent the last month of the previous year.12 will represent the first month of the next year.13 will represent the second month of the next year."
},
{
"code": null,
"e": 1173,
"s": 1118,
"text": "-1 will represent the last month of the previous year."
},
{
"code": null,
"e": 1225,
"s": 1173,
"text": "12 will represent the first month of the next year."
},
{
"code": null,
"e": 1278,
"s": 1225,
"text": "13 will represent the second month of the next year."
},
{
"code": null,
"e": 1717,
"s": 1278,
"text": "day: It is an optional parameter. It is used to specify an integer between 1 and 31 representing the day of the month. Other values which are allowed are:0 will represent the last hour of the previous month.-1 will represent the hour before the last hour of the previous month.If the month has 31 days then 32 will represent the first day of the next month.If the month has 30 days then 32 will represent the second day of the next month."
},
{
"code": null,
"e": 1771,
"s": 1717,
"text": "0 will represent the last hour of the previous month."
},
{
"code": null,
"e": 1842,
"s": 1771,
"text": "-1 will represent the hour before the last hour of the previous month."
},
{
"code": null,
"e": 1923,
"s": 1842,
"text": "If the month has 31 days then 32 will represent the first day of the next month."
},
{
"code": null,
"e": 2005,
"s": 1923,
"text": "If the month has 30 days then 32 will represent the second day of the next month."
},
{
"code": null,
"e": 2251,
"s": 2005,
"text": "hour: It is an optional parameter. It is used to specify an integer between 0 and 23 representing the hours.Other values which are allowed are :-1 will represent the last hour of the previous day.24 will represent the first hour of the next day."
},
{
"code": null,
"e": 2304,
"s": 2251,
"text": "-1 will represent the last hour of the previous day."
},
{
"code": null,
"e": 2354,
"s": 2304,
"text": "24 will represent the first hour of the next day."
},
{
"code": null,
"e": 2610,
"s": 2354,
"text": "minute: It is an optional parameter. It is used to specify an integer between 0 and 59 representing the minutes.Other values which are allowed are :-1 will represent the last minute of the previous hour.60 will represent the first minute of the next hour."
},
{
"code": null,
"e": 2666,
"s": 2610,
"text": "-1 will represent the last minute of the previous hour."
},
{
"code": null,
"e": 2719,
"s": 2666,
"text": "60 will represent the first minute of the next hour."
},
{
"code": null,
"e": 2978,
"s": 2719,
"text": "second: It is an optional parameter. It is used to specify an integer between 0 and 59 representing the seconds.Other values which are allowed are:-1 will represent the last second of the previous minute.60 will represent the first second of the next minute."
},
{
"code": null,
"e": 3036,
"s": 2978,
"text": "-1 will represent the last second of the previous minute."
},
{
"code": null,
"e": 3091,
"s": 3036,
"text": "60 will represent the first second of the next minute."
},
{
"code": null,
"e": 3374,
"s": 3091,
"text": "millisecond: It is an optional parameter. It is used to specify an integer between 0 and 999 representing the milliseconds.Other values which are allowed are :-1 will represent the last millisecond of the previous second.1000 will represent the first millisecond of the next second."
},
{
"code": null,
"e": 3437,
"s": 3374,
"text": "-1 will represent the last millisecond of the previous second."
},
{
"code": null,
"e": 3499,
"s": 3437,
"text": "1000 will represent the first millisecond of the next second."
},
{
"code": null,
"e": 3666,
"s": 3499,
"text": "Return value: The Date.UTC() method returns a number representing the number of milliseconds in the given Date object since January 1, 1970, 00:00:00, universal time."
},
{
"code": null,
"e": 3718,
"s": 3666,
"text": "Below Examples illustrate the method in JavaScript:"
},
{
"code": null,
"e": 4009,
"s": 3718,
"text": "Example 1: In this example three parameters are passed in the Date.UTC() method represents the year, month, and day respectively. The method returns the number of milliseconds between the date specified as parameter and midnight of January 1, 1970.Date.UTC(2010, 01, 28)Output:1267315200000"
},
{
"code": null,
"e": 4032,
"s": 4009,
"text": "Date.UTC(2010, 01, 28)"
},
{
"code": null,
"e": 4040,
"s": 4032,
"text": "Output:"
},
{
"code": null,
"e": 4054,
"s": 4040,
"text": "1267315200000"
},
{
"code": null,
"e": 4363,
"s": 4054,
"text": "Example 2: In this example three parameters are passed in the Date.UTC() method which represent year, month, and day respectively, and a data object “new date” is created. The method returns the UTC time for the passed parameters.new Date(Date.UTC(2010, 01, 28))Output:Sun Feb 28 2010 05:30:00 GMT+0530 (IST)"
},
{
"code": null,
"e": 4396,
"s": 4363,
"text": "new Date(Date.UTC(2010, 01, 28))"
},
{
"code": null,
"e": 4404,
"s": 4396,
"text": "Output:"
},
{
"code": null,
"e": 4444,
"s": 4404,
"text": "Sun Feb 28 2010 05:30:00 GMT+0530 (IST)"
},
{
"code": null,
"e": 4492,
"s": 4444,
"text": "More codes for the above method are as follows:"
},
{
"code": null,
"e": 4611,
"s": 4492,
"text": "Program 1: In this program returning the number of milliseconds between a specified date and midnight January 1, 1970."
},
{
"code": "<script> var test = Date.UTC(2010, 01, 28); document.write(\"Output : \" + test);</script>",
"e": 4704,
"s": 4611,
"text": null
},
{
"code": null,
"e": 4712,
"s": 4704,
"text": "Output:"
},
{
"code": null,
"e": 4735,
"s": 4712,
"text": "Output : 1267315200000"
},
{
"code": null,
"e": 4823,
"s": 4735,
"text": "Program 2: In this program creating a date object using UTC time instead of local time."
},
{
"code": "<script>var test = new Date(Date.UTC(2010, 01, 28));document.write(\"Output : \" + test);</script>",
"e": 4920,
"s": 4823,
"text": null
},
{
"code": null,
"e": 4928,
"s": 4920,
"text": "Output:"
},
{
"code": null,
"e": 4977,
"s": 4928,
"text": "Output : Sun Feb 28 2010 05:30:00 GMT+0530 (IST)"
},
{
"code": null,
"e": 5070,
"s": 4977,
"text": "Supported Browsers: The browsers supported by JavaScript Date UTC() Method are listed below:"
},
{
"code": null,
"e": 5096,
"s": 5070,
"text": "Google Chrome 1 and above"
},
{
"code": null,
"e": 5114,
"s": 5096,
"text": "Edge 12 and above"
},
{
"code": null,
"e": 5134,
"s": 5114,
"text": "Firefox 1 and above"
},
{
"code": null,
"e": 5164,
"s": 5134,
"text": "Internet Explorer 3 and above"
},
{
"code": null,
"e": 5182,
"s": 5164,
"text": "Opera 3 and above"
},
{
"code": null,
"e": 5201,
"s": 5182,
"text": "Safari 1 and above"
},
{
"code": null,
"e": 5213,
"s": 5201,
"text": "ysachin2314"
},
{
"code": null,
"e": 5231,
"s": 5213,
"text": "date-time-program"
},
{
"code": null,
"e": 5247,
"s": 5231,
"text": "javascript-date"
},
{
"code": null,
"e": 5266,
"s": 5247,
"text": "JavaScript-Methods"
},
{
"code": null,
"e": 5277,
"s": 5266,
"text": "JavaScript"
},
{
"code": null,
"e": 5294,
"s": 5277,
"text": "Web Technologies"
},
{
"code": null,
"e": 5392,
"s": 5294,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 5453,
"s": 5392,
"text": "Difference between var, let and const keywords in JavaScript"
},
{
"code": null,
"e": 5525,
"s": 5453,
"text": "Differences between Functional Components and Class Components in React"
},
{
"code": null,
"e": 5565,
"s": 5525,
"text": "Remove elements from a JavaScript Array"
},
{
"code": null,
"e": 5606,
"s": 5565,
"text": "Difference Between PUT and PATCH Request"
},
{
"code": null,
"e": 5658,
"s": 5606,
"text": "How to append HTML code to a div using JavaScript ?"
},
{
"code": null,
"e": 5691,
"s": 5658,
"text": "Installation of Node.js on Linux"
},
{
"code": null,
"e": 5753,
"s": 5691,
"text": "Top 10 Projects For Beginners To Practice HTML and CSS Skills"
},
{
"code": null,
"e": 5814,
"s": 5753,
"text": "Difference between var, let and const keywords in JavaScript"
},
{
"code": null,
"e": 5864,
"s": 5814,
"text": "How to insert spaces/tabs in text using HTML/CSS?"
}
] |
Find all Pairs possible from the given Array | 27 Jan, 2022
Given an array arr[] of N integers, the task is to find all the pairs possible from the given array. Note:
(arr[i], arr[i]) is also considered as a valid pair.(arr[i], arr[j]) and (arr[j], arr[i]) are considered as two different pairs.
(arr[i], arr[i]) is also considered as a valid pair.
(arr[i], arr[j]) and (arr[j], arr[i]) are considered as two different pairs.
Examples:
Input: arr[] = {1, 2} Output: (1, 1), (1, 2), (2, 1), (2, 2).Input: arr[] = {1, 2, 3} Output: (1, 1), (1, 2), (1, 3), (2, 1), (2, 2), (2, 3), (3, 1), (3, 2), (3, 3)
Approach: In order to find all the possible pairs from the array, we need to traverse the array and select the first element of the pair. Then we need to pair this element with all the elements in the array from index 0 to N-1. Below is the step by step approach:
Traverse the array and select an element in each traversal.
For each element selected, traverse the array with help of another loop and form the pair of this element with each element in the array from the second loop.
The array in the second loop will get executed from its first element to its last element, i.e. from index 0 to N-1.
Print each pair formed.
Below is the implementation of the above approach:
C++
Java
Python3
C#
Javascript
// C++ implementation to find all// Pairs possible from the given Array #include <bits/stdc++.h>using namespace std; // Function to print all possible// pairs from the arrayvoid printPairs(int arr[], int n){ // Nested loop for all possible pairs for (int i = 0; i < n; i++) { for (int j = 0; j < n; j++) { cout << "(" << arr[i] << ", " << arr[j] << ")" << ", "; } }} // Driver codeint main(){ int arr[] = { 1, 2 }; int n = sizeof(arr) / sizeof(arr[0]); printPairs(arr, n); return 0;}
// Java implementation to find all// Pairs possible from the given Arrayclass GFG{ // Function to print all possible// pairs from the arraystatic void printPairs(int arr[], int n){ // Nested loop for all possible pairs for (int i = 0; i < n; i++) { for (int j = 0; j < n; j++) { System.out.print("(" + arr[i]+ ", " + arr[j]+ ")" + ", "); } }} // Driver codepublic static void main(String[] args){ int arr[] = { 1, 2 }; int n = arr.length; printPairs(arr, n); }} // This code is contributed by PrinciRaj1992
# Python3 implementation to find all# Pairs possible from the given Array # Function to print all possible# pairs from the arraydef printPairs(arr, n): # Nested loop for all possible pairs for i in range(n): for j in range(n): print("(",arr[i],",",arr[j],")",end=", ") # Driver code arr=[1, 2]n = len(arr) printPairs(arr, n) # This code is contributed by mohit kumar 29
// C# implementation to find all// Pairs possible from the given Arrayusing System; class GFG{ // Function to print all possible// pairs from the arraystatic void printPairs(int []arr, int n){ // Nested loop for all possible pairs for (int i = 0; i < n; i++) { for (int j = 0; j < n; j++) { Console.Write("(" + arr[i]+ ", " + arr[j]+ ")" + ", "); } }} // Driver codepublic static void Main(string[] args){ int []arr = { 1, 2 }; int n = arr.Length; printPairs(arr, n);}} // This code is contributed by AnkitRai01
<script> // Javascript implementation to find all// Pairs possible from the given Array // Function to print all possible// pairs from the arrayfunction printPairs(arr, n){ // Nested loop for all possible pairs for (var i = 0; i < n; i++) { for (var j = 0; j < n; j++) { document.write("(" + arr[i] + ", " + arr[j] + ")" + ", "); } }} // Driver codevar arr = [ 1, 2 ];var n = arr.length;printPairs(arr, n); // This code is contributed by rutvik_56.</script>
(1, 1), (1, 2), (2, 1), (2, 2),
Time Complexity: O(N2)
Auxiliary Space: O(1)
Approach :
During the merge operation in merge sort we can get all the pairs and we can store those pairs into a vector of pairs.
By just making few changes into the merge sort algorithm we can get all the pairs.
C++
/* This code was submitted by : Chirag Mittal from IIIT Dharwad ( username : iitjeechirag ) storing all the pairs while merging Time Complexity : O(N logN) Space Complexity : O(N) + O(Number Of Pairs) using Merge Sort Algorithm*/ #include<bits/stdc++.h>using namespace std;void getPairsMerge(int arr[],int l,int r,int mid,vector<pair<int,int>>&p){ int b[l+r+1],i=l,k=l,j=mid+1; while(i<=mid && j<=r){ if(arr[i]>arr[j]){ b[k]=arr[j]; p.push_back({arr[i],arr[j]}); p.push_back({arr[j],arr[i]}); p.push_back({arr[j],arr[j]}); k++; j++; } else{ p.push_back({arr[i],arr[j]}); p.push_back({arr[j],arr[i]}); p.push_back({arr[i],arr[i]}); b[k]=arr[i]; i++; k++; } } while(i<=mid){ b[k]=arr[i]; p.push_back({arr[i],arr[i]}); i++; k++; } while(j<=r){ b[k]=arr[j]; p.push_back({arr[j],arr[j]}); j++; k++; } for(int x=l;x<=r;x++){ arr[x]=b[x]; }} void getAllPairs(int arr[],int l,int r,vector<pair<int,int>>&p){ if(l<r){ int mid=(l+r)/2; getAllPairs(arr,l,mid,p); getAllPairs(arr,mid+1,r,p); getPairsMerge(arr,l,r,mid,p); }} int main(){ int n=2; int arr[n]={1,2}; vector<pair<int,int>>p; getAllPairs(arr,0,n-1,p); for(auto it:p){ cout<<it.first<<" "<<it.second<<endl; }}
1 2
2 1
1 1
2 2
Time Complexity : O (N LogN )
Auxiliary Space: O(l + r)
mohit kumar 29
princiraj1992
ankthon
rutvik_56
chiragmittaliiitdwd
souravmahato348
adnanirshad158
Arrays
Mathematical
Arrays
Mathematical
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Maximum and minimum of an array using minimum number of comparisons
Top 50 Array Coding Problems for Interviews
Multidimensional Arrays in Java
Stack Data Structure (Introduction and Program)
Linear Search
Program for Fibonacci numbers
Set in C++ Standard Template Library (STL)
Write a program to print all permutations of a given string
C++ Data Types
Merge two sorted arrays | [
{
"code": null,
"e": 52,
"s": 24,
"text": "\n27 Jan, 2022"
},
{
"code": null,
"e": 161,
"s": 52,
"text": "Given an array arr[] of N integers, the task is to find all the pairs possible from the given array. Note: "
},
{
"code": null,
"e": 290,
"s": 161,
"text": "(arr[i], arr[i]) is also considered as a valid pair.(arr[i], arr[j]) and (arr[j], arr[i]) are considered as two different pairs."
},
{
"code": null,
"e": 343,
"s": 290,
"text": "(arr[i], arr[i]) is also considered as a valid pair."
},
{
"code": null,
"e": 420,
"s": 343,
"text": "(arr[i], arr[j]) and (arr[j], arr[i]) are considered as two different pairs."
},
{
"code": null,
"e": 432,
"s": 420,
"text": "Examples: "
},
{
"code": null,
"e": 599,
"s": 432,
"text": "Input: arr[] = {1, 2} Output: (1, 1), (1, 2), (2, 1), (2, 2).Input: arr[] = {1, 2, 3} Output: (1, 1), (1, 2), (1, 3), (2, 1), (2, 2), (2, 3), (3, 1), (3, 2), (3, 3) "
},
{
"code": null,
"e": 867,
"s": 601,
"text": "Approach: In order to find all the possible pairs from the array, we need to traverse the array and select the first element of the pair. Then we need to pair this element with all the elements in the array from index 0 to N-1. Below is the step by step approach: "
},
{
"code": null,
"e": 927,
"s": 867,
"text": "Traverse the array and select an element in each traversal."
},
{
"code": null,
"e": 1086,
"s": 927,
"text": "For each element selected, traverse the array with help of another loop and form the pair of this element with each element in the array from the second loop."
},
{
"code": null,
"e": 1203,
"s": 1086,
"text": "The array in the second loop will get executed from its first element to its last element, i.e. from index 0 to N-1."
},
{
"code": null,
"e": 1227,
"s": 1203,
"text": "Print each pair formed."
},
{
"code": null,
"e": 1279,
"s": 1227,
"text": "Below is the implementation of the above approach: "
},
{
"code": null,
"e": 1283,
"s": 1279,
"text": "C++"
},
{
"code": null,
"e": 1288,
"s": 1283,
"text": "Java"
},
{
"code": null,
"e": 1296,
"s": 1288,
"text": "Python3"
},
{
"code": null,
"e": 1299,
"s": 1296,
"text": "C#"
},
{
"code": null,
"e": 1310,
"s": 1299,
"text": "Javascript"
},
{
"code": "// C++ implementation to find all// Pairs possible from the given Array #include <bits/stdc++.h>using namespace std; // Function to print all possible// pairs from the arrayvoid printPairs(int arr[], int n){ // Nested loop for all possible pairs for (int i = 0; i < n; i++) { for (int j = 0; j < n; j++) { cout << \"(\" << arr[i] << \", \" << arr[j] << \")\" << \", \"; } }} // Driver codeint main(){ int arr[] = { 1, 2 }; int n = sizeof(arr) / sizeof(arr[0]); printPairs(arr, n); return 0;}",
"e": 1875,
"s": 1310,
"text": null
},
{
"code": "// Java implementation to find all// Pairs possible from the given Arrayclass GFG{ // Function to print all possible// pairs from the arraystatic void printPairs(int arr[], int n){ // Nested loop for all possible pairs for (int i = 0; i < n; i++) { for (int j = 0; j < n; j++) { System.out.print(\"(\" + arr[i]+ \", \" + arr[j]+ \")\" + \", \"); } }} // Driver codepublic static void main(String[] args){ int arr[] = { 1, 2 }; int n = arr.length; printPairs(arr, n); }} // This code is contributed by PrinciRaj1992",
"e": 2464,
"s": 1875,
"text": null
},
{
"code": "# Python3 implementation to find all# Pairs possible from the given Array # Function to print all possible# pairs from the arraydef printPairs(arr, n): # Nested loop for all possible pairs for i in range(n): for j in range(n): print(\"(\",arr[i],\",\",arr[j],\")\",end=\", \") # Driver code arr=[1, 2]n = len(arr) printPairs(arr, n) # This code is contributed by mohit kumar 29",
"e": 2859,
"s": 2464,
"text": null
},
{
"code": "// C# implementation to find all// Pairs possible from the given Arrayusing System; class GFG{ // Function to print all possible// pairs from the arraystatic void printPairs(int []arr, int n){ // Nested loop for all possible pairs for (int i = 0; i < n; i++) { for (int j = 0; j < n; j++) { Console.Write(\"(\" + arr[i]+ \", \" + arr[j]+ \")\" + \", \"); } }} // Driver codepublic static void Main(string[] args){ int []arr = { 1, 2 }; int n = arr.Length; printPairs(arr, n);}} // This code is contributed by AnkitRai01",
"e": 3452,
"s": 2859,
"text": null
},
{
"code": "<script> // Javascript implementation to find all// Pairs possible from the given Array // Function to print all possible// pairs from the arrayfunction printPairs(arr, n){ // Nested loop for all possible pairs for (var i = 0; i < n; i++) { for (var j = 0; j < n; j++) { document.write(\"(\" + arr[i] + \", \" + arr[j] + \")\" + \", \"); } }} // Driver codevar arr = [ 1, 2 ];var n = arr.length;printPairs(arr, n); // This code is contributed by rutvik_56.</script>",
"e": 3976,
"s": 3452,
"text": null
},
{
"code": null,
"e": 4009,
"s": 3976,
"text": "(1, 1), (1, 2), (2, 1), (2, 2), "
},
{
"code": null,
"e": 4032,
"s": 4009,
"text": "Time Complexity: O(N2)"
},
{
"code": null,
"e": 4055,
"s": 4032,
"text": "Auxiliary Space: O(1) "
},
{
"code": null,
"e": 4067,
"s": 4055,
"text": "Approach : "
},
{
"code": null,
"e": 4187,
"s": 4067,
"text": "During the merge operation in merge sort we can get all the pairs and we can store those pairs into a vector of pairs. "
},
{
"code": null,
"e": 4270,
"s": 4187,
"text": "By just making few changes into the merge sort algorithm we can get all the pairs."
},
{
"code": null,
"e": 4274,
"s": 4270,
"text": "C++"
},
{
"code": "/* This code was submitted by : Chirag Mittal from IIIT Dharwad ( username : iitjeechirag ) storing all the pairs while merging Time Complexity : O(N logN) Space Complexity : O(N) + O(Number Of Pairs) using Merge Sort Algorithm*/ #include<bits/stdc++.h>using namespace std;void getPairsMerge(int arr[],int l,int r,int mid,vector<pair<int,int>>&p){ int b[l+r+1],i=l,k=l,j=mid+1; while(i<=mid && j<=r){ if(arr[i]>arr[j]){ b[k]=arr[j]; p.push_back({arr[i],arr[j]}); p.push_back({arr[j],arr[i]}); p.push_back({arr[j],arr[j]}); k++; j++; } else{ p.push_back({arr[i],arr[j]}); p.push_back({arr[j],arr[i]}); p.push_back({arr[i],arr[i]}); b[k]=arr[i]; i++; k++; } } while(i<=mid){ b[k]=arr[i]; p.push_back({arr[i],arr[i]}); i++; k++; } while(j<=r){ b[k]=arr[j]; p.push_back({arr[j],arr[j]}); j++; k++; } for(int x=l;x<=r;x++){ arr[x]=b[x]; }} void getAllPairs(int arr[],int l,int r,vector<pair<int,int>>&p){ if(l<r){ int mid=(l+r)/2; getAllPairs(arr,l,mid,p); getAllPairs(arr,mid+1,r,p); getPairsMerge(arr,l,r,mid,p); }} int main(){ int n=2; int arr[n]={1,2}; vector<pair<int,int>>p; getAllPairs(arr,0,n-1,p); for(auto it:p){ cout<<it.first<<\" \"<<it.second<<endl; }}",
"e": 5760,
"s": 4274,
"text": null
},
{
"code": null,
"e": 5776,
"s": 5760,
"text": "1 2\n2 1\n1 1\n2 2"
},
{
"code": null,
"e": 5806,
"s": 5776,
"text": "Time Complexity : O (N LogN )"
},
{
"code": null,
"e": 5832,
"s": 5806,
"text": "Auxiliary Space: O(l + r)"
},
{
"code": null,
"e": 5847,
"s": 5832,
"text": "mohit kumar 29"
},
{
"code": null,
"e": 5861,
"s": 5847,
"text": "princiraj1992"
},
{
"code": null,
"e": 5869,
"s": 5861,
"text": "ankthon"
},
{
"code": null,
"e": 5879,
"s": 5869,
"text": "rutvik_56"
},
{
"code": null,
"e": 5899,
"s": 5879,
"text": "chiragmittaliiitdwd"
},
{
"code": null,
"e": 5915,
"s": 5899,
"text": "souravmahato348"
},
{
"code": null,
"e": 5930,
"s": 5915,
"text": "adnanirshad158"
},
{
"code": null,
"e": 5937,
"s": 5930,
"text": "Arrays"
},
{
"code": null,
"e": 5950,
"s": 5937,
"text": "Mathematical"
},
{
"code": null,
"e": 5957,
"s": 5950,
"text": "Arrays"
},
{
"code": null,
"e": 5970,
"s": 5957,
"text": "Mathematical"
},
{
"code": null,
"e": 6068,
"s": 5970,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 6136,
"s": 6068,
"text": "Maximum and minimum of an array using minimum number of comparisons"
},
{
"code": null,
"e": 6180,
"s": 6136,
"text": "Top 50 Array Coding Problems for Interviews"
},
{
"code": null,
"e": 6212,
"s": 6180,
"text": "Multidimensional Arrays in Java"
},
{
"code": null,
"e": 6260,
"s": 6212,
"text": "Stack Data Structure (Introduction and Program)"
},
{
"code": null,
"e": 6274,
"s": 6260,
"text": "Linear Search"
},
{
"code": null,
"e": 6304,
"s": 6274,
"text": "Program for Fibonacci numbers"
},
{
"code": null,
"e": 6347,
"s": 6304,
"text": "Set in C++ Standard Template Library (STL)"
},
{
"code": null,
"e": 6407,
"s": 6347,
"text": "Write a program to print all permutations of a given string"
},
{
"code": null,
"e": 6422,
"s": 6407,
"text": "C++ Data Types"
}
] |
Python SQLite – CRUD Operations | 21 Apr, 2021
In this article, we will go through the CRUD Operation using the SQLite module in Python.
The abbreviation CRUD expands to Create, Read, Update and Delete. These four are fundamental operations in a database. In the sample database, we will create it, and do some operations. Let’s discuss these operations one by one with the help of examples.
The create command is used to create the table in database. First we will go through its syntax then understand with an example.
Syntax: CREATE TABLE table_name ( Attr1 Type1, Attr2 Type2, ... , Attrn Typen ) ;
In this example, we will create a table named “gfg” with three attributes:
namepointsaccuracy
name
points
accuracy
Python
# Python code to create a relation # using SQLite3 # import the sqlite3 packageimport sqlite3 # create a database named backupcnt = sqlite3.connect("backup.dp") # create a table named gfgcnt.execute('''CREATE TABLE gfg(NAME TEXT,POINTS INTEGER,ACCURACY REAL);''')
Output:
This refers to the insertion of new data into the table. Data is inserted in the form of a tuple. The number of attributes in the tuple must be equal to that defined in the relation schema while creating the table.
1. To insert attributes in the order specified in the relation schema:Syntax: INSERT INTO tableName VALUES ( value1, value2, ... valuen ) 2.To insert attributes in the order specified in the relation schema or in a different order:INSERT INTO tableName ( Attribute1, Attribute3, Attribute2 . . . ) VALUES ( value1, value3, value2 . . . )
The program below demonstrates the addition of three tuples to the gfg relation that was created earlier.
Python3
# Python3 Code to insert data into# the database # Insert three tuples into the gfg table# insert in default ordercnt.execute('''INSERT INTO gfg VALUES('Count Inversion',20,80.5);''') # insert in different ordercnt.execute('''INSERT INTO gfg(ACCURACY, POINTS, NAME) VALUES(90.5, 15, 'Kadanes Algo');''') cnt.execute('''INSERT INTO gfg(NAME, ACCURACY, POINTS) VALUES('REVERSE STR', 100, 5);''') # commit changes to the databasecnt.commit()
Output:
This refers to reading data from a database. A read statement has three clauses:
SELECT: Takes as the predicate the attributes to be queried, use * for all attributes.FROM: Takes as the predicate a relation.WHERE: Takes as the predicate a condition, this is not compulsory.
SELECT: Takes as the predicate the attributes to be queried, use * for all attributes.
FROM: Takes as the predicate a relation.
WHERE: Takes as the predicate a condition, this is not compulsory.
After executing a read statement in python SQLite3, an iterable cursor object is returned. This can be used to print data.
Example: SELECT NAME, POINTS, ACCURACY FROM gfg WHERE ACCURACY>85;
The program below demonstrates the usage of the read statement.
Python3
# Python3 code to read data from a table print('Name, Points and Accuracy from ' 'records with accuracy greater than 85') cursor = cnt.execute('''SELECT * FROM gfg WHERE ACCURACY>85;''') # print data using the cursor objectfor i in cursor: print(i[0]+" "+str(i[1])+" "+str(i[2])) print('') # Print new line print('Name, Accuracy from ' 'records with accuracy greater than 85') cursor = cnt.execute('''SELECT NAME, ACCURACY FROMgfg WHERE ACCURACY>85;''') # print data using the cursor objectfor i in cursor: print(i[0]+" "+str(i[1]))
Output:
This refers to the updating of tuple values already present in the table.
Syntax: UPDATE tableName SET Attribute1 = Value1 , Attribute2 = Value2 , . . . WHERE condition;The WHERE clause must be included, else all records in the table will be updated.
EXAMPLE: UPDATE gfg SET POINTS=POINTS+5 WHERE POINTS<20;
The program below demonstrates the usage of the update statement.
Python3
# Python3 code to update records in a database # Print records before updationcursor = cnt.execute('''SELECT * FROM gfg''')print('Before Updation')for i in cursor: print(i[0]+" "+str(i[1])+" "+str(i[2])) print('') # print a newline # Execute an Update statementcnt.execute('''UPDATE gfg SET POINTS=POINTS+5 WHEREPOINTS<20;''') cursor = cnt.execute('''SELECT * FROM gfg''')print('After Updation')for i in cursor: print(i[0]+" "+str(i[1])+" "+str(i[2]))
Output:
This refers to the deletion of the tuple present in the table.
SYNTAX: DELETE FROM tableName WHERE condition
If WHERE clause is not used then all the records will be deleted.
EXAMPLE: DELETE FROM gfg WHERE ACCURACY>91
The program below demonstrates the usage of the delete statement.
Python3
# Python3 code to delete records from database # Print records before deletioncursor = cnt.execute('''SELECT * FROM gfg''')print('Before Deletion')for i in cursor: print(i[0]+" "+str(i[1])+" "+str(i[2])) print('') # print a newline # Execute a delete statementcnt.execute('''DELETE FROM gfg WHERE ACCURACY>91;''') cursor = cnt.execute('''SELECT * FROM gfg''')print('After Deletion')for i in cursor: print(i[0]+" "+str(i[1])+" "+str(i[2]))
Output:
Picked
Python-SQLite
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here. | [
{
"code": null,
"e": 28,
"s": 0,
"text": "\n21 Apr, 2021"
},
{
"code": null,
"e": 118,
"s": 28,
"text": "In this article, we will go through the CRUD Operation using the SQLite module in Python."
},
{
"code": null,
"e": 373,
"s": 118,
"text": "The abbreviation CRUD expands to Create, Read, Update and Delete. These four are fundamental operations in a database. In the sample database, we will create it, and do some operations. Let’s discuss these operations one by one with the help of examples."
},
{
"code": null,
"e": 502,
"s": 373,
"text": "The create command is used to create the table in database. First we will go through its syntax then understand with an example."
},
{
"code": null,
"e": 584,
"s": 502,
"text": "Syntax: CREATE TABLE table_name ( Attr1 Type1, Attr2 Type2, ... , Attrn Typen ) ;"
},
{
"code": null,
"e": 659,
"s": 584,
"text": "In this example, we will create a table named “gfg” with three attributes:"
},
{
"code": null,
"e": 678,
"s": 659,
"text": "namepointsaccuracy"
},
{
"code": null,
"e": 683,
"s": 678,
"text": "name"
},
{
"code": null,
"e": 690,
"s": 683,
"text": "points"
},
{
"code": null,
"e": 699,
"s": 690,
"text": "accuracy"
},
{
"code": null,
"e": 706,
"s": 699,
"text": "Python"
},
{
"code": "# Python code to create a relation # using SQLite3 # import the sqlite3 packageimport sqlite3 # create a database named backupcnt = sqlite3.connect(\"backup.dp\") # create a table named gfgcnt.execute('''CREATE TABLE gfg(NAME TEXT,POINTS INTEGER,ACCURACY REAL);''')",
"e": 977,
"s": 706,
"text": null
},
{
"code": null,
"e": 985,
"s": 977,
"text": "Output:"
},
{
"code": null,
"e": 1200,
"s": 985,
"text": "This refers to the insertion of new data into the table. Data is inserted in the form of a tuple. The number of attributes in the tuple must be equal to that defined in the relation schema while creating the table."
},
{
"code": null,
"e": 1538,
"s": 1200,
"text": "1. To insert attributes in the order specified in the relation schema:Syntax: INSERT INTO tableName VALUES ( value1, value2, ... valuen ) 2.To insert attributes in the order specified in the relation schema or in a different order:INSERT INTO tableName ( Attribute1, Attribute3, Attribute2 . . . ) VALUES ( value1, value3, value2 . . . )"
},
{
"code": null,
"e": 1644,
"s": 1538,
"text": "The program below demonstrates the addition of three tuples to the gfg relation that was created earlier."
},
{
"code": null,
"e": 1652,
"s": 1644,
"text": "Python3"
},
{
"code": "# Python3 Code to insert data into# the database # Insert three tuples into the gfg table# insert in default ordercnt.execute('''INSERT INTO gfg VALUES('Count Inversion',20,80.5);''') # insert in different ordercnt.execute('''INSERT INTO gfg(ACCURACY, POINTS, NAME) VALUES(90.5, 15, 'Kadanes Algo');''') cnt.execute('''INSERT INTO gfg(NAME, ACCURACY, POINTS) VALUES('REVERSE STR', 100, 5);''') # commit changes to the databasecnt.commit()",
"e": 2095,
"s": 1652,
"text": null
},
{
"code": null,
"e": 2103,
"s": 2095,
"text": "Output:"
},
{
"code": null,
"e": 2184,
"s": 2103,
"text": "This refers to reading data from a database. A read statement has three clauses:"
},
{
"code": null,
"e": 2377,
"s": 2184,
"text": "SELECT: Takes as the predicate the attributes to be queried, use * for all attributes.FROM: Takes as the predicate a relation.WHERE: Takes as the predicate a condition, this is not compulsory."
},
{
"code": null,
"e": 2464,
"s": 2377,
"text": "SELECT: Takes as the predicate the attributes to be queried, use * for all attributes."
},
{
"code": null,
"e": 2505,
"s": 2464,
"text": "FROM: Takes as the predicate a relation."
},
{
"code": null,
"e": 2572,
"s": 2505,
"text": "WHERE: Takes as the predicate a condition, this is not compulsory."
},
{
"code": null,
"e": 2695,
"s": 2572,
"text": "After executing a read statement in python SQLite3, an iterable cursor object is returned. This can be used to print data."
},
{
"code": null,
"e": 2762,
"s": 2695,
"text": "Example: SELECT NAME, POINTS, ACCURACY FROM gfg WHERE ACCURACY>85;"
},
{
"code": null,
"e": 2826,
"s": 2762,
"text": "The program below demonstrates the usage of the read statement."
},
{
"code": null,
"e": 2834,
"s": 2826,
"text": "Python3"
},
{
"code": "# Python3 code to read data from a table print('Name, Points and Accuracy from ' 'records with accuracy greater than 85') cursor = cnt.execute('''SELECT * FROM gfg WHERE ACCURACY>85;''') # print data using the cursor objectfor i in cursor: print(i[0]+\" \"+str(i[1])+\" \"+str(i[2])) print('') # Print new line print('Name, Accuracy from ' 'records with accuracy greater than 85') cursor = cnt.execute('''SELECT NAME, ACCURACY FROMgfg WHERE ACCURACY>85;''') # print data using the cursor objectfor i in cursor: print(i[0]+\" \"+str(i[1]))",
"e": 3399,
"s": 2834,
"text": null
},
{
"code": null,
"e": 3407,
"s": 3399,
"text": "Output:"
},
{
"code": null,
"e": 3481,
"s": 3407,
"text": "This refers to the updating of tuple values already present in the table."
},
{
"code": null,
"e": 3658,
"s": 3481,
"text": "Syntax: UPDATE tableName SET Attribute1 = Value1 , Attribute2 = Value2 , . . . WHERE condition;The WHERE clause must be included, else all records in the table will be updated."
},
{
"code": null,
"e": 3715,
"s": 3658,
"text": "EXAMPLE: UPDATE gfg SET POINTS=POINTS+5 WHERE POINTS<20;"
},
{
"code": null,
"e": 3781,
"s": 3715,
"text": "The program below demonstrates the usage of the update statement."
},
{
"code": null,
"e": 3789,
"s": 3781,
"text": "Python3"
},
{
"code": "# Python3 code to update records in a database # Print records before updationcursor = cnt.execute('''SELECT * FROM gfg''')print('Before Updation')for i in cursor: print(i[0]+\" \"+str(i[1])+\" \"+str(i[2])) print('') # print a newline # Execute an Update statementcnt.execute('''UPDATE gfg SET POINTS=POINTS+5 WHEREPOINTS<20;''') cursor = cnt.execute('''SELECT * FROM gfg''')print('After Updation')for i in cursor: print(i[0]+\" \"+str(i[1])+\" \"+str(i[2]))",
"e": 4264,
"s": 3789,
"text": null
},
{
"code": null,
"e": 4272,
"s": 4264,
"text": "Output:"
},
{
"code": null,
"e": 4335,
"s": 4272,
"text": "This refers to the deletion of the tuple present in the table."
},
{
"code": null,
"e": 4381,
"s": 4335,
"text": "SYNTAX: DELETE FROM tableName WHERE condition"
},
{
"code": null,
"e": 4447,
"s": 4381,
"text": "If WHERE clause is not used then all the records will be deleted."
},
{
"code": null,
"e": 4490,
"s": 4447,
"text": "EXAMPLE: DELETE FROM gfg WHERE ACCURACY>91"
},
{
"code": null,
"e": 4556,
"s": 4490,
"text": "The program below demonstrates the usage of the delete statement."
},
{
"code": null,
"e": 4564,
"s": 4556,
"text": "Python3"
},
{
"code": "# Python3 code to delete records from database # Print records before deletioncursor = cnt.execute('''SELECT * FROM gfg''')print('Before Deletion')for i in cursor: print(i[0]+\" \"+str(i[1])+\" \"+str(i[2])) print('') # print a newline # Execute a delete statementcnt.execute('''DELETE FROM gfg WHERE ACCURACY>91;''') cursor = cnt.execute('''SELECT * FROM gfg''')print('After Deletion')for i in cursor: print(i[0]+\" \"+str(i[1])+\" \"+str(i[2]))",
"e": 5026,
"s": 4564,
"text": null
},
{
"code": null,
"e": 5034,
"s": 5026,
"text": "Output:"
},
{
"code": null,
"e": 5041,
"s": 5034,
"text": "Picked"
},
{
"code": null,
"e": 5055,
"s": 5041,
"text": "Python-SQLite"
},
{
"code": null,
"e": 5062,
"s": 5055,
"text": "Python"
}
] |
How to pass an Array to a Function in Golang? | 25 Mar, 2021
Arrays in Golang or Go programming language is much similar to other programming languages. In the program, sometimes we need to store a collection of data of the same type, like a list of student marks. Such type of collection is stored in a program using an Array. An array is a fixed-length sequence which is used to store homogeneous elements in the memory. In Go language, you are allowed to pass an array as an argument in the function. For passing an array as an argument in the function you have to first create a formal parameter using the following syntax:
Syntax:
// For sized array
func function_name(variable_name [size]type){
// Code
}
Using this syntax you can pass 1 or multiple dimensional arrays to the function. Let us discuss this concept with the help of an example:
Example:
Go
// Go program to illustrate how to pass an// array as an argument in the functionpackage main import "fmt" // This function accept// an array as an argumentfunc myfun(a [6]int, size int) int { var k, val, r int for k = 0; k < size; k++ { val += a[k] } r = val / size return r} // Main functionfunc main() { // Creating and initializing an array var arr = [6]int{67, 59, 29, 35, 4, 34} var res int // Passing an array as an argument res = myfun(arr, 6) fmt.Printf("Final result is: %d ", res)}
Output:
Final result is: 38
Explanation: In the above example, we have a function named as myfun() which accept an array as an argument. In the main function, we passed arr[6] of int type to the function with the size of the array and the function return the average of the array.
ravikumarvallabhu
arorakashish0911
Go-Functions
Golang
Golang-Arrays
Go Language
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Different ways to concatenate two strings in Golang
time.Sleep() Function in Golang With Examples
strings.Contains Function in Golang with Examples
strings.Replace() Function in Golang With Examples
fmt.Sprintf() Function in Golang With Examples
Golang Maps
Time Formatting in Golang
Interfaces in Golang
Different Ways to Find the Type of Variable in Golang
How to convert a string in lower case in Golang? | [
{
"code": null,
"e": 28,
"s": 0,
"text": "\n25 Mar, 2021"
},
{
"code": null,
"e": 596,
"s": 28,
"text": "Arrays in Golang or Go programming language is much similar to other programming languages. In the program, sometimes we need to store a collection of data of the same type, like a list of student marks. Such type of collection is stored in a program using an Array. An array is a fixed-length sequence which is used to store homogeneous elements in the memory. In Go language, you are allowed to pass an array as an argument in the function. For passing an array as an argument in the function you have to first create a formal parameter using the following syntax: "
},
{
"code": null,
"e": 606,
"s": 596,
"text": "Syntax: "
},
{
"code": null,
"e": 681,
"s": 606,
"text": "// For sized array\nfunc function_name(variable_name [size]type){\n// Code\n}"
},
{
"code": null,
"e": 819,
"s": 681,
"text": "Using this syntax you can pass 1 or multiple dimensional arrays to the function. Let us discuss this concept with the help of an example:"
},
{
"code": null,
"e": 829,
"s": 819,
"text": "Example: "
},
{
"code": null,
"e": 832,
"s": 829,
"text": "Go"
},
{
"code": "// Go program to illustrate how to pass an// array as an argument in the functionpackage main import \"fmt\" // This function accept// an array as an argumentfunc myfun(a [6]int, size int) int { var k, val, r int for k = 0; k < size; k++ { val += a[k] } r = val / size return r} // Main functionfunc main() { // Creating and initializing an array var arr = [6]int{67, 59, 29, 35, 4, 34} var res int // Passing an array as an argument res = myfun(arr, 6) fmt.Printf(\"Final result is: %d \", res)}",
"e": 1369,
"s": 832,
"text": null
},
{
"code": null,
"e": 1378,
"s": 1369,
"text": "Output: "
},
{
"code": null,
"e": 1399,
"s": 1378,
"text": "Final result is: 38 "
},
{
"code": null,
"e": 1653,
"s": 1399,
"text": "Explanation: In the above example, we have a function named as myfun() which accept an array as an argument. In the main function, we passed arr[6] of int type to the function with the size of the array and the function return the average of the array. "
},
{
"code": null,
"e": 1671,
"s": 1653,
"text": "ravikumarvallabhu"
},
{
"code": null,
"e": 1688,
"s": 1671,
"text": "arorakashish0911"
},
{
"code": null,
"e": 1701,
"s": 1688,
"text": "Go-Functions"
},
{
"code": null,
"e": 1708,
"s": 1701,
"text": "Golang"
},
{
"code": null,
"e": 1722,
"s": 1708,
"text": "Golang-Arrays"
},
{
"code": null,
"e": 1734,
"s": 1722,
"text": "Go Language"
},
{
"code": null,
"e": 1832,
"s": 1734,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 1884,
"s": 1832,
"text": "Different ways to concatenate two strings in Golang"
},
{
"code": null,
"e": 1930,
"s": 1884,
"text": "time.Sleep() Function in Golang With Examples"
},
{
"code": null,
"e": 1980,
"s": 1930,
"text": "strings.Contains Function in Golang with Examples"
},
{
"code": null,
"e": 2031,
"s": 1980,
"text": "strings.Replace() Function in Golang With Examples"
},
{
"code": null,
"e": 2078,
"s": 2031,
"text": "fmt.Sprintf() Function in Golang With Examples"
},
{
"code": null,
"e": 2090,
"s": 2078,
"text": "Golang Maps"
},
{
"code": null,
"e": 2116,
"s": 2090,
"text": "Time Formatting in Golang"
},
{
"code": null,
"e": 2137,
"s": 2116,
"text": "Interfaces in Golang"
},
{
"code": null,
"e": 2191,
"s": 2137,
"text": "Different Ways to Find the Type of Variable in Golang"
}
] |
How to use cURL to Get JSON Data and Decode JSON Data in PHP ? | 01 Apr, 2022
In this article, we are going to see how to use cURL to Get JSON data and Decode JSON data in PHP.
cURL:
It stands for Client URL.
It is a command line tool for sending and getting files using URL syntax.
cURL allows communicating with other servers using HTTP, FTP, Telnet, and more.
Approach:
We are going to fetch JSON data from one of free website, which gives JSON data for testing i.e. reqres.in
First, we initialize curl using curl_init() method.
Sending GET request to reqres.in server using curl_setopt() method with CURLOPT_URL to get json data.
After that, we have to tell curl to store json data in a variable instead of dumping on screen. This is done by using CURLOPT_RETURNTRANSFER parameter in curl_setopt() function.
Execute curl using curl_exec() method.
At last, close the curl using curl_close() method.
Example:
PHP
<?php // Initializing curl$curl = curl_init(); // Sending GET request to reqres.in// server to get JSON datacurl_setopt($curl, CURLOPT_URL, "https://reqres.in/api/users?page=2"); // Telling curl to store JSON// data in a variable instead// of dumping on screencurl_setopt($curl, CURLOPT_RETURNTRANSFER, true); // Executing curl$response = curl_exec($curl); // Checking if any error occurs// during request or notif($e = curl_error($curl)) { echo $e;} else { // Decoding JSON data $decodedData = json_decode($response, true); // Outputting JSON data in // Decoded form var_dump($decodedData);} // Closing curlcurl_close($curl);?>
Output:
GET Request using cURL
simmytarika5
JSON
PHP-cURL
PHP-function
PHP-Questions
Picked
PHP
Web Technologies
PHP
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to execute PHP code using command line ?
PHP in_array() Function
How to delete an array element based on key in PHP?
How to Insert Form Data into Database using PHP ?
How to convert array to string in PHP ?
Installation of Node.js on Linux
Top 10 Projects For Beginners To Practice HTML and CSS Skills
Difference between var, let and const keywords in JavaScript
How to insert spaces/tabs in text using HTML/CSS?
How to fetch data from an API in ReactJS ? | [
{
"code": null,
"e": 28,
"s": 0,
"text": "\n01 Apr, 2022"
},
{
"code": null,
"e": 127,
"s": 28,
"text": "In this article, we are going to see how to use cURL to Get JSON data and Decode JSON data in PHP."
},
{
"code": null,
"e": 134,
"s": 127,
"text": "cURL: "
},
{
"code": null,
"e": 160,
"s": 134,
"text": "It stands for Client URL."
},
{
"code": null,
"e": 234,
"s": 160,
"text": "It is a command line tool for sending and getting files using URL syntax."
},
{
"code": null,
"e": 314,
"s": 234,
"text": "cURL allows communicating with other servers using HTTP, FTP, Telnet, and more."
},
{
"code": null,
"e": 324,
"s": 314,
"text": "Approach:"
},
{
"code": null,
"e": 431,
"s": 324,
"text": "We are going to fetch JSON data from one of free website, which gives JSON data for testing i.e. reqres.in"
},
{
"code": null,
"e": 483,
"s": 431,
"text": "First, we initialize curl using curl_init() method."
},
{
"code": null,
"e": 585,
"s": 483,
"text": "Sending GET request to reqres.in server using curl_setopt() method with CURLOPT_URL to get json data."
},
{
"code": null,
"e": 763,
"s": 585,
"text": "After that, we have to tell curl to store json data in a variable instead of dumping on screen. This is done by using CURLOPT_RETURNTRANSFER parameter in curl_setopt() function."
},
{
"code": null,
"e": 802,
"s": 763,
"text": "Execute curl using curl_exec() method."
},
{
"code": null,
"e": 853,
"s": 802,
"text": "At last, close the curl using curl_close() method."
},
{
"code": null,
"e": 862,
"s": 853,
"text": "Example:"
},
{
"code": null,
"e": 866,
"s": 862,
"text": "PHP"
},
{
"code": "<?php // Initializing curl$curl = curl_init(); // Sending GET request to reqres.in// server to get JSON datacurl_setopt($curl, CURLOPT_URL, \"https://reqres.in/api/users?page=2\"); // Telling curl to store JSON// data in a variable instead// of dumping on screencurl_setopt($curl, CURLOPT_RETURNTRANSFER, true); // Executing curl$response = curl_exec($curl); // Checking if any error occurs// during request or notif($e = curl_error($curl)) { echo $e;} else { // Decoding JSON data $decodedData = json_decode($response, true); // Outputting JSON data in // Decoded form var_dump($decodedData);} // Closing curlcurl_close($curl);?>",
"e": 1546,
"s": 866,
"text": null
},
{
"code": null,
"e": 1554,
"s": 1546,
"text": "Output:"
},
{
"code": null,
"e": 1577,
"s": 1554,
"text": "GET Request using cURL"
},
{
"code": null,
"e": 1590,
"s": 1577,
"text": "simmytarika5"
},
{
"code": null,
"e": 1595,
"s": 1590,
"text": "JSON"
},
{
"code": null,
"e": 1604,
"s": 1595,
"text": "PHP-cURL"
},
{
"code": null,
"e": 1617,
"s": 1604,
"text": "PHP-function"
},
{
"code": null,
"e": 1631,
"s": 1617,
"text": "PHP-Questions"
},
{
"code": null,
"e": 1638,
"s": 1631,
"text": "Picked"
},
{
"code": null,
"e": 1642,
"s": 1638,
"text": "PHP"
},
{
"code": null,
"e": 1659,
"s": 1642,
"text": "Web Technologies"
},
{
"code": null,
"e": 1663,
"s": 1659,
"text": "PHP"
},
{
"code": null,
"e": 1761,
"s": 1663,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 1806,
"s": 1761,
"text": "How to execute PHP code using command line ?"
},
{
"code": null,
"e": 1830,
"s": 1806,
"text": "PHP in_array() Function"
},
{
"code": null,
"e": 1882,
"s": 1830,
"text": "How to delete an array element based on key in PHP?"
},
{
"code": null,
"e": 1932,
"s": 1882,
"text": "How to Insert Form Data into Database using PHP ?"
},
{
"code": null,
"e": 1972,
"s": 1932,
"text": "How to convert array to string in PHP ?"
},
{
"code": null,
"e": 2005,
"s": 1972,
"text": "Installation of Node.js on Linux"
},
{
"code": null,
"e": 2067,
"s": 2005,
"text": "Top 10 Projects For Beginners To Practice HTML and CSS Skills"
},
{
"code": null,
"e": 2128,
"s": 2067,
"text": "Difference between var, let and const keywords in JavaScript"
},
{
"code": null,
"e": 2178,
"s": 2128,
"text": "How to insert spaces/tabs in text using HTML/CSS?"
}
] |
Ceiling in a sorted array | 29 Jun, 2022
Given a sorted array and a value x, the ceiling of x is the smallest element in an array greater than or equal to x, and the floor is the greatest element smaller than or equal to x. Assume that the array is sorted in non-decreasing order. Write efficient functions to find the floor and ceiling of x. Examples :
For example, let the input array be {1, 2, 8, 10, 10, 12, 19}
For x = 0: floor doesn't exist in array, ceil = 1
For x = 1: floor = 1, ceil = 1
For x = 5: floor = 2, ceil = 8
For x = 20: floor = 19, ceil doesn't exist in array
In the below methods, we have implemented only ceiling search functions. Floor search can be implemented in the same way.
Method 1 (Linear Search) Algorithm to search ceiling of x:
If x is smaller than or equal to the first element in the array then return 0(index of the first element).Else linearly search for an index i such that x lies between arr[i] and arr[i+1]. If we do not find an index i in step 2, then return -1.
If x is smaller than or equal to the first element in the array then return 0(index of the first element).
Else linearly search for an index i such that x lies between arr[i] and arr[i+1].
If we do not find an index i in step 2, then return -1.
Below is the implementation of the above approach:
C++
C
Java
Python3
C#
PHP
Javascript
// C++ implementation of above approach#include <bits/stdc++.h>using namespace std; /* Function to get index of ceiling of x in arr[low..high] */int ceilSearch(int arr[], int low, int high, int x){ int i; /* If x is smaller than or equal to first element, then return the first element */ if(x <= arr[low]) return low; /* Otherwise, linearly search for ceil value */ for(i = low; i < high; i++) { if(arr[i] == x) return i; /* if x lies between arr[i] and arr[i+1] including arr[i+1], then return arr[i+1] */ if(arr[i] < x && arr[i+1] >= x) return i+1; } /* If we reach here then x is greater than the last element of the array, return -1 in this case */ return -1;} /* Driver code*/int main(){ int arr[] = {1, 2, 8, 10, 10, 12, 19}; int n = sizeof(arr)/sizeof(arr[0]); int x = 3; int index = ceilSearch(arr, 0, n-1, x); if(index == -1) cout << "Ceiling of " << x << " doesn't exist in array "; else cout << "ceiling of " << x << " is " << arr[index]; return 0;} // This is code is contributed by rathbhupendra
#include<stdio.h> /* Function to get index of ceiling of x in arr[low..high] */int ceilSearch(int arr[], int low, int high, int x){ int i; /* If x is smaller than or equal to first element, then return the first element */ if(x <= arr[low]) return low; /* Otherwise, linearly search for ceil value */ for(i = low; i < high; i++) { if(arr[i] == x) return i; /* if x lies between arr[i] and arr[i+1] including arr[i+1], then return arr[i+1] */ if(arr[i] < x && arr[i+1] >= x) return i+1; } /* If we reach here then x is greater than the last element of the array, return -1 in this case */ return -1;} /* Driver program to check above functions */int main(){ int arr[] = {1, 2, 8, 10, 10, 12, 19}; int n = sizeof(arr)/sizeof(arr[0]); int x = 3; int index = ceilSearch(arr, 0, n-1, x); if(index == -1) printf("Ceiling of %d doesn't exist in array ", x); else printf("ceiling of %d is %d", x, arr[index]); getchar(); return 0;}
class Main{ /* Function to get index of ceiling of x in arr[low..high] */ static int ceilSearch(int arr[], int low, int high, int x) { int i; /* If x is smaller than or equal to first element,then return the first element */ if(x <= arr[low]) return low; /* Otherwise, linearly search for ceil value */ for(i = low; i < high; i++) { if(arr[i] == x) return i; /* if x lies between arr[i] and arr[i+1] including arr[i+1], then return arr[i+1] */ if(arr[i] < x && arr[i+1] >= x) return i+1; } /* If we reach here then x is greater than the last element of the array, return -1 in this case */ return -1; } /* Driver program to check above functions */ public static void main (String[] args) { int arr[] = {1, 2, 8, 10, 10, 12, 19}; int n = arr.length; int x = 3; int index = ceilSearch(arr, 0, n-1, x); if(index == -1) System.out.println("Ceiling of "+x+" doesn't exist in array"); else System.out.println("ceiling of "+x+" is "+arr[index]); } }
# Function to get index of ceiling of x in arr[low..high] */def ceilSearch(arr, low, high, x): # If x is smaller than or equal to first element, # then return the first element */ if x <= arr[low]: return low # Otherwise, linearly search for ceil value */ i = low for i in range(high): if arr[i] == x: return i # if x lies between arr[i] and arr[i+1] including # arr[i+1], then return arr[i+1] */ if arr[i] < x and arr[i+1] >= x: return i+1 # If we reach here then x is greater than the last element # of the array, return -1 in this case */ return -1 # Driver program to check above functions */arr = [1, 2, 8, 10, 10, 12, 19]n = len(arr)x = 3index = ceilSearch(arr, 0, n-1, x); if index == -1: print ("Ceiling of %d doesn't exist in array "% x)else: print ("ceiling of %d is %d"%(x, arr[index])) # This code is contributed by Shreyanshi Arun
// C# program to find ceiling// in a sorted arrayusing System; class GFG { // Function to get index of ceiling // of x in arr[low..high] static int ceilSearch(int[] arr, int low, int high, int x) { int i; // If x is smaller than or equal // to first element, then return // the first element if (x <= arr[low]) return low; // Otherwise, linearly search // for ceil value for (i = low; i < high; i++) { if (arr[i] == x) return i; /* if x lies between arr[i] and arr[i+1] including arr[i+1], then return arr[i+1] */ if (arr[i] < x && arr[i + 1] >= x) return i + 1; } /* If we reach here then x is greater than the last element of the array, return -1 in this case */ return -1; } // Driver code public static void Main() { int[] arr = { 1, 2, 8, 10, 10, 12, 19 }; int n = arr.Length; int x = 3; int index = ceilSearch(arr, 0, n - 1, x); if (index == -1) Console.Write("Ceiling of " + x + " doesn't exist in array"); else Console.Write("ceiling of " + x + " is " + arr[index]); }} // This code is contributed by Sam007.
<?php// Function to get index of// ceiling of x in arr[low..high]function ceilSearch($arr, $low, $high, $x){ // If x is smaller than or equal // to first element, then return // the first element if($x <= $arr[$low]) return $low; // Otherwise, linearly search // for ceil value for($i = $low; $i < $high; $i++) { if($arr[$i] == $x) return $i; // if x lies between arr[i] and // arr[i+1] including arr[i+1], // then return arr[i+1] if($arr[$i] < $x && $arr[$i + 1] >= $x) return $i + 1; } // If we reach here then x is greater // than the last element of the array, // return -1 in this case return -1;} // Driver Code$arr = array(1, 2, 8, 10, 10, 12, 19);$n = sizeof($arr);$x = 3;$index = ceilSearch($arr, 0, $n - 1, $x);if($index == -1) echo("Ceiling of " . $x . " doesn't exist in array ");else echo("ceiling of " . $x . " is " . $arr[$index]); // This code is contributed by Ajit.?>
<script> /* Function to get index of ceiling ofx in arr[low..high] */function ceilSearch(arr, low, high, x){ let i; /* If x is smaller than or equal to first element, then return the first element */ if(x <= arr[low]) return low; /* Otherwise, linearly search for ceil value */ for(i = low; i < high; i++) { if(arr[i] == x) return i; /* if x lies between arr[i] and arr[i+1] including arr[i+1], then return arr[i+1] */ if(arr[i] < x && arr[i+1] >= x) return i+1; } /* If we reach here then x is greater than the last element of the array, return -1 in this case */ return -1;} // driver code let arr = [1, 2, 8, 10, 10, 12, 19]; let n = arr.length; let x = 3; let index = ceilSearch(arr, 0, n-1, x); if(index == -1) document.write("Ceiling of " + x + " doesn't exist in array "); else document.write ("ceiling of " + x + " is " + arr[index]); </script>
ceiling of 3 is 8
Time Complexity: O(n), Auxiliary Space: O(1)
Method 2 (Binary Search)
Instead of using linear search, binary search is used here to find out the index. Binary search reduces the time complexity to O(Logn).
C++
C
Java
Python3
C#
PHP
Javascript
#include <bits/stdc++.h>using namespace std; /* Function to get index of ceiling of x in arr[low..high]*/int ceilSearch(int arr[], int low, int high, int x){ int mid; /* If x is smaller than or equal to the first element, then return the first element */ if (x <= arr[low]) return low; /* If x is greater than the last element, then return -1 */ if (x > arr[high]) return -1; /* get the index of middle element of arr[low..high]*/ mid = (low + high) / 2; /* low + (high - low)/2 */ /* If x is same as middle element, then return mid */ if (arr[mid] == x) return mid; /* If x is greater than arr[mid], then either arr[mid + 1] is ceiling of x or ceiling lies in arr[mid+1...high] */ else if (arr[mid] < x) { if (mid + 1 <= high && x <= arr[mid + 1]) return mid + 1; else return ceilSearch(arr, mid + 1, high, x); } /* If x is smaller than arr[mid], then either arr[mid] is ceiling of x or ceiling lies in arr[low...mid-1] */ else { if (mid - 1 >= low && x > arr[mid - 1]) return mid; else return ceilSearch(arr, low, mid - 1, x); }} // Driver Codeint main(){ int arr[] = { 1, 2, 8, 10, 10, 12, 19 }; int n = sizeof(arr) / sizeof(arr[0]); int x = 20; int index = ceilSearch(arr, 0, n - 1, x); if (index == -1) cout << "Ceiling of " << x << " doesn't exist in array "; else cout << "ceiling of " << x << " is " << arr[index]; return 0;} // This code is contributed by rathbhupendra
#include <stdio.h> /* Function to get index of ceiling of x in arr[low..high]*/int ceilSearch(int arr[], int low, int high, int x){ int mid; /* If x is smaller than or equal to the first element, then return the first element */ if (x <= arr[low]) return low; /* If x is greater than the last element, then return -1 */ if (x > arr[high]) return -1; /* get the index of middle element of arr[low..high]*/ mid = (low + high) / 2; /* low + (high - low)/2 */ /* If x is same as middle element, then return mid */ if (arr[mid] == x) return mid; /* If x is greater than arr[mid], then either arr[mid + 1] is ceiling of x or ceiling lies in arr[mid+1...high] */ else if (arr[mid] < x) { if (mid + 1 <= high && x <= arr[mid + 1]) return mid + 1; else return ceilSearch(arr, mid + 1, high, x); } /* If x is smaller than arr[mid], then either arr[mid] is ceiling of x or ceiling lies in arr[low...mid-1] */ else { if (mid - 1 >= low && x > arr[mid - 1]) return mid; else return ceilSearch(arr, low, mid - 1, x); }} /* Driver program to check above functions */int main(){ int arr[] = { 1, 2, 8, 10, 10, 12, 19 }; int n = sizeof(arr) / sizeof(arr[0]); int x = 20; int index = ceilSearch(arr, 0, n - 1, x); if (index == -1) printf("Ceiling of %d doesn't exist in array ", x); else printf("ceiling of %d is %d", x, arr[index]); getchar(); return 0;}
class Main { /* Function to get index of ceiling of x in arr[low..high]*/ static int ceilSearch(int arr[], int low, int high, int x) { // base condition if length of arr == 0 then return // -1 if (high == 0) { return -1; } /* this while loop function will run until condition not break once condition break loop will return start and ans is low which will be next smallest greater than target which is ceiling*/ while (low <= high) { int mid = low + (high - low) / 2; // calculate mid if (x == arr[mid]) { return mid; } if (x < arr[mid]) { high = mid - 1; } else { low = mid + 1; } } return low; } /* step 1 : { low = 1, 2, 8, 10= mid, 10, 12, 19= high}; if( x < mid) yes set high = mid -1; step 2 : { low = 1, 2 = mid, 8 = high, 10, 10, 12, 19}; if( x < mid) no set low = mid + 1; step 3 : {1, 2, 8 = high,low,low, 10, 10, 12, 19}; if( x == mid ) yes return mid if(x < mid ) no low = mid + 1 step 4 : {1, 2, 8 = high,mid, 10 = low, 10, 12, 19}; check while(low < = high) condition break and return low which will next greater of target */ /* Driver program to check above functions */ public static void main(String[] args) { int arr[] = { 1, 2, 8, 10, 10, 12, 19 }; int n = arr.length; int x = 8; int index = ceilSearch(arr, 0, n - 1, x); if (index == -1) System.out.println("Ceiling of " + x + " doesn't exist in array"); else System.out.println("ceiling of " + x + " is " + arr[index]); }}
# Function to get index of ceiling of x in arr[low..high]*/def ceilSearch(arr, low, high, x): # If x is smaller than or equal to the first element, # then return the first element */ if x <= arr[low]: return low # If x is greater than the last element, then return -1 */ if x > arr[high]: return -1 # get the index of middle element of arr[low..high]*/ mid = (low + high)/2; # low + (high - low)/2 */ # If x is same as middle element, then return mid */ if arr[mid] == x: return mid # If x is greater than arr[mid], then either arr[mid + 1] # is ceiling of x or ceiling lies in arr[mid+1...high] */ elif arr[mid] < x: if mid + 1 <= high and x <= arr[mid+1]: return mid + 1 else: return ceilSearch(arr, mid+1, high, x) # If x is smaller than arr[mid], then either arr[mid] # is ceiling of x or ceiling lies in arr[low...mid-1] */ else: if mid - 1 >= low and x > arr[mid-1]: return mid else: return ceilSearch(arr, low, mid - 1, x) # Driver program to check above functionsarr = [1, 2, 8, 10, 10, 12, 19]n = len(arr)x = 20index = ceilSearch(arr, 0, n-1, x); if index == -1: print ("Ceiling of %d doesn't exist in array "% x)else: print ("ceiling of %d is %d"%(x, arr[index])) # This code is contributed by Shreyanshi Arun
// C# program to find ceiling// in a sorted array using System; class GFG { // Function to get index of ceiling // of x in arr[low..high] static int ceilSearch(int[] arr, int low, int high, int x) { int mid; // If x is smaller than or equal // to the first element, then // return the first element. if (x <= arr[low]) return low; // If x is greater than the last // element, then return -1 if (x > arr[high]) return -1; // get the index of middle // element of arr[low..high] mid = (low + high) / 2; // low + (high - low)/2 // If x is same as middle // element then return mid if (arr[mid] == x) return mid; // If x is greater than arr[mid], // then either arr[mid + 1] is // ceiling of x or ceiling lies // in arr[mid+1...high] else if (arr[mid] < x) { if (mid + 1 <= high && x <= arr[mid + 1]) return mid + 1; else return ceilSearch(arr, mid + 1, high, x); } // If x is smaller than arr[mid], // then either arr[mid] is ceiling // of x or ceiling lies in // arr[low...mid-1] else { if (mid - 1 >= low && x > arr[mid - 1]) return mid; else return ceilSearch(arr, low, mid - 1, x); } } // Driver code public static void Main() { int[] arr = { 1, 2, 8, 10, 10, 12, 19 }; int n = arr.Length; int x = 8; int index = ceilSearch(arr, 0, n - 1, x); if (index == -1) Console.Write("Ceiling of " + x + " doesn't exist in array"); else Console.Write("ceiling of " + x + " is " + arr[index]); }} // This code is contributed by Sam007.
<?php// PHP Program for Ceiling in// a sorted array // Function to get index of ceiling// of x in arr[low..high]function ceilSearch($arr, $low, $high, $x){ $mid; /* If x is smaller than or equal to the first element, then return the first element */ if($x <= $arr[$low]) return $low; /* If x is greater than the last element, then return -1 */ if($x > $arr[$high]) return -1; /* get the index of middle element of arr[low..high] */ // low + (high - low)/2 $mid = ($low + $high)/2; /* If x is same as middle element, then return mid */ if($arr[$mid] == $x) return $mid; /* If x is greater than arr[mid], then either arr[mid + 1] is ceiling of x or ceiling lies in arr[mid+1...high] */ else if($arr[$mid] < $x) { if($mid + 1 <= $high && $x <= $arr[$mid + 1]) return $mid + 1; else return ceilSearch($arr, $mid + 1, $high, $x); } /* If x is smaller than arr[mid], then either arr[mid] is ceiling of x or ceiling lies in arr[low....mid-1] */ else { if($mid - 1 >= $low && $x > $arr[$mid - 1]) return $mid; else return ceilSearch($arr, $low, $mid - 1, $x); }} // Driver Code$arr = array(1, 2, 8, 10, 10, 12, 19);$n = sizeof($arr);$x = 20;$index = ceilSearch($arr, 0, $n - 1, $x);if($index == -1) echo("Ceiling of $x doesn't exist in array ");else echo("ceiling of $x is"); echo(isset($arr[$index])); // This code is contributed by nitin mittal.?>
<script>// Javascript Program for Ceiling in // a sorted array // Function to get index of ceiling// of x in arr[low..high]function ceilSearch(arr, low, high, x){ let mid; /* If x is smaller than or equal to the first element, then return the first element */ if(x <= arr[low]) return low; /* If x is greater than the last element, then return -1 */ if(x > arr[high]) return -1; /* get the index of middle element of arr[low..high] */ // low + (high - low)/2 mid = (low + high)/2; /* If x is same as middle element, then return mid */ if(arr[mid] == x) return mid; /* If x is greater than arr[mid], then either arr[mid + 1] is ceiling of x or ceiling lies in arr[mid+1...high] */ else if(arr[mid] < x) { if(mid + 1 <= high && x <= arr[mid + 1]) return mid + 1; else return ceilSearch(arr, mid + 1, high, x); } /* If x is smaller than arr[mid], then either arr[mid] is ceiling of x or ceiling lies in arr[low....mid-1] */ else { if(mid - 1 >= low && x > arr[mid - 1]) return mid; else return ceilSearch(arr, low, mid - 1, x); }} // Driver Codelet arr = [1, 2, 8, 10, 10, 12, 19];let n = arr.length;let x = 20;let index = ceilSearch(arr, 0, n - 1, x); if(index == -1){ document.write(`Ceiling of ${x} doesn't exist in array `);}else{ document.write(`ceiling of ${x} is ${arr[index]}`); } // This code is contributed by _saurabh_jaiswal. </script>
Ceiling of 20 doesn't exist in array
Time Complexity: O(log(n)), Auxiliary Space: O(1)
Another Implementation of Method 2 :
As like previous method here also binary search is being used but the code logic is different instead of lots of if else check i will simply return and lets understand through below steps :
Step 1 : { low->1, 2, 8, 10<-mid, 10, 12, 19<-high};
if( x < mid) yes set high = mid -1;
Step 2 : { low ->1, 2 <-mid, 8 <-high, 10, 10, 12, 19};
if( x < mid) no set low = mid + 1;
Step 3 : {1, 2, 8<-high,low,mid, 10, 10, 12, 19};
if( x == mid ) yes return mid
if(x < mid ) no low = mid + 1
Step 4 : {1, 2, 8<-high,mid, 10<-low, 10, 12, 19};
check while(low =< high)
condition break and return low which is my ceiling of target.
C++
Java
C#
Javascript
Python3
#include <bits/stdc++.h>using namespace std; /* Function to get index of ceiling of x in arr[low..high]*/int ceilSearch(int arr[], int low, int high, int x){ // base condition if length of arr == 0 then return -1 if (x == 0) { return -1; } int mid; /* this while loop function will run until condition not break once condition break loop will return start and ans is low which will be next smallest greater than target which is ceiling*/ while (low <= high) { mid = low + (high - low) / 2; if (arr[mid] == x) { return mid; } else if (x < arr[mid]) { high = mid - 1; } else { low = mid + 1; } } return low;} /* step 1 : { low = 1, 2, 8, 10= mid, 10, 12, 19= high}; if( x < mid) yes set high = mid -1; step 2 : { low = 1, 2 = mid, 8 = high, 10, 10, 12, 19}; if( x < mid) no set low = mid + 1; step 3 : {1, 2, 8 = high,low,low, 10, 10, 12, 19}; if( x == mid ) yes return mid if(x < mid ) no low = mid + 1 step 4 : {1, 2, 8 = high,mid, 10 = low, 10, 12, 19}; check while(low < = high) condition break and return low which will next greater of target */ /* Driver program to check above functions */int main(){ int arr[] = {1, 2, 8, 10, 10, 12, 19}; int n = sizeof(arr) / sizeof(arr[0]); int x = 8; int index = ceilSearch(arr, 0, n - 1, x); if (index == -1) { cout << "Ceiling of " << x << " does not exist in an array"; } else { cout << "Ceiling of " << x << " is " << arr[index]; } return 0;}
class Main { /* Function to get index of ceiling of x in arr[low..high]*/ static int ceilSearch(int arr[], int low, int high, int x) { // base condition if length of arr == 0 then return // -1 if (x == 0) { return -1; } /* this while loop function will run until condition not break once condition break loop will return start and ans is low which will be next smallest greater than target which is ceiling*/ while (low <= high) { int mid = low + (high - low) / 2; // calculate mid if (x == arr[mid]) { return mid; } if (x < arr[mid]) { high = mid - 1; } else { low = mid + 1; } } return low; } /* step 1 : { low = 1, 2, 8, 10= mid, 10, 12, 19= high}; if( x < mid) yes set high = mid -1; step 2 : { low = 1, 2 = mid, 8 = high, 10, 10, 12, 19}; if( x < mid) no set low = mid + 1; step 3 : {1, 2, 8 = high,low,low, 10, 10, 12, 19}; if( x == mid ) yes return mid if(x < mid ) no low = mid + 1 step 4 : {1, 2, 8 = high,mid, 10 = low, 10, 12, 19}; check while(low < = high) condition break and return low which will next greater of target */ /* Driver program to check above functions */ public static void main(String[] args) { int arr[] = { 1, 2, 8, 10, 10, 12, 19 }; int n = arr.length; int x = 8; int index = ceilSearch(arr, 0, n - 1, x); if (index == -1) System.out.println("Ceiling of " + x + " doesn't exist in array"); else System.out.println("ceiling of " + x + " is " + arr[index]); }}
// C# program for the above approach using System;class GFG{ /* Function to get index of ceiling of x in arr[low..high]*/ static int ceilSearch(int[] arr, int low, int high, int x) { // base condition if length of arr == 0 then return -1 if (x == 0) { return -1; } /* this while loop function will run until condition not break once condition break loop will return start and ans is low which will be next smallest greater than target which is ceiling*/ while (low <= high) { int mid = low + (high - low) / 2;//calculate mid if (x == arr[mid]) { return mid; } if (x < arr[mid]) { high = mid - 1; } else { low = mid + 1; } } return low; /* step 1 : { low = 1, 2, 8, 10= mid, 10, 12, 19= high}; if( x < mid) yes set high = mid -1; step 2 : { low = 1, 2 = mid, 8 = high, 10, 10, 12, 19}; if( x < mid) no set low = mid + 1; step 3 : {1, 2, 8 = high,low,low, 10, 10, 12, 19}; if( x == mid ) yes return mid if(x < mid ) no low = mid + 1 step 4 : {1, 2, 8 = high,mid, 10 = low, 10, 12, 19}; check while(low < = high) condition break and return low which will next greater of target */ } /* Driver program to check above functions */ public static void Main() { int[] arr = { 1, 2, 8, 10, 10, 12, 19 }; int n = arr.Length; int x = 8; int index = ceilSearch(arr, 0, n - 1, x); if (index == -1) Console.WriteLine("Ceiling of " + x + " doesn't exist in array"); else Console.WriteLine("ceiling of " + x + " is " + arr[index]); }}
//JS program to implement the approach /* Function to get index of ceiling of x in arr[low..high]*/function ceilSearch(arr, low, high, x){ // base condition if length of arr == 0 then return -1 if (x == 0) { return -1; } var mid; /* this while loop function will run until condition not break once condition break loop will return start and ans is low which will be next smallest greater than target which is ceiling*/ while (low <= high) { mid = low + (high - low) / 2; if (arr[mid] == x) { return mid; } else if (x < arr[mid]) { high = mid - 1; } else { low = mid + 1; } } return low;} /* step 1 : { low = 1, 2, 8, 10= mid, 10, 12, 19= high}; if( x < mid) yes set high = mid -1; step 2 : { low = 1, 2 = mid, 8 = high, 10, 10, 12, 19}; if( x < mid) no set low = mid + 1; step 3 : {1, 2, 8 = high,low,low, 10, 10, 12, 19}; if( x == mid ) yes return mid if(x < mid ) no low = mid + 1 step 4 : {1, 2, 8 = high,mid, 10 = low, 10, 12, 19}; check while(low < = high) condition break and return low which will next greater of target */ /* Driver program to check above functions */var arr = [1, 2, 8, 10, 10, 12, 19];var n = arr.length;var x = 8;var index = ceilSearch(arr, 0, n - 1, x); if (index == -1) { console.log("Ceiling of " + x + " does not exist in an array"); } else { console.log("Ceiling of " + x + " is " + arr[index]); }
# Function to get index of ceiling of x in arr[low..high]def ceilSearch(arr, low, high, x): # base condition if length of arr == 0 then return -1 if (x == 0): return -1 """this while loop function will run until condition not break once condition break loop will return start and ans is low which will be next smallest greater than target which is ceiling""" while (low <= high): mid = low + (high - low) / 2 mid = int(mid) if (arr[mid] == x): return mid elif (x < arr[mid]): high = mid - 1 else: low = mid + 1 return low """ step 1 : { low = 1, 2, 8, 10= mid, 10, 12, 19= high}; if( x < mid) yes set high = mid -1; step 2 : { low = 1, 2 = mid, 8 = high, 10, 10, 12, 19}; if( x < mid) no set low = mid + 1; step 3 : {1, 2, 8 = high,low,low, 10, 10, 12, 19}; if( x == mid ) yes return mid if(x < mid ) no low = mid + 1 step 4 : {1, 2, 8 = high,mid, 10 = low, 10, 12, 19}; check while(low < = high) condition break and return low which will next greater of target """ # Driver program to check above functionsarr = [1, 2, 8, 10, 10, 12, 19]n = len(arr)x = 8index = ceilSearch(arr, 0, n - 1, x)if (index == -1): print("Ceiling of", x, "does not exist in an array")else: print("Ceiling of", x, "is", arr[index])
Ceiling of 8 is 8
Time Complexity: O(log(n)), where n is the length of the given array, Auxiliary Space: O(1)
https://www.youtube.com/watch?v=Nzm9emAkSCM
Related Articles:
Floor in a Sorted Array Find floor and ceil in an unsorted array
Please write comments if you find any of the above codes/algorithms incorrect, find better ways to solve the same problem, or want to share code for floor implementation.
jit_t
nitin mittal
rathbhupendra
MukulSamrat
_saurabh_jaiswal
jana_sayantan
nnr223442
surindertarika1234
devendrasalunke
sagartomar9927
sumitgumber28
simmytarika5
surinderdawra388
simranarora5sos
chandramauliguptach
shaheeneallamaiqbal
phasing17
susobhanakhuli
dvrv369
Binary Search
Arrays
Searching
Arrays
Searching
Binary Search
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Arrays in Java
Write a program to reverse an array or string
Maximum and minimum of an array using minimum number of comparisons
Top 50 Array Coding Problems for Interviews
Largest Sum Contiguous Subarray
Binary Search
Maximum and minimum of an array using minimum number of comparisons
Linear Search
Search an element in a sorted and rotated array
Find the Missing Number | [
{
"code": null,
"e": 52,
"s": 24,
"text": "\n29 Jun, 2022"
},
{
"code": null,
"e": 366,
"s": 52,
"text": "Given a sorted array and a value x, the ceiling of x is the smallest element in an array greater than or equal to x, and the floor is the greatest element smaller than or equal to x. Assume that the array is sorted in non-decreasing order. Write efficient functions to find the floor and ceiling of x. Examples : "
},
{
"code": null,
"e": 613,
"s": 366,
"text": "For example, let the input array be {1, 2, 8, 10, 10, 12, 19}\nFor x = 0: floor doesn't exist in array, ceil = 1\nFor x = 1: floor = 1, ceil = 1\nFor x = 5: floor = 2, ceil = 8\nFor x = 20: floor = 19, ceil doesn't exist in array"
},
{
"code": null,
"e": 735,
"s": 613,
"text": "In the below methods, we have implemented only ceiling search functions. Floor search can be implemented in the same way."
},
{
"code": null,
"e": 795,
"s": 735,
"text": "Method 1 (Linear Search) Algorithm to search ceiling of x: "
},
{
"code": null,
"e": 1040,
"s": 795,
"text": "If x is smaller than or equal to the first element in the array then return 0(index of the first element).Else linearly search for an index i such that x lies between arr[i] and arr[i+1]. If we do not find an index i in step 2, then return -1. "
},
{
"code": null,
"e": 1147,
"s": 1040,
"text": "If x is smaller than or equal to the first element in the array then return 0(index of the first element)."
},
{
"code": null,
"e": 1230,
"s": 1147,
"text": "Else linearly search for an index i such that x lies between arr[i] and arr[i+1]. "
},
{
"code": null,
"e": 1287,
"s": 1230,
"text": "If we do not find an index i in step 2, then return -1. "
},
{
"code": null,
"e": 1338,
"s": 1287,
"text": "Below is the implementation of the above approach:"
},
{
"code": null,
"e": 1342,
"s": 1338,
"text": "C++"
},
{
"code": null,
"e": 1344,
"s": 1342,
"text": "C"
},
{
"code": null,
"e": 1349,
"s": 1344,
"text": "Java"
},
{
"code": null,
"e": 1357,
"s": 1349,
"text": "Python3"
},
{
"code": null,
"e": 1360,
"s": 1357,
"text": "C#"
},
{
"code": null,
"e": 1364,
"s": 1360,
"text": "PHP"
},
{
"code": null,
"e": 1375,
"s": 1364,
"text": "Javascript"
},
{
"code": "// C++ implementation of above approach#include <bits/stdc++.h>using namespace std; /* Function to get index of ceiling of x in arr[low..high] */int ceilSearch(int arr[], int low, int high, int x){ int i; /* If x is smaller than or equal to first element, then return the first element */ if(x <= arr[low]) return low; /* Otherwise, linearly search for ceil value */ for(i = low; i < high; i++) { if(arr[i] == x) return i; /* if x lies between arr[i] and arr[i+1] including arr[i+1], then return arr[i+1] */ if(arr[i] < x && arr[i+1] >= x) return i+1; } /* If we reach here then x is greater than the last element of the array, return -1 in this case */ return -1;} /* Driver code*/int main(){ int arr[] = {1, 2, 8, 10, 10, 12, 19}; int n = sizeof(arr)/sizeof(arr[0]); int x = 3; int index = ceilSearch(arr, 0, n-1, x); if(index == -1) cout << \"Ceiling of \" << x << \" doesn't exist in array \"; else cout << \"ceiling of \" << x << \" is \" << arr[index]; return 0;} // This is code is contributed by rathbhupendra",
"e": 2545,
"s": 1375,
"text": null
},
{
"code": "#include<stdio.h> /* Function to get index of ceiling of x in arr[low..high] */int ceilSearch(int arr[], int low, int high, int x){ int i; /* If x is smaller than or equal to first element, then return the first element */ if(x <= arr[low]) return low; /* Otherwise, linearly search for ceil value */ for(i = low; i < high; i++) { if(arr[i] == x) return i; /* if x lies between arr[i] and arr[i+1] including arr[i+1], then return arr[i+1] */ if(arr[i] < x && arr[i+1] >= x) return i+1; } /* If we reach here then x is greater than the last element of the array, return -1 in this case */ return -1;} /* Driver program to check above functions */int main(){ int arr[] = {1, 2, 8, 10, 10, 12, 19}; int n = sizeof(arr)/sizeof(arr[0]); int x = 3; int index = ceilSearch(arr, 0, n-1, x); if(index == -1) printf(\"Ceiling of %d doesn't exist in array \", x); else printf(\"ceiling of %d is %d\", x, arr[index]); getchar(); return 0;}",
"e": 3555,
"s": 2545,
"text": null
},
{
"code": "class Main{ /* Function to get index of ceiling of x in arr[low..high] */ static int ceilSearch(int arr[], int low, int high, int x) { int i; /* If x is smaller than or equal to first element,then return the first element */ if(x <= arr[low]) return low; /* Otherwise, linearly search for ceil value */ for(i = low; i < high; i++) { if(arr[i] == x) return i; /* if x lies between arr[i] and arr[i+1] including arr[i+1], then return arr[i+1] */ if(arr[i] < x && arr[i+1] >= x) return i+1; } /* If we reach here then x is greater than the last element of the array, return -1 in this case */ return -1; } /* Driver program to check above functions */ public static void main (String[] args) { int arr[] = {1, 2, 8, 10, 10, 12, 19}; int n = arr.length; int x = 3; int index = ceilSearch(arr, 0, n-1, x); if(index == -1) System.out.println(\"Ceiling of \"+x+\" doesn't exist in array\"); else System.out.println(\"ceiling of \"+x+\" is \"+arr[index]); } }",
"e": 4742,
"s": 3555,
"text": null
},
{
"code": "# Function to get index of ceiling of x in arr[low..high] */def ceilSearch(arr, low, high, x): # If x is smaller than or equal to first element, # then return the first element */ if x <= arr[low]: return low # Otherwise, linearly search for ceil value */ i = low for i in range(high): if arr[i] == x: return i # if x lies between arr[i] and arr[i+1] including # arr[i+1], then return arr[i+1] */ if arr[i] < x and arr[i+1] >= x: return i+1 # If we reach here then x is greater than the last element # of the array, return -1 in this case */ return -1 # Driver program to check above functions */arr = [1, 2, 8, 10, 10, 12, 19]n = len(arr)x = 3index = ceilSearch(arr, 0, n-1, x); if index == -1: print (\"Ceiling of %d doesn't exist in array \"% x)else: print (\"ceiling of %d is %d\"%(x, arr[index])) # This code is contributed by Shreyanshi Arun",
"e": 5689,
"s": 4742,
"text": null
},
{
"code": "// C# program to find ceiling// in a sorted arrayusing System; class GFG { // Function to get index of ceiling // of x in arr[low..high] static int ceilSearch(int[] arr, int low, int high, int x) { int i; // If x is smaller than or equal // to first element, then return // the first element if (x <= arr[low]) return low; // Otherwise, linearly search // for ceil value for (i = low; i < high; i++) { if (arr[i] == x) return i; /* if x lies between arr[i] and arr[i+1] including arr[i+1], then return arr[i+1] */ if (arr[i] < x && arr[i + 1] >= x) return i + 1; } /* If we reach here then x is greater than the last element of the array, return -1 in this case */ return -1; } // Driver code public static void Main() { int[] arr = { 1, 2, 8, 10, 10, 12, 19 }; int n = arr.Length; int x = 3; int index = ceilSearch(arr, 0, n - 1, x); if (index == -1) Console.Write(\"Ceiling of \" + x + \" doesn't exist in array\"); else Console.Write(\"ceiling of \" + x + \" is \" + arr[index]); }} // This code is contributed by Sam007.",
"e": 7080,
"s": 5689,
"text": null
},
{
"code": "<?php// Function to get index of// ceiling of x in arr[low..high]function ceilSearch($arr, $low, $high, $x){ // If x is smaller than or equal // to first element, then return // the first element if($x <= $arr[$low]) return $low; // Otherwise, linearly search // for ceil value for($i = $low; $i < $high; $i++) { if($arr[$i] == $x) return $i; // if x lies between arr[i] and // arr[i+1] including arr[i+1], // then return arr[i+1] if($arr[$i] < $x && $arr[$i + 1] >= $x) return $i + 1; } // If we reach here then x is greater // than the last element of the array, // return -1 in this case return -1;} // Driver Code$arr = array(1, 2, 8, 10, 10, 12, 19);$n = sizeof($arr);$x = 3;$index = ceilSearch($arr, 0, $n - 1, $x);if($index == -1) echo(\"Ceiling of \" . $x . \" doesn't exist in array \");else echo(\"ceiling of \" . $x . \" is \" . $arr[$index]); // This code is contributed by Ajit.?>",
"e": 8136,
"s": 7080,
"text": null
},
{
"code": "<script> /* Function to get index of ceiling ofx in arr[low..high] */function ceilSearch(arr, low, high, x){ let i; /* If x is smaller than or equal to first element, then return the first element */ if(x <= arr[low]) return low; /* Otherwise, linearly search for ceil value */ for(i = low; i < high; i++) { if(arr[i] == x) return i; /* if x lies between arr[i] and arr[i+1] including arr[i+1], then return arr[i+1] */ if(arr[i] < x && arr[i+1] >= x) return i+1; } /* If we reach here then x is greater than the last element of the array, return -1 in this case */ return -1;} // driver code let arr = [1, 2, 8, 10, 10, 12, 19]; let n = arr.length; let x = 3; let index = ceilSearch(arr, 0, n-1, x); if(index == -1) document.write(\"Ceiling of \" + x + \" doesn't exist in array \"); else document.write (\"ceiling of \" + x + \" is \" + arr[index]); </script>",
"e": 9150,
"s": 8136,
"text": null
},
{
"code": null,
"e": 9168,
"s": 9150,
"text": "ceiling of 3 is 8"
},
{
"code": null,
"e": 9213,
"s": 9168,
"text": "Time Complexity: O(n), Auxiliary Space: O(1)"
},
{
"code": null,
"e": 9239,
"s": 9213,
"text": "Method 2 (Binary Search) "
},
{
"code": null,
"e": 9376,
"s": 9239,
"text": "Instead of using linear search, binary search is used here to find out the index. Binary search reduces the time complexity to O(Logn). "
},
{
"code": null,
"e": 9380,
"s": 9376,
"text": "C++"
},
{
"code": null,
"e": 9382,
"s": 9380,
"text": "C"
},
{
"code": null,
"e": 9387,
"s": 9382,
"text": "Java"
},
{
"code": null,
"e": 9395,
"s": 9387,
"text": "Python3"
},
{
"code": null,
"e": 9398,
"s": 9395,
"text": "C#"
},
{
"code": null,
"e": 9402,
"s": 9398,
"text": "PHP"
},
{
"code": null,
"e": 9413,
"s": 9402,
"text": "Javascript"
},
{
"code": "#include <bits/stdc++.h>using namespace std; /* Function to get index of ceiling of x in arr[low..high]*/int ceilSearch(int arr[], int low, int high, int x){ int mid; /* If x is smaller than or equal to the first element, then return the first element */ if (x <= arr[low]) return low; /* If x is greater than the last element, then return -1 */ if (x > arr[high]) return -1; /* get the index of middle element of arr[low..high]*/ mid = (low + high) / 2; /* low + (high - low)/2 */ /* If x is same as middle element, then return mid */ if (arr[mid] == x) return mid; /* If x is greater than arr[mid], then either arr[mid + 1] is ceiling of x or ceiling lies in arr[mid+1...high] */ else if (arr[mid] < x) { if (mid + 1 <= high && x <= arr[mid + 1]) return mid + 1; else return ceilSearch(arr, mid + 1, high, x); } /* If x is smaller than arr[mid], then either arr[mid] is ceiling of x or ceiling lies in arr[low...mid-1] */ else { if (mid - 1 >= low && x > arr[mid - 1]) return mid; else return ceilSearch(arr, low, mid - 1, x); }} // Driver Codeint main(){ int arr[] = { 1, 2, 8, 10, 10, 12, 19 }; int n = sizeof(arr) / sizeof(arr[0]); int x = 20; int index = ceilSearch(arr, 0, n - 1, x); if (index == -1) cout << \"Ceiling of \" << x << \" doesn't exist in array \"; else cout << \"ceiling of \" << x << \" is \" << arr[index]; return 0;} // This code is contributed by rathbhupendra",
"e": 11034,
"s": 9413,
"text": null
},
{
"code": "#include <stdio.h> /* Function to get index of ceiling of x in arr[low..high]*/int ceilSearch(int arr[], int low, int high, int x){ int mid; /* If x is smaller than or equal to the first element, then return the first element */ if (x <= arr[low]) return low; /* If x is greater than the last element, then return -1 */ if (x > arr[high]) return -1; /* get the index of middle element of arr[low..high]*/ mid = (low + high) / 2; /* low + (high - low)/2 */ /* If x is same as middle element, then return mid */ if (arr[mid] == x) return mid; /* If x is greater than arr[mid], then either arr[mid + 1] is ceiling of x or ceiling lies in arr[mid+1...high] */ else if (arr[mid] < x) { if (mid + 1 <= high && x <= arr[mid + 1]) return mid + 1; else return ceilSearch(arr, mid + 1, high, x); } /* If x is smaller than arr[mid], then either arr[mid] is ceiling of x or ceiling lies in arr[low...mid-1] */ else { if (mid - 1 >= low && x > arr[mid - 1]) return mid; else return ceilSearch(arr, low, mid - 1, x); }} /* Driver program to check above functions */int main(){ int arr[] = { 1, 2, 8, 10, 10, 12, 19 }; int n = sizeof(arr) / sizeof(arr[0]); int x = 20; int index = ceilSearch(arr, 0, n - 1, x); if (index == -1) printf(\"Ceiling of %d doesn't exist in array \", x); else printf(\"ceiling of %d is %d\", x, arr[index]); getchar(); return 0;}",
"e": 12583,
"s": 11034,
"text": null
},
{
"code": "class Main { /* Function to get index of ceiling of x in arr[low..high]*/ static int ceilSearch(int arr[], int low, int high, int x) { // base condition if length of arr == 0 then return // -1 if (high == 0) { return -1; } /* this while loop function will run until condition not break once condition break loop will return start and ans is low which will be next smallest greater than target which is ceiling*/ while (low <= high) { int mid = low + (high - low) / 2; // calculate mid if (x == arr[mid]) { return mid; } if (x < arr[mid]) { high = mid - 1; } else { low = mid + 1; } } return low; } /* step 1 : { low = 1, 2, 8, 10= mid, 10, 12, 19= high}; if( x < mid) yes set high = mid -1; step 2 : { low = 1, 2 = mid, 8 = high, 10, 10, 12, 19}; if( x < mid) no set low = mid + 1; step 3 : {1, 2, 8 = high,low,low, 10, 10, 12, 19}; if( x == mid ) yes return mid if(x < mid ) no low = mid + 1 step 4 : {1, 2, 8 = high,mid, 10 = low, 10, 12, 19}; check while(low < = high) condition break and return low which will next greater of target */ /* Driver program to check above functions */ public static void main(String[] args) { int arr[] = { 1, 2, 8, 10, 10, 12, 19 }; int n = arr.length; int x = 8; int index = ceilSearch(arr, 0, n - 1, x); if (index == -1) System.out.println(\"Ceiling of \" + x + \" doesn't exist in array\"); else System.out.println(\"ceiling of \" + x + \" is \" + arr[index]); }}",
"e": 14485,
"s": 12583,
"text": null
},
{
"code": "# Function to get index of ceiling of x in arr[low..high]*/def ceilSearch(arr, low, high, x): # If x is smaller than or equal to the first element, # then return the first element */ if x <= arr[low]: return low # If x is greater than the last element, then return -1 */ if x > arr[high]: return -1 # get the index of middle element of arr[low..high]*/ mid = (low + high)/2; # low + (high - low)/2 */ # If x is same as middle element, then return mid */ if arr[mid] == x: return mid # If x is greater than arr[mid], then either arr[mid + 1] # is ceiling of x or ceiling lies in arr[mid+1...high] */ elif arr[mid] < x: if mid + 1 <= high and x <= arr[mid+1]: return mid + 1 else: return ceilSearch(arr, mid+1, high, x) # If x is smaller than arr[mid], then either arr[mid] # is ceiling of x or ceiling lies in arr[low...mid-1] */ else: if mid - 1 >= low and x > arr[mid-1]: return mid else: return ceilSearch(arr, low, mid - 1, x) # Driver program to check above functionsarr = [1, 2, 8, 10, 10, 12, 19]n = len(arr)x = 20index = ceilSearch(arr, 0, n-1, x); if index == -1: print (\"Ceiling of %d doesn't exist in array \"% x)else: print (\"ceiling of %d is %d\"%(x, arr[index])) # This code is contributed by Shreyanshi Arun",
"e": 15863,
"s": 14485,
"text": null
},
{
"code": "// C# program to find ceiling// in a sorted array using System; class GFG { // Function to get index of ceiling // of x in arr[low..high] static int ceilSearch(int[] arr, int low, int high, int x) { int mid; // If x is smaller than or equal // to the first element, then // return the first element. if (x <= arr[low]) return low; // If x is greater than the last // element, then return -1 if (x > arr[high]) return -1; // get the index of middle // element of arr[low..high] mid = (low + high) / 2; // low + (high - low)/2 // If x is same as middle // element then return mid if (arr[mid] == x) return mid; // If x is greater than arr[mid], // then either arr[mid + 1] is // ceiling of x or ceiling lies // in arr[mid+1...high] else if (arr[mid] < x) { if (mid + 1 <= high && x <= arr[mid + 1]) return mid + 1; else return ceilSearch(arr, mid + 1, high, x); } // If x is smaller than arr[mid], // then either arr[mid] is ceiling // of x or ceiling lies in // arr[low...mid-1] else { if (mid - 1 >= low && x > arr[mid - 1]) return mid; else return ceilSearch(arr, low, mid - 1, x); } } // Driver code public static void Main() { int[] arr = { 1, 2, 8, 10, 10, 12, 19 }; int n = arr.Length; int x = 8; int index = ceilSearch(arr, 0, n - 1, x); if (index == -1) Console.Write(\"Ceiling of \" + x + \" doesn't exist in array\"); else Console.Write(\"ceiling of \" + x + \" is \" + arr[index]); }} // This code is contributed by Sam007.",
"e": 17790,
"s": 15863,
"text": null
},
{
"code": "<?php// PHP Program for Ceiling in// a sorted array // Function to get index of ceiling// of x in arr[low..high]function ceilSearch($arr, $low, $high, $x){ $mid; /* If x is smaller than or equal to the first element, then return the first element */ if($x <= $arr[$low]) return $low; /* If x is greater than the last element, then return -1 */ if($x > $arr[$high]) return -1; /* get the index of middle element of arr[low..high] */ // low + (high - low)/2 $mid = ($low + $high)/2; /* If x is same as middle element, then return mid */ if($arr[$mid] == $x) return $mid; /* If x is greater than arr[mid], then either arr[mid + 1] is ceiling of x or ceiling lies in arr[mid+1...high] */ else if($arr[$mid] < $x) { if($mid + 1 <= $high && $x <= $arr[$mid + 1]) return $mid + 1; else return ceilSearch($arr, $mid + 1, $high, $x); } /* If x is smaller than arr[mid], then either arr[mid] is ceiling of x or ceiling lies in arr[low....mid-1] */ else { if($mid - 1 >= $low && $x > $arr[$mid - 1]) return $mid; else return ceilSearch($arr, $low, $mid - 1, $x); }} // Driver Code$arr = array(1, 2, 8, 10, 10, 12, 19);$n = sizeof($arr);$x = 20;$index = ceilSearch($arr, 0, $n - 1, $x);if($index == -1) echo(\"Ceiling of $x doesn't exist in array \");else echo(\"ceiling of $x is\"); echo(isset($arr[$index])); // This code is contributed by nitin mittal.?>",
"e": 19488,
"s": 17790,
"text": null
},
{
"code": "<script>// Javascript Program for Ceiling in // a sorted array // Function to get index of ceiling// of x in arr[low..high]function ceilSearch(arr, low, high, x){ let mid; /* If x is smaller than or equal to the first element, then return the first element */ if(x <= arr[low]) return low; /* If x is greater than the last element, then return -1 */ if(x > arr[high]) return -1; /* get the index of middle element of arr[low..high] */ // low + (high - low)/2 mid = (low + high)/2; /* If x is same as middle element, then return mid */ if(arr[mid] == x) return mid; /* If x is greater than arr[mid], then either arr[mid + 1] is ceiling of x or ceiling lies in arr[mid+1...high] */ else if(arr[mid] < x) { if(mid + 1 <= high && x <= arr[mid + 1]) return mid + 1; else return ceilSearch(arr, mid + 1, high, x); } /* If x is smaller than arr[mid], then either arr[mid] is ceiling of x or ceiling lies in arr[low....mid-1] */ else { if(mid - 1 >= low && x > arr[mid - 1]) return mid; else return ceilSearch(arr, low, mid - 1, x); }} // Driver Codelet arr = [1, 2, 8, 10, 10, 12, 19];let n = arr.length;let x = 20;let index = ceilSearch(arr, 0, n - 1, x); if(index == -1){ document.write(`Ceiling of ${x} doesn't exist in array `);}else{ document.write(`ceiling of ${x} is ${arr[index]}`); } // This code is contributed by _saurabh_jaiswal. </script>",
"e": 21116,
"s": 19488,
"text": null
},
{
"code": null,
"e": 21154,
"s": 21116,
"text": "Ceiling of 20 doesn't exist in array "
},
{
"code": null,
"e": 21204,
"s": 21154,
"text": "Time Complexity: O(log(n)), Auxiliary Space: O(1)"
},
{
"code": null,
"e": 21241,
"s": 21204,
"text": "Another Implementation of Method 2 :"
},
{
"code": null,
"e": 21431,
"s": 21241,
"text": "As like previous method here also binary search is being used but the code logic is different instead of lots of if else check i will simply return and lets understand through below steps :"
},
{
"code": null,
"e": 21484,
"s": 21431,
"text": "Step 1 : { low->1, 2, 8, 10<-mid, 10, 12, 19<-high};"
},
{
"code": null,
"e": 21520,
"s": 21484,
"text": "if( x < mid) yes set high = mid -1;"
},
{
"code": null,
"e": 21576,
"s": 21520,
"text": "Step 2 : { low ->1, 2 <-mid, 8 <-high, 10, 10, 12, 19};"
},
{
"code": null,
"e": 21611,
"s": 21576,
"text": "if( x < mid) no set low = mid + 1;"
},
{
"code": null,
"e": 21662,
"s": 21611,
"text": "Step 3 : {1, 2, 8<-high,low,mid, 10, 10, 12, 19};"
},
{
"code": null,
"e": 21724,
"s": 21662,
"text": "if( x == mid ) yes return mid \nif(x < mid ) no low = mid + 1"
},
{
"code": null,
"e": 21776,
"s": 21724,
"text": "Step 4 : {1, 2, 8<-high,mid, 10<-low, 10, 12, 19};"
},
{
"code": null,
"e": 21802,
"s": 21776,
"text": "check while(low =< high)"
},
{
"code": null,
"e": 21865,
"s": 21802,
"text": "condition break and return low which is my ceiling of target."
},
{
"code": null,
"e": 21869,
"s": 21865,
"text": "C++"
},
{
"code": null,
"e": 21874,
"s": 21869,
"text": "Java"
},
{
"code": null,
"e": 21877,
"s": 21874,
"text": "C#"
},
{
"code": null,
"e": 21888,
"s": 21877,
"text": "Javascript"
},
{
"code": null,
"e": 21896,
"s": 21888,
"text": "Python3"
},
{
"code": "#include <bits/stdc++.h>using namespace std; /* Function to get index of ceiling of x in arr[low..high]*/int ceilSearch(int arr[], int low, int high, int x){ // base condition if length of arr == 0 then return -1 if (x == 0) { return -1; } int mid; /* this while loop function will run until condition not break once condition break loop will return start and ans is low which will be next smallest greater than target which is ceiling*/ while (low <= high) { mid = low + (high - low) / 2; if (arr[mid] == x) { return mid; } else if (x < arr[mid]) { high = mid - 1; } else { low = mid + 1; } } return low;} /* step 1 : { low = 1, 2, 8, 10= mid, 10, 12, 19= high}; if( x < mid) yes set high = mid -1; step 2 : { low = 1, 2 = mid, 8 = high, 10, 10, 12, 19}; if( x < mid) no set low = mid + 1; step 3 : {1, 2, 8 = high,low,low, 10, 10, 12, 19}; if( x == mid ) yes return mid if(x < mid ) no low = mid + 1 step 4 : {1, 2, 8 = high,mid, 10 = low, 10, 12, 19}; check while(low < = high) condition break and return low which will next greater of target */ /* Driver program to check above functions */int main(){ int arr[] = {1, 2, 8, 10, 10, 12, 19}; int n = sizeof(arr) / sizeof(arr[0]); int x = 8; int index = ceilSearch(arr, 0, n - 1, x); if (index == -1) { cout << \"Ceiling of \" << x << \" does not exist in an array\"; } else { cout << \"Ceiling of \" << x << \" is \" << arr[index]; } return 0;}",
"e": 23501,
"s": 21896,
"text": null
},
{
"code": "class Main { /* Function to get index of ceiling of x in arr[low..high]*/ static int ceilSearch(int arr[], int low, int high, int x) { // base condition if length of arr == 0 then return // -1 if (x == 0) { return -1; } /* this while loop function will run until condition not break once condition break loop will return start and ans is low which will be next smallest greater than target which is ceiling*/ while (low <= high) { int mid = low + (high - low) / 2; // calculate mid if (x == arr[mid]) { return mid; } if (x < arr[mid]) { high = mid - 1; } else { low = mid + 1; } } return low; } /* step 1 : { low = 1, 2, 8, 10= mid, 10, 12, 19= high}; if( x < mid) yes set high = mid -1; step 2 : { low = 1, 2 = mid, 8 = high, 10, 10, 12, 19}; if( x < mid) no set low = mid + 1; step 3 : {1, 2, 8 = high,low,low, 10, 10, 12, 19}; if( x == mid ) yes return mid if(x < mid ) no low = mid + 1 step 4 : {1, 2, 8 = high,mid, 10 = low, 10, 12, 19}; check while(low < = high) condition break and return low which will next greater of target */ /* Driver program to check above functions */ public static void main(String[] args) { int arr[] = { 1, 2, 8, 10, 10, 12, 19 }; int n = arr.length; int x = 8; int index = ceilSearch(arr, 0, n - 1, x); if (index == -1) System.out.println(\"Ceiling of \" + x + \" doesn't exist in array\"); else System.out.println(\"ceiling of \" + x + \" is \" + arr[index]); }}",
"e": 25400,
"s": 23501,
"text": null
},
{
"code": "// C# program for the above approach using System;class GFG{ /* Function to get index of ceiling of x in arr[low..high]*/ static int ceilSearch(int[] arr, int low, int high, int x) { // base condition if length of arr == 0 then return -1 if (x == 0) { return -1; } /* this while loop function will run until condition not break once condition break loop will return start and ans is low which will be next smallest greater than target which is ceiling*/ while (low <= high) { int mid = low + (high - low) / 2;//calculate mid if (x == arr[mid]) { return mid; } if (x < arr[mid]) { high = mid - 1; } else { low = mid + 1; } } return low; /* step 1 : { low = 1, 2, 8, 10= mid, 10, 12, 19= high}; if( x < mid) yes set high = mid -1; step 2 : { low = 1, 2 = mid, 8 = high, 10, 10, 12, 19}; if( x < mid) no set low = mid + 1; step 3 : {1, 2, 8 = high,low,low, 10, 10, 12, 19}; if( x == mid ) yes return mid if(x < mid ) no low = mid + 1 step 4 : {1, 2, 8 = high,mid, 10 = low, 10, 12, 19}; check while(low < = high) condition break and return low which will next greater of target */ } /* Driver program to check above functions */ public static void Main() { int[] arr = { 1, 2, 8, 10, 10, 12, 19 }; int n = arr.Length; int x = 8; int index = ceilSearch(arr, 0, n - 1, x); if (index == -1) Console.WriteLine(\"Ceiling of \" + x + \" doesn't exist in array\"); else Console.WriteLine(\"ceiling of \" + x + \" is \" + arr[index]); }}",
"e": 27117,
"s": 25400,
"text": null
},
{
"code": "//JS program to implement the approach /* Function to get index of ceiling of x in arr[low..high]*/function ceilSearch(arr, low, high, x){ // base condition if length of arr == 0 then return -1 if (x == 0) { return -1; } var mid; /* this while loop function will run until condition not break once condition break loop will return start and ans is low which will be next smallest greater than target which is ceiling*/ while (low <= high) { mid = low + (high - low) / 2; if (arr[mid] == x) { return mid; } else if (x < arr[mid]) { high = mid - 1; } else { low = mid + 1; } } return low;} /* step 1 : { low = 1, 2, 8, 10= mid, 10, 12, 19= high}; if( x < mid) yes set high = mid -1; step 2 : { low = 1, 2 = mid, 8 = high, 10, 10, 12, 19}; if( x < mid) no set low = mid + 1; step 3 : {1, 2, 8 = high,low,low, 10, 10, 12, 19}; if( x == mid ) yes return mid if(x < mid ) no low = mid + 1 step 4 : {1, 2, 8 = high,mid, 10 = low, 10, 12, 19}; check while(low < = high) condition break and return low which will next greater of target */ /* Driver program to check above functions */var arr = [1, 2, 8, 10, 10, 12, 19];var n = arr.length;var x = 8;var index = ceilSearch(arr, 0, n - 1, x); if (index == -1) { console.log(\"Ceiling of \" + x + \" does not exist in an array\"); } else { console.log(\"Ceiling of \" + x + \" is \" + arr[index]); }",
"e": 28657,
"s": 27117,
"text": null
},
{
"code": "# Function to get index of ceiling of x in arr[low..high]def ceilSearch(arr, low, high, x): # base condition if length of arr == 0 then return -1 if (x == 0): return -1 \"\"\"this while loop function will run until condition not break once condition break loop will return start and ans is low which will be next smallest greater than target which is ceiling\"\"\" while (low <= high): mid = low + (high - low) / 2 mid = int(mid) if (arr[mid] == x): return mid elif (x < arr[mid]): high = mid - 1 else: low = mid + 1 return low \"\"\" step 1 : { low = 1, 2, 8, 10= mid, 10, 12, 19= high}; if( x < mid) yes set high = mid -1; step 2 : { low = 1, 2 = mid, 8 = high, 10, 10, 12, 19}; if( x < mid) no set low = mid + 1; step 3 : {1, 2, 8 = high,low,low, 10, 10, 12, 19}; if( x == mid ) yes return mid if(x < mid ) no low = mid + 1 step 4 : {1, 2, 8 = high,mid, 10 = low, 10, 12, 19}; check while(low < = high) condition break and return low which will next greater of target \"\"\" # Driver program to check above functionsarr = [1, 2, 8, 10, 10, 12, 19]n = len(arr)x = 8index = ceilSearch(arr, 0, n - 1, x)if (index == -1): print(\"Ceiling of\", x, \"does not exist in an array\")else: print(\"Ceiling of\", x, \"is\", arr[index])",
"e": 30092,
"s": 28657,
"text": null
},
{
"code": null,
"e": 30110,
"s": 30092,
"text": "Ceiling of 8 is 8"
},
{
"code": null,
"e": 30202,
"s": 30110,
"text": "Time Complexity: O(log(n)), where n is the length of the given array, Auxiliary Space: O(1)"
},
{
"code": null,
"e": 30246,
"s": 30202,
"text": "https://www.youtube.com/watch?v=Nzm9emAkSCM"
},
{
"code": null,
"e": 30265,
"s": 30246,
"text": "Related Articles: "
},
{
"code": null,
"e": 30330,
"s": 30265,
"text": "Floor in a Sorted Array Find floor and ceil in an unsorted array"
},
{
"code": null,
"e": 30501,
"s": 30330,
"text": "Please write comments if you find any of the above codes/algorithms incorrect, find better ways to solve the same problem, or want to share code for floor implementation."
},
{
"code": null,
"e": 30507,
"s": 30501,
"text": "jit_t"
},
{
"code": null,
"e": 30520,
"s": 30507,
"text": "nitin mittal"
},
{
"code": null,
"e": 30534,
"s": 30520,
"text": "rathbhupendra"
},
{
"code": null,
"e": 30546,
"s": 30534,
"text": "MukulSamrat"
},
{
"code": null,
"e": 30563,
"s": 30546,
"text": "_saurabh_jaiswal"
},
{
"code": null,
"e": 30577,
"s": 30563,
"text": "jana_sayantan"
},
{
"code": null,
"e": 30587,
"s": 30577,
"text": "nnr223442"
},
{
"code": null,
"e": 30606,
"s": 30587,
"text": "surindertarika1234"
},
{
"code": null,
"e": 30622,
"s": 30606,
"text": "devendrasalunke"
},
{
"code": null,
"e": 30637,
"s": 30622,
"text": "sagartomar9927"
},
{
"code": null,
"e": 30651,
"s": 30637,
"text": "sumitgumber28"
},
{
"code": null,
"e": 30664,
"s": 30651,
"text": "simmytarika5"
},
{
"code": null,
"e": 30681,
"s": 30664,
"text": "surinderdawra388"
},
{
"code": null,
"e": 30697,
"s": 30681,
"text": "simranarora5sos"
},
{
"code": null,
"e": 30717,
"s": 30697,
"text": "chandramauliguptach"
},
{
"code": null,
"e": 30737,
"s": 30717,
"text": "shaheeneallamaiqbal"
},
{
"code": null,
"e": 30747,
"s": 30737,
"text": "phasing17"
},
{
"code": null,
"e": 30762,
"s": 30747,
"text": "susobhanakhuli"
},
{
"code": null,
"e": 30770,
"s": 30762,
"text": "dvrv369"
},
{
"code": null,
"e": 30784,
"s": 30770,
"text": "Binary Search"
},
{
"code": null,
"e": 30791,
"s": 30784,
"text": "Arrays"
},
{
"code": null,
"e": 30801,
"s": 30791,
"text": "Searching"
},
{
"code": null,
"e": 30808,
"s": 30801,
"text": "Arrays"
},
{
"code": null,
"e": 30818,
"s": 30808,
"text": "Searching"
},
{
"code": null,
"e": 30832,
"s": 30818,
"text": "Binary Search"
},
{
"code": null,
"e": 30930,
"s": 30832,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 30945,
"s": 30930,
"text": "Arrays in Java"
},
{
"code": null,
"e": 30991,
"s": 30945,
"text": "Write a program to reverse an array or string"
},
{
"code": null,
"e": 31059,
"s": 30991,
"text": "Maximum and minimum of an array using minimum number of comparisons"
},
{
"code": null,
"e": 31103,
"s": 31059,
"text": "Top 50 Array Coding Problems for Interviews"
},
{
"code": null,
"e": 31135,
"s": 31103,
"text": "Largest Sum Contiguous Subarray"
},
{
"code": null,
"e": 31149,
"s": 31135,
"text": "Binary Search"
},
{
"code": null,
"e": 31217,
"s": 31149,
"text": "Maximum and minimum of an array using minimum number of comparisons"
},
{
"code": null,
"e": 31231,
"s": 31217,
"text": "Linear Search"
},
{
"code": null,
"e": 31279,
"s": 31231,
"text": "Search an element in a sorted and rotated array"
}
] |
Reverse Diagonal elements of matrix | 28 Apr, 2021
Given a square matrix of order n*n, we have to reverse the elements of both diagonals.Examples:
Input : {1, 2, 3,
4, 5, 6,
7, 8, 9}
Output :{9, 2, 7,
4, 5, 6,
3, 8, 1}
Explanation:
Major Diagonal Elements before: 1 5 9
After reverse: 9 5 1
Minor Diagonal Elements before: 3 5 7
After reverse: 7 5 3
Input :{1, 2, 3, 4,
5, 6, 7, 8,
9, 10, 11, 12,
13, 14, 15, 16}
Output :{16, 2, 3, 13,
5, 11, 10, 8,
9, 7, 6, 12,
4, 14, 15, 1}
C++
Java
Python 3
C#
PHP
Javascript
#include <bits/stdc++.h>using namespace std;#define N 4 // Function to swap diagonals elementsvoid reverseDiagonal(int array[][N]){ int i = 0, j = N; while (i < j) { // For reversing elements of major // diagonal. swap(array[i][i], array[j - 1][j - 1]); // For reversing elements of minor // diagonal. swap(array[i][j - 1], array[j - 1][i]); i++; j--; } // Print matrix after reversals. for (int i = 0; i < N; ++i) { for (int j = 0; j < N; ++j) printf("%d ", array[i][j]); printf("\n"); }} // Driver functionint main(){ int matrix[N][N] = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16 }; reverseDiagonal(matrix); return 0;}
// Java Program to Reverse// Diagonal elements of matriximport java.io.*; class GFG{static int N = 4; // Function to swap// diagonals elementsstatic void reverseDiagonal(int array[][]){ int i = 0, j = N; int temp = 0; while (i < j) { // For reversing elements // of major diagonal. temp = array[i][i]; array[i][i] = array[j - 1][j - 1]; array[j - 1][j - 1] = temp; // For reversing elements // of minor diagonal. temp = array[i][j - 1]; array[i][j - 1] = array[j - 1][i]; array[j - 1][i] = temp; i++; j--; } // Print matrix after // reversals. for (i = 0; i < N; ++i) { for (j = 0; j < N; ++j) System.out.print(array[i][j] + " "); System.out.println(); }} // Driver Codepublic static void main (String[] args){ int matrix[][] = {{1, 2, 3, 4}, {5, 6, 7, 8}, {9, 10, 11, 12}, {13, 14, 15, 16}}; reverseDiagonal(matrix);}} // This code is contributed// by anuj_67.
# Python3 Program to Reverse# Diagonal elements of matrix N = 4 # Function to swap diagonals elementsdef reverseDiagonal(array): i = 0 j = N while (i < j) : # For reversing elements of major # diagonal. array[i][i], array[j - 1][j - 1] = array[j-1][j-1], array[i][i] # For reversing elements of minor # diagonal. array[i][j - 1], array[j - 1][i] = array[j-1][i], array[i][j-1] i += 1 j -= 1 # Print matrix after reversals. for i in range(N): for j in range( N): print( array[i][j],end=" ") print() # Driver functionif __name__ == "__main__": matrix = [[ 1, 2, 3, 4], [5, 6, 7, 8], [9, 10, 11, 12], [13, 14, 15, 16 ]] reverseDiagonal(matrix)
// C# Program to Reverse// Diagonal elements of matrixusing System; class GFG{static int N = 4; // Function to swap// diagonals elementsstatic void reverseDiagonal(int [,]array){ int i = 0, j = N; int temp = 0; while (i < j) { // For reversing elements // of major diagonal. temp = array[i, i]; array[i, i] = array[j - 1, j - 1]; array[j - 1, j - 1] = temp; // For reversing elements // of minor diagonal. temp = array[i, j - 1]; array[i, j - 1] = array[j - 1, i]; array[j - 1, i] = temp; i++; j--; } // Print matrix after // reversals. for (i = 0; i < N; ++i) { for (j = 0; j < N; ++j) Console.Write(array[i, j] + " "); Console.WriteLine(); }} // Driver Codepublic static void Main (){ int [,]matrix = {{1, 2, 3, 4}, {5, 6, 7, 8}, {9, 10, 11, 12}, {13, 14, 15, 16}}; reverseDiagonal(matrix);}} // This code is contributed// by anuj_67.
<?php// PHP Program to Reverse// Diagonal elements of matrix // Function to swap// diagonals elementsfunction reverseDiagonal($array){ $N = 4; $i = 0; $j = $N; $temp = 0; while ($i < $j) { // For reversing elements // of major diagonal. $temp = $array[$i][$i]; $array[$i][$i] = $array[$j - 1][$j - 1]; $array[$j - 1][$j - 1] = $temp; // For reversing elements // of minor diagonal. $temp = $array[$i][$j - 1]; $array[$i][$j - 1] = $array[$j - 1][$i]; $array[$j - 1][$i] = $temp; $i++; $j--; } // Print matrix after // reversals. for ($i = 0; $i < $N; ++$i) { for ($j = 0; $j < $N; ++$j) echo $array[$i][$j] . " "; echo "\n"; }} // Driver Code$matrix = array(array(1, 2, 3, 4), array(5, 6, 7, 8), array(9, 10, 11, 12), array(13, 14, 15, 16)); reverseDiagonal($matrix); // This code is contributed// by Akanksha Rai
<script> // JavaScript Program to Reverse// Diagonal elements of matrixlet N = 4; // Function to swap// diagonals elementsfunction reverseDiagonal(array){ let i = 0, j = N; let temp = 0; while (i < j) { // For reversing elements // of major diagonal. temp = array[i][i]; array[i][i] = array[j - 1][j - 1]; array[j - 1][j - 1] = temp; // For reversing elements // of minor diagonal. temp = array[i][j - 1]; array[i][j - 1] = array[j - 1][i]; array[j - 1][i] = temp; i++; j--; } // Print matrix after // reversals. for (i = 0; i < N; ++i) { for (j = 0; j < N; ++j) document.write(array[i][j] + " "); document.write("<br>"); }} // Driver Code let matrix = [[1, 2, 3, 4], [5, 6, 7, 8], [9, 10, 11, 12], [13, 14, 15, 16]]; reverseDiagonal(matrix); // This code is contributed// by sravan kumar Gottumukkala </script>
16 2 3 13
5 11 10 8
9 7 6 12
4 14 15 1
vt_m
ukasp
Akanksha_Rai
sravankumar8128
Matrix
School Programming
Matrix
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Unique paths in a Grid with Obstacles
Find median in row wise sorted matrix
Traverse a given Matrix using Recursion
Zigzag (or diagonal) traversal of Matrix
A Boolean Matrix Question
Python Dictionary
Reverse a string in Java
Arrays in C/C++
Introduction To PYTHON
Interfaces in Java | [
{
"code": null,
"e": 52,
"s": 24,
"text": "\n28 Apr, 2021"
},
{
"code": null,
"e": 150,
"s": 52,
"text": "Given a square matrix of order n*n, we have to reverse the elements of both diagonals.Examples: "
},
{
"code": null,
"e": 671,
"s": 150,
"text": "Input : {1, 2, 3,\n 4, 5, 6,\n 7, 8, 9}\nOutput :{9, 2, 7,\n 4, 5, 6,\n 3, 8, 1}\nExplanation: \n Major Diagonal Elements before: 1 5 9\n After reverse: 9 5 1\n Minor Diagonal Elements before: 3 5 7\n After reverse: 7 5 3 \nInput :{1, 2, 3, 4,\n 5, 6, 7, 8,\n 9, 10, 11, 12,\n 13, 14, 15, 16}\n\nOutput :{16, 2, 3, 13,\n 5, 11, 10, 8,\n 9, 7, 6, 12,\n 4, 14, 15, 1}\n "
},
{
"code": null,
"e": 679,
"s": 675,
"text": "C++"
},
{
"code": null,
"e": 684,
"s": 679,
"text": "Java"
},
{
"code": null,
"e": 693,
"s": 684,
"text": "Python 3"
},
{
"code": null,
"e": 696,
"s": 693,
"text": "C#"
},
{
"code": null,
"e": 700,
"s": 696,
"text": "PHP"
},
{
"code": null,
"e": 711,
"s": 700,
"text": "Javascript"
},
{
"code": "#include <bits/stdc++.h>using namespace std;#define N 4 // Function to swap diagonals elementsvoid reverseDiagonal(int array[][N]){ int i = 0, j = N; while (i < j) { // For reversing elements of major // diagonal. swap(array[i][i], array[j - 1][j - 1]); // For reversing elements of minor // diagonal. swap(array[i][j - 1], array[j - 1][i]); i++; j--; } // Print matrix after reversals. for (int i = 0; i < N; ++i) { for (int j = 0; j < N; ++j) printf(\"%d \", array[i][j]); printf(\"\\n\"); }} // Driver functionint main(){ int matrix[N][N] = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16 }; reverseDiagonal(matrix); return 0;}",
"e": 1541,
"s": 711,
"text": null
},
{
"code": "// Java Program to Reverse// Diagonal elements of matriximport java.io.*; class GFG{static int N = 4; // Function to swap// diagonals elementsstatic void reverseDiagonal(int array[][]){ int i = 0, j = N; int temp = 0; while (i < j) { // For reversing elements // of major diagonal. temp = array[i][i]; array[i][i] = array[j - 1][j - 1]; array[j - 1][j - 1] = temp; // For reversing elements // of minor diagonal. temp = array[i][j - 1]; array[i][j - 1] = array[j - 1][i]; array[j - 1][i] = temp; i++; j--; } // Print matrix after // reversals. for (i = 0; i < N; ++i) { for (j = 0; j < N; ++j) System.out.print(array[i][j] + \" \"); System.out.println(); }} // Driver Codepublic static void main (String[] args){ int matrix[][] = {{1, 2, 3, 4}, {5, 6, 7, 8}, {9, 10, 11, 12}, {13, 14, 15, 16}}; reverseDiagonal(matrix);}} // This code is contributed// by anuj_67.",
"e": 2625,
"s": 1541,
"text": null
},
{
"code": "# Python3 Program to Reverse# Diagonal elements of matrix N = 4 # Function to swap diagonals elementsdef reverseDiagonal(array): i = 0 j = N while (i < j) : # For reversing elements of major # diagonal. array[i][i], array[j - 1][j - 1] = array[j-1][j-1], array[i][i] # For reversing elements of minor # diagonal. array[i][j - 1], array[j - 1][i] = array[j-1][i], array[i][j-1] i += 1 j -= 1 # Print matrix after reversals. for i in range(N): for j in range( N): print( array[i][j],end=\" \") print() # Driver functionif __name__ == \"__main__\": matrix = [[ 1, 2, 3, 4], [5, 6, 7, 8], [9, 10, 11, 12], [13, 14, 15, 16 ]] reverseDiagonal(matrix)",
"e": 3458,
"s": 2625,
"text": null
},
{
"code": "// C# Program to Reverse// Diagonal elements of matrixusing System; class GFG{static int N = 4; // Function to swap// diagonals elementsstatic void reverseDiagonal(int [,]array){ int i = 0, j = N; int temp = 0; while (i < j) { // For reversing elements // of major diagonal. temp = array[i, i]; array[i, i] = array[j - 1, j - 1]; array[j - 1, j - 1] = temp; // For reversing elements // of minor diagonal. temp = array[i, j - 1]; array[i, j - 1] = array[j - 1, i]; array[j - 1, i] = temp; i++; j--; } // Print matrix after // reversals. for (i = 0; i < N; ++i) { for (j = 0; j < N; ++j) Console.Write(array[i, j] + \" \"); Console.WriteLine(); }} // Driver Codepublic static void Main (){ int [,]matrix = {{1, 2, 3, 4}, {5, 6, 7, 8}, {9, 10, 11, 12}, {13, 14, 15, 16}}; reverseDiagonal(matrix);}} // This code is contributed// by anuj_67.",
"e": 4514,
"s": 3458,
"text": null
},
{
"code": "<?php// PHP Program to Reverse// Diagonal elements of matrix // Function to swap// diagonals elementsfunction reverseDiagonal($array){ $N = 4; $i = 0; $j = $N; $temp = 0; while ($i < $j) { // For reversing elements // of major diagonal. $temp = $array[$i][$i]; $array[$i][$i] = $array[$j - 1][$j - 1]; $array[$j - 1][$j - 1] = $temp; // For reversing elements // of minor diagonal. $temp = $array[$i][$j - 1]; $array[$i][$j - 1] = $array[$j - 1][$i]; $array[$j - 1][$i] = $temp; $i++; $j--; } // Print matrix after // reversals. for ($i = 0; $i < $N; ++$i) { for ($j = 0; $j < $N; ++$j) echo $array[$i][$j] . \" \"; echo \"\\n\"; }} // Driver Code$matrix = array(array(1, 2, 3, 4), array(5, 6, 7, 8), array(9, 10, 11, 12), array(13, 14, 15, 16)); reverseDiagonal($matrix); // This code is contributed// by Akanksha Rai",
"e": 5545,
"s": 4514,
"text": null
},
{
"code": "<script> // JavaScript Program to Reverse// Diagonal elements of matrixlet N = 4; // Function to swap// diagonals elementsfunction reverseDiagonal(array){ let i = 0, j = N; let temp = 0; while (i < j) { // For reversing elements // of major diagonal. temp = array[i][i]; array[i][i] = array[j - 1][j - 1]; array[j - 1][j - 1] = temp; // For reversing elements // of minor diagonal. temp = array[i][j - 1]; array[i][j - 1] = array[j - 1][i]; array[j - 1][i] = temp; i++; j--; } // Print matrix after // reversals. for (i = 0; i < N; ++i) { for (j = 0; j < N; ++j) document.write(array[i][j] + \" \"); document.write(\"<br>\"); }} // Driver Code let matrix = [[1, 2, 3, 4], [5, 6, 7, 8], [9, 10, 11, 12], [13, 14, 15, 16]]; reverseDiagonal(matrix); // This code is contributed// by sravan kumar Gottumukkala </script>",
"e": 6575,
"s": 5545,
"text": null
},
{
"code": null,
"e": 6632,
"s": 6575,
"text": "16 2 3 13 \n5 11 10 8 \n9 7 6 12 \n4 14 15 1"
},
{
"code": null,
"e": 6639,
"s": 6634,
"text": "vt_m"
},
{
"code": null,
"e": 6645,
"s": 6639,
"text": "ukasp"
},
{
"code": null,
"e": 6658,
"s": 6645,
"text": "Akanksha_Rai"
},
{
"code": null,
"e": 6674,
"s": 6658,
"text": "sravankumar8128"
},
{
"code": null,
"e": 6681,
"s": 6674,
"text": "Matrix"
},
{
"code": null,
"e": 6700,
"s": 6681,
"text": "School Programming"
},
{
"code": null,
"e": 6707,
"s": 6700,
"text": "Matrix"
},
{
"code": null,
"e": 6805,
"s": 6707,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 6843,
"s": 6805,
"text": "Unique paths in a Grid with Obstacles"
},
{
"code": null,
"e": 6881,
"s": 6843,
"text": "Find median in row wise sorted matrix"
},
{
"code": null,
"e": 6921,
"s": 6881,
"text": "Traverse a given Matrix using Recursion"
},
{
"code": null,
"e": 6962,
"s": 6921,
"text": "Zigzag (or diagonal) traversal of Matrix"
},
{
"code": null,
"e": 6988,
"s": 6962,
"text": "A Boolean Matrix Question"
},
{
"code": null,
"e": 7006,
"s": 6988,
"text": "Python Dictionary"
},
{
"code": null,
"e": 7031,
"s": 7006,
"text": "Reverse a string in Java"
},
{
"code": null,
"e": 7047,
"s": 7031,
"text": "Arrays in C/C++"
},
{
"code": null,
"e": 7070,
"s": 7047,
"text": "Introduction To PYTHON"
}
] |
Python OpenCV – cv2.transpose() method | 08 Jul, 2020
OpenCV is a library of programming functions mainly aimed at real-time computer vision. cv2.transpose() method is used to transpose a 2D array. The function cv::transpose rotate the image 90 degrees Counter clockwise.
Syntax: cv2.cv.transpose( src[, dst] )
Parameters:src: It is the image whose matrix is to be transposed.dst: It is the output image of the same size and depth as src image. It is an optional parameter.
Return Value: It returns an image.
Image used for all the below examples:
Example:
# Python program to explain cv2.transpose() method # importing cv2import cv2 # pathpath = r'C:\Users\user\Desktop\geeks14.png' # Reading an image in default modesrc = cv2.imread(path) # Window name in which image is displayedwindow_name = 'Image' # Using cv2.transpose() methodimage = cv2.transpose(src) # Displaying the imagecv2.imshow(window_name, image)cv2.waitKey(0)
Output:
Python-OpenCV
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here. | [
{
"code": null,
"e": 28,
"s": 0,
"text": "\n08 Jul, 2020"
},
{
"code": null,
"e": 246,
"s": 28,
"text": "OpenCV is a library of programming functions mainly aimed at real-time computer vision. cv2.transpose() method is used to transpose a 2D array. The function cv::transpose rotate the image 90 degrees Counter clockwise."
},
{
"code": null,
"e": 285,
"s": 246,
"text": "Syntax: cv2.cv.transpose( src[, dst] )"
},
{
"code": null,
"e": 448,
"s": 285,
"text": "Parameters:src: It is the image whose matrix is to be transposed.dst: It is the output image of the same size and depth as src image. It is an optional parameter."
},
{
"code": null,
"e": 483,
"s": 448,
"text": "Return Value: It returns an image."
},
{
"code": null,
"e": 522,
"s": 483,
"text": "Image used for all the below examples:"
},
{
"code": null,
"e": 531,
"s": 522,
"text": "Example:"
},
{
"code": "# Python program to explain cv2.transpose() method # importing cv2import cv2 # pathpath = r'C:\\Users\\user\\Desktop\\geeks14.png' # Reading an image in default modesrc = cv2.imread(path) # Window name in which image is displayedwindow_name = 'Image' # Using cv2.transpose() methodimage = cv2.transpose(src) # Displaying the imagecv2.imshow(window_name, image)cv2.waitKey(0)",
"e": 908,
"s": 531,
"text": null
},
{
"code": null,
"e": 916,
"s": 908,
"text": "Output:"
},
{
"code": null,
"e": 930,
"s": 916,
"text": "Python-OpenCV"
},
{
"code": null,
"e": 937,
"s": 930,
"text": "Python"
}
] |
How to open a component in a new tab in ReactJS ? | 19 Oct, 2021
React Router is a standard library for routing in React. It enables the navigation among views of various components in a React Application, allows changing the browser URL, and keeps the UI in sync with the URL. In this tutorial, you will understand how to open a new component in another tab while residing in the main application. For demonstration, we will create two components: the first component and a second component. We will use Switch, React Router, Link to open these two components in new tabs.
Approach: We will create two simple components naming ‘FirstComponent’ and ‘SecondComponent’. In our main component i.e. App.js, we will provide 2 buttons with links to open the first and second components. Then we will apply the logic to open that first and second component in a new tab with different routes.
Step 1: Create a React application using the following command:
npx create-react-app foldername
Step 2: After creating your project folder i.e. folder name, move to it using the following command:
cd foldername
Step 3: Installing packages. React Router can be installed via npm in your React application.To install the React Router use the following command:
npm install react-router-dom
Project Structure: The default file structure will look like this :
project structure
After installing react-router-dom, add its components to your React application. To know more about react-router refer this article: https://www.geeksforgeeks.org/reactjs-router/
Changing the project structure: In your project directory, create 2 files named FirstComponent.js and SecondComponent.js in the src folder. Now your new project structure will look like this:
new project structure
Example: Let’s understand the implementation through example.
FirstComponent.js: This is the component which we will use to display in a new tab . We will try to open this component when a user tries to open the first component on click. This component contains a heading with some CSS styles applied.
FirstComponent.js
import React from "react"; // First simple component with heading tagfunction FirstComponent() { return ( <div> <h1 style={{ // Applying some styles to the heading display: "flex", justifyContent: "center", padding: "15px", border: "13px solid #b4f0b4", color: "rgb(11, 167, 11)", }} > ????Geeks For Geeks First Component in New Tab???? </h1> </div> );}export default FirstComponent;
SecondComponent.js: This is the second component which we will use to display in a new tab . We will try to open this component when the user tries to open the second component on click. This component contains a heading with some CSS styles applied.
SecondComponent.js
import React from "react"; // Second simple component with heading tagfunction SecondComponent() { return ( <div> <h1 style={{ // Applying some styles to the heading display: "flex", justifyContent: "center", padding: "15px", border: "13px solid #6A0DAD", color: "#7F00FF", }} > ????Geeks For Geeks Second Component in New Tab </h1> </div> );}export default SecondComponent;
Route: Route component will help us to establish the link between the component’s UI and the URL. To include routes to the application, add the code give below to your app.js.
App.js: App.js is our default component where some default code is already written. Now import our new components in the App.js file. Include React Router components in the application. We will try to open the first component when the user will click the “Open First Component” button. For this, we are providing the Link to open the path to the first component i.e. “/geeks/first”. Thus the first component will open in a new tab at “http://localhost:3000/geeks/first” location . Similarly, We will try to open the second component when the user will click the “Open Second Component” button. For this, we are providing the Link to open the path to the second component i.e. “/geeks/second”. Thus the SecondComponent will open in a new tab at “http://localhost:3000/geeks/second” location.
App.js
import React from "react";import { BrowserRouter as Router, Route, Link, Switch } from "react-router-dom"; // Importing newly created componentsimport SecondComponent from "./SecondComponent";import FirstComponent from "./FirstComponent"; function App() { return ( // BrowserRouter to wrap all // the other components <Router> {/*switch used to render only the first route that matches the location rather than rendering all matching routes. */} <Switch> <Route exact path="/geeks/second" component={SecondComponent}> </Route> <Route exact path="/geeks/first" component={FirstComponent}> </Route> <ul> <br /> <li> {/* Link component uses the to prop to describe the location where the links should navigate to. */} <Link to="/geeks/first" target="_blank"> Open First Component </Link> </li> <br /> <li> <Link to="/geeks/second" target="_blank"> Open Second Component </Link> </li> </ul> </Switch> </Router> );}export default App;
Step to Run Application: Run the application using the following command from the root directory of the project :
npm start
Output: Your web application will be live on “http://localhost:3000”.Now, click on the links you created.
Explanation: You will notice that both components will open in a new tab with their particular routes. Your FirstComponent will open in a new tab at “http://localhost:3000/geeks/first” location. Your SecondComponent will open in a new tab at “http://localhost:3000/geeks/second” location.
Picked
React-Questions
routing
TrueGeek-2021
ReactJS
TrueGeek
Web Technologies
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here. | [
{
"code": null,
"e": 53,
"s": 25,
"text": "\n19 Oct, 2021"
},
{
"code": null,
"e": 563,
"s": 53,
"text": "React Router is a standard library for routing in React. It enables the navigation among views of various components in a React Application, allows changing the browser URL, and keeps the UI in sync with the URL. In this tutorial, you will understand how to open a new component in another tab while residing in the main application. For demonstration, we will create two components: the first component and a second component. We will use Switch, React Router, Link to open these two components in new tabs. "
},
{
"code": null,
"e": 875,
"s": 563,
"text": "Approach: We will create two simple components naming ‘FirstComponent’ and ‘SecondComponent’. In our main component i.e. App.js, we will provide 2 buttons with links to open the first and second components. Then we will apply the logic to open that first and second component in a new tab with different routes."
},
{
"code": null,
"e": 939,
"s": 875,
"text": "Step 1: Create a React application using the following command:"
},
{
"code": null,
"e": 971,
"s": 939,
"text": "npx create-react-app foldername"
},
{
"code": null,
"e": 1072,
"s": 971,
"text": "Step 2: After creating your project folder i.e. folder name, move to it using the following command:"
},
{
"code": null,
"e": 1086,
"s": 1072,
"text": "cd foldername"
},
{
"code": null,
"e": 1236,
"s": 1088,
"text": "Step 3: Installing packages. React Router can be installed via npm in your React application.To install the React Router use the following command:"
},
{
"code": null,
"e": 1266,
"s": 1236,
"text": "npm install react-router-dom "
},
{
"code": null,
"e": 1334,
"s": 1266,
"text": "Project Structure: The default file structure will look like this :"
},
{
"code": null,
"e": 1352,
"s": 1334,
"text": "project structure"
},
{
"code": null,
"e": 1532,
"s": 1352,
"text": "After installing react-router-dom, add its components to your React application. To know more about react-router refer this article: https://www.geeksforgeeks.org/reactjs-router/ "
},
{
"code": null,
"e": 1724,
"s": 1532,
"text": "Changing the project structure: In your project directory, create 2 files named FirstComponent.js and SecondComponent.js in the src folder. Now your new project structure will look like this:"
},
{
"code": null,
"e": 1746,
"s": 1724,
"text": "new project structure"
},
{
"code": null,
"e": 1809,
"s": 1746,
"text": "Example: Let’s understand the implementation through example. "
},
{
"code": null,
"e": 2049,
"s": 1809,
"text": "FirstComponent.js: This is the component which we will use to display in a new tab . We will try to open this component when a user tries to open the first component on click. This component contains a heading with some CSS styles applied."
},
{
"code": null,
"e": 2067,
"s": 2049,
"text": "FirstComponent.js"
},
{
"code": "import React from \"react\"; // First simple component with heading tagfunction FirstComponent() { return ( <div> <h1 style={{ // Applying some styles to the heading display: \"flex\", justifyContent: \"center\", padding: \"15px\", border: \"13px solid #b4f0b4\", color: \"rgb(11, 167, 11)\", }} > ????Geeks For Geeks First Component in New Tab???? </h1> </div> );}export default FirstComponent;",
"e": 2541,
"s": 2067,
"text": null
},
{
"code": null,
"e": 2792,
"s": 2541,
"text": "SecondComponent.js: This is the second component which we will use to display in a new tab . We will try to open this component when the user tries to open the second component on click. This component contains a heading with some CSS styles applied."
},
{
"code": null,
"e": 2811,
"s": 2792,
"text": "SecondComponent.js"
},
{
"code": "import React from \"react\"; // Second simple component with heading tagfunction SecondComponent() { return ( <div> <h1 style={{ // Applying some styles to the heading display: \"flex\", justifyContent: \"center\", padding: \"15px\", border: \"13px solid #6A0DAD\", color: \"#7F00FF\", }} > ????Geeks For Geeks Second Component in New Tab </h1> </div> );}export default SecondComponent;",
"e": 3276,
"s": 2811,
"text": null
},
{
"code": null,
"e": 3452,
"s": 3276,
"text": "Route: Route component will help us to establish the link between the component’s UI and the URL. To include routes to the application, add the code give below to your app.js."
},
{
"code": null,
"e": 4243,
"s": 3452,
"text": "App.js: App.js is our default component where some default code is already written. Now import our new components in the App.js file. Include React Router components in the application. We will try to open the first component when the user will click the “Open First Component” button. For this, we are providing the Link to open the path to the first component i.e. “/geeks/first”. Thus the first component will open in a new tab at “http://localhost:3000/geeks/first” location . Similarly, We will try to open the second component when the user will click the “Open Second Component” button. For this, we are providing the Link to open the path to the second component i.e. “/geeks/second”. Thus the SecondComponent will open in a new tab at “http://localhost:3000/geeks/second” location."
},
{
"code": null,
"e": 4250,
"s": 4243,
"text": "App.js"
},
{
"code": "import React from \"react\";import { BrowserRouter as Router, Route, Link, Switch } from \"react-router-dom\"; // Importing newly created componentsimport SecondComponent from \"./SecondComponent\";import FirstComponent from \"./FirstComponent\"; function App() { return ( // BrowserRouter to wrap all // the other components <Router> {/*switch used to render only the first route that matches the location rather than rendering all matching routes. */} <Switch> <Route exact path=\"/geeks/second\" component={SecondComponent}> </Route> <Route exact path=\"/geeks/first\" component={FirstComponent}> </Route> <ul> <br /> <li> {/* Link component uses the to prop to describe the location where the links should navigate to. */} <Link to=\"/geeks/first\" target=\"_blank\"> Open First Component </Link> </li> <br /> <li> <Link to=\"/geeks/second\" target=\"_blank\"> Open Second Component </Link> </li> </ul> </Switch> </Router> );}export default App;",
"e": 5466,
"s": 4250,
"text": null
},
{
"code": null,
"e": 5580,
"s": 5466,
"text": "Step to Run Application: Run the application using the following command from the root directory of the project :"
},
{
"code": null,
"e": 5590,
"s": 5580,
"text": "npm start"
},
{
"code": null,
"e": 5697,
"s": 5590,
"text": "Output: Your web application will be live on “http://localhost:3000”.Now, click on the links you created. "
},
{
"code": null,
"e": 5986,
"s": 5697,
"text": "Explanation: You will notice that both components will open in a new tab with their particular routes. Your FirstComponent will open in a new tab at “http://localhost:3000/geeks/first” location. Your SecondComponent will open in a new tab at “http://localhost:3000/geeks/second” location."
},
{
"code": null,
"e": 5993,
"s": 5986,
"text": "Picked"
},
{
"code": null,
"e": 6009,
"s": 5993,
"text": "React-Questions"
},
{
"code": null,
"e": 6017,
"s": 6009,
"text": "routing"
},
{
"code": null,
"e": 6031,
"s": 6017,
"text": "TrueGeek-2021"
},
{
"code": null,
"e": 6039,
"s": 6031,
"text": "ReactJS"
},
{
"code": null,
"e": 6048,
"s": 6039,
"text": "TrueGeek"
},
{
"code": null,
"e": 6065,
"s": 6048,
"text": "Web Technologies"
}
] |
Solidity – Break and Continue Statements | 11 May, 2022
In any programming language, Control statements are used to change the execution of the program. Solidity allows us to handle loops and switch statements. These statements are usually used when we have to terminate the loop without reaching the bottom or we have to skip some part of the block of code and start the new iteration. Solidity provides the following control statements to handle the program execution.
This statement is used when we have to terminate the loop or switch statements or some block of code in which it is present. After the break statement, the control is passed to the statements present after the break. In nested loops, break statement terminates only those loops which has break statement.
Example: In the below example, the contract Types is defined consisting of a dynamic array, an unsigned integer variable, and a function containing the while loop to demonstrate the working of the break statement.
Solidity
// Solidity program to demonstrate// use of Break statementpragma solidity ^0.5.0; // Creating a contractcontract Types { // Declaring a dynamic array uint[] data; // Declaring the state variable uint8 j = 0; // Defining the function to // demonstrate use of Break // statement function loop( ) public returns(uint[] memory){ while(j < 5) { j++; if(j==3){ break; } data.push(j); } return data; }}
Output :
This statement is used when we have to skip the remaining block of code and start the next iteration of the loop immediately. After executing the continue statement, the control is transferred to the loop check condition, and if the condition is true the next iteration starts.
Example: In the below example, contract Types is defined consisting of a dynamic array, an unsigned integer variable, and a function containing the while loop to demonstrate the working of the continue statement.
Solidity
// Solidity program to demonstrate// use of Continue statementpragma solidity ^0.5.0; // Creating a contractcontract Types { // Declaring a dynamic array uint[] data; // Declaring a state variable uint8 j = 0; // Defining a function to // demonstrate the use of // Continue statement function loop( ) public returns(uint[] memory){ while(j < 5) { j++; if(j==3){ continue; } data.push(j); } return data; }}
Output :
Solidity Control-Flow
Blockchain
Solidity
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Solidity - Arrays
How to Become a Blockchain Developer?
Solidity - Mappings
Storage vs Memory in Solidity
How to connect ReactJS with MetaMask ?
Solidity - Arrays
Solidity - Mappings
Storage vs Memory in Solidity
Solidity - Enums and Structs
Solidity - Fall Back Function | [
{
"code": null,
"e": 28,
"s": 0,
"text": "\n11 May, 2022"
},
{
"code": null,
"e": 443,
"s": 28,
"text": "In any programming language, Control statements are used to change the execution of the program. Solidity allows us to handle loops and switch statements. These statements are usually used when we have to terminate the loop without reaching the bottom or we have to skip some part of the block of code and start the new iteration. Solidity provides the following control statements to handle the program execution."
},
{
"code": null,
"e": 748,
"s": 443,
"text": "This statement is used when we have to terminate the loop or switch statements or some block of code in which it is present. After the break statement, the control is passed to the statements present after the break. In nested loops, break statement terminates only those loops which has break statement."
},
{
"code": null,
"e": 962,
"s": 748,
"text": "Example: In the below example, the contract Types is defined consisting of a dynamic array, an unsigned integer variable, and a function containing the while loop to demonstrate the working of the break statement."
},
{
"code": null,
"e": 971,
"s": 962,
"text": "Solidity"
},
{
"code": "// Solidity program to demonstrate// use of Break statementpragma solidity ^0.5.0; // Creating a contractcontract Types { // Declaring a dynamic array uint[] data; // Declaring the state variable uint8 j = 0; // Defining the function to // demonstrate use of Break // statement function loop( ) public returns(uint[] memory){ while(j < 5) { j++; if(j==3){ break; } data.push(j); } return data; }}",
"e": 1471,
"s": 971,
"text": null
},
{
"code": null,
"e": 1481,
"s": 1471,
"text": "Output : "
},
{
"code": null,
"e": 1759,
"s": 1481,
"text": "This statement is used when we have to skip the remaining block of code and start the next iteration of the loop immediately. After executing the continue statement, the control is transferred to the loop check condition, and if the condition is true the next iteration starts."
},
{
"code": null,
"e": 1972,
"s": 1759,
"text": "Example: In the below example, contract Types is defined consisting of a dynamic array, an unsigned integer variable, and a function containing the while loop to demonstrate the working of the continue statement."
},
{
"code": null,
"e": 1981,
"s": 1972,
"text": "Solidity"
},
{
"code": "// Solidity program to demonstrate// use of Continue statementpragma solidity ^0.5.0; // Creating a contractcontract Types { // Declaring a dynamic array uint[] data; // Declaring a state variable uint8 j = 0; // Defining a function to // demonstrate the use of // Continue statement function loop( ) public returns(uint[] memory){ while(j < 5) { j++; if(j==3){ continue; } data.push(j); } return data; }}",
"e": 2488,
"s": 1981,
"text": null
},
{
"code": null,
"e": 2498,
"s": 2488,
"text": "Output : "
},
{
"code": null,
"e": 2520,
"s": 2498,
"text": "Solidity Control-Flow"
},
{
"code": null,
"e": 2531,
"s": 2520,
"text": "Blockchain"
},
{
"code": null,
"e": 2540,
"s": 2531,
"text": "Solidity"
},
{
"code": null,
"e": 2638,
"s": 2540,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 2656,
"s": 2638,
"text": "Solidity - Arrays"
},
{
"code": null,
"e": 2694,
"s": 2656,
"text": "How to Become a Blockchain Developer?"
},
{
"code": null,
"e": 2714,
"s": 2694,
"text": "Solidity - Mappings"
},
{
"code": null,
"e": 2744,
"s": 2714,
"text": "Storage vs Memory in Solidity"
},
{
"code": null,
"e": 2783,
"s": 2744,
"text": "How to connect ReactJS with MetaMask ?"
},
{
"code": null,
"e": 2801,
"s": 2783,
"text": "Solidity - Arrays"
},
{
"code": null,
"e": 2821,
"s": 2801,
"text": "Solidity - Mappings"
},
{
"code": null,
"e": 2851,
"s": 2821,
"text": "Storage vs Memory in Solidity"
},
{
"code": null,
"e": 2880,
"s": 2851,
"text": "Solidity - Enums and Structs"
}
] |
How to use labels in Java code? | Java provides two types of branching/control statements namely, break and continue.
This statement terminates the loop or switch statement and transfers execution to the statement immediately following the loop or switch.
Following is the example of the break statement. Here we are trying to print elements up to 10 and, using break statement we are terminating the loop when the value in the loop reaches 8.
Live Demo
public class BreakExample {
public static void main(String args[]){
for(int i=0; i<10; i++){
if (i==8){
break;
}
System.out.println("......."+i);
}
}
}
.......0
.......1
.......2
.......3
.......4
.......5
.......6
.......7
This statement causes the loop to skip the remainder of its body and immediately retest its condition prior to reiterating.
Following is the example of the continue statement. Here we are trying to print elements up to 10 and, using break continue we are skipping the loop when the value in the loop reaches 8.
Live Demo
public class ContinueExample {
public static void main(String args[]){
for(int i=0; i<10; i++){
if (i==8){
continue;
}
System.out.println("......."+i);
}
}
}
.......0
.......1
.......2
.......3
.......4
.......5
.......6
.......7
.......9
Java provides two types of branching statements namely, labelled and unlabelled.
We can also use the above-mentioned branching statements with labels.
You can assign a label to the break/continue statement and can use that label with the break/continue statement as −
Task:
for(int i=0; i<10; i++){
if (i==8){
continue Task;
(or)
break Task;
}
}
The labeled break statement terminates the outer most loop whereas the normal break statement terminates the innermost loop.
Live Demo
public class LabeledBreakExample {
public static void main(String args[]){
Task:
for(int i=0; i<10; i++){
if (i==8){
break Task;
}
System.out.println("......."+i );
}
}
}
.......0
.......1
.......2
.......3
.......4
.......5
.......6
.......7
.......9
The labelled continue statement skips the current iteration of the outer most loop whereas the normal continue skips the current iteration of the innermost loop.
Live Demo
public class LabeledContinueExample {
public static void main(String args[]){
Task:
for(int i=0; i<10; i++){
if (i==8){
continue Task;
}
System.out.println("......."+i );
}
}
}
.......0
.......1
.......2
.......3
.......4
.......5
.......6
.......7
.......9 | [
{
"code": null,
"e": 1271,
"s": 1187,
"text": "Java provides two types of branching/control statements namely, break and continue."
},
{
"code": null,
"e": 1409,
"s": 1271,
"text": "This statement terminates the loop or switch statement and transfers execution to the statement immediately following the loop or switch."
},
{
"code": null,
"e": 1597,
"s": 1409,
"text": "Following is the example of the break statement. Here we are trying to print elements up to 10 and, using break statement we are terminating the loop when the value in the loop reaches 8."
},
{
"code": null,
"e": 1607,
"s": 1597,
"text": "Live Demo"
},
{
"code": null,
"e": 1816,
"s": 1607,
"text": "public class BreakExample {\n public static void main(String args[]){\n for(int i=0; i<10; i++){\n if (i==8){\n break;\n }\n System.out.println(\".......\"+i);\n }\n }\n}"
},
{
"code": null,
"e": 1888,
"s": 1816,
"text": ".......0\n.......1\n.......2\n.......3\n.......4\n.......5\n.......6\n.......7"
},
{
"code": null,
"e": 2013,
"s": 1888,
"text": " This statement causes the loop to skip the remainder of its body and immediately retest its condition prior to reiterating."
},
{
"code": null,
"e": 2200,
"s": 2013,
"text": "Following is the example of the continue statement. Here we are trying to print elements up to 10 and, using break continue we are skipping the loop when the value in the loop reaches 8."
},
{
"code": null,
"e": 2210,
"s": 2200,
"text": "Live Demo"
},
{
"code": null,
"e": 2425,
"s": 2210,
"text": "public class ContinueExample {\n public static void main(String args[]){\n for(int i=0; i<10; i++){\n if (i==8){\n continue;\n }\n System.out.println(\".......\"+i);\n }\n }\n}"
},
{
"code": null,
"e": 2506,
"s": 2425,
"text": ".......0\n.......1\n.......2\n.......3\n.......4\n.......5\n.......6\n.......7\n.......9"
},
{
"code": null,
"e": 2587,
"s": 2506,
"text": "Java provides two types of branching statements namely, labelled and unlabelled."
},
{
"code": null,
"e": 2657,
"s": 2587,
"text": "We can also use the above-mentioned branching statements with labels."
},
{
"code": null,
"e": 2774,
"s": 2657,
"text": "You can assign a label to the break/continue statement and can use that label with the break/continue statement as −"
},
{
"code": null,
"e": 2876,
"s": 2774,
"text": "Task:\nfor(int i=0; i<10; i++){\n if (i==8){\n continue Task;\n (or)\n break Task;\n }\n}"
},
{
"code": null,
"e": 3001,
"s": 2876,
"text": "The labeled break statement terminates the outer most loop whereas the normal break statement terminates the innermost loop."
},
{
"code": null,
"e": 3011,
"s": 3001,
"text": "Live Demo"
},
{
"code": null,
"e": 3247,
"s": 3011,
"text": "public class LabeledBreakExample {\n public static void main(String args[]){\n Task:\n for(int i=0; i<10; i++){\n if (i==8){\n break Task;\n }\n System.out.println(\".......\"+i );\n }\n }\n}"
},
{
"code": null,
"e": 3328,
"s": 3247,
"text": ".......0\n.......1\n.......2\n.......3\n.......4\n.......5\n.......6\n.......7\n.......9"
},
{
"code": null,
"e": 3490,
"s": 3328,
"text": "The labelled continue statement skips the current iteration of the outer most loop whereas the normal continue skips the current iteration of the innermost loop."
},
{
"code": null,
"e": 3500,
"s": 3490,
"text": "Live Demo"
},
{
"code": null,
"e": 3749,
"s": 3500,
"text": "public class LabeledContinueExample {\n public static void main(String args[]){\n Task:\n for(int i=0; i<10; i++){\n if (i==8){\n continue Task;\n }\n System.out.println(\".......\"+i );\n } \n } \n}"
},
{
"code": null,
"e": 3830,
"s": 3749,
"text": ".......0\n.......1\n.......2\n.......3\n.......4\n.......5\n.......6\n.......7\n.......9"
}
] |
Variables and autograd in Pytorch | 29 Jun, 2021
PyTorch is a python library developed by Facebook to run and train the machine and deep learning algorithms. In a neural network, we have to perform backpropagation which involves optimizing the parameter to minimize the error in its prediction.
For this PyTorch offers torch.autograd that does automatic differentiation by collecting all gradients. Autograd does this by keeping a record of data(tensors) & all executed operations in a directed acyclic graph consisting of function objects. In this DAG, leaves are the input tensors, roots are the output tensors. By tracing this graph from roots to leaves we can automatically compute the gradients using the chain rule.
A variable is an automatic differentiation tool given a forward formulation. It wraps a variable. Variable supports nearly all the APIs defined by a Tensor. While defining a variable we pass the parameter requires_grad which indicates if the variable is trainable or not. By default, it is set to false. An example is depicted below to understand it more clearly.
Example 1:
Python3
# importing librariesimport torchfrom torch.autograd import Variable # packing the tensors with Variablea = Variable(torch.tensor([5., 4.]), requires_grad=True)b = Variable(torch.tensor([6., 8.])) # polynomial function with a,b as variabley = ((a**2)+(5*b))z = y.mean()print('Z value is:', z)
Output:
Z value is: tensor(55.5000, grad_fn=<MeanBackward0>)
Thus, in the above forward pass, we compute a resulting tensor maintaining the gradient function in DAG. After that when backward is called, it follows backward with the links created in the graph to backpropagate the gradient and accumulates them in the respective variable’s grad attribute.
Example 2:
Python3
# importing librariesimport torchfrom torch.autograd import Variable # packing the tensors with Variablea = Variable(torch.tensor([5., 4.]), requires_grad=True)b = Variable(torch.tensor([6., 8.])) # polynomial function with a,b as variabley = ((a**2)+(5*b))z = y.mean() # dy/da=2*a=10,8# dy/db=5 # computing gradientz.backward() # printing outprint('Gradient of a', a.grad)print('Gradient of b', b.grad)
Output:
Gradient of a tensor([5., 4.])
Gradient of b None
Above you can notice that b’s gradient is not updated as in this variable requires_grad is not set to true. This is where Autograd comes into the picture.
Autograd is a PyTorch package for the differentiation for all operations on Tensors. It performs the backpropagation starting from a variable. In deep learning, this variable often holds the value of the cost function. Backward executes the backward pass and computes all the backpropagation gradients automatically.
First, we create some random features, e.g., weight and bias vectors. Perform a linear regression by multiplying x, W matrices. Then calculate the squared error and call the backward function to backpropagate, updating the gradient value of each variable. At last, we optimize the weight matrix and print it out.
Example:
Python3
# importing librariesimport torchfrom torch.autograd import Variable # creating random tensors for weights and wrap them in variablesx = Variable(torch.randn(1, 10), requires_grad=False)W = Variable(torch.randn(10, 1), requires_grad=True) # weight matrixb = Variable(torch.randn(1), requires_grad=True) # bias vectory = Variable(torch.tensor([[0.822]])) # performing matrix multiplication to compute outputy_pred = torch.matmul(x, W)+b # calculating lossloss = (y_pred-y).pow(2)print(loss) # computing gradientloss.backward() print(W.grad)print(b.grad) lr = 0.001 # updating the weight matrix after backpropagationwith torch.no_grad(): W = W-(lr*W.grad.data)print(W)
Output:
tensor([[1.3523]], grad_fn=<PowBackward0>)
tensor([[-0.4488],
[ 1.8151],
[ 3.5312],
[ 1.4467],
[ 2.8628],
[-0.9358],
[-2.7980],
[ 0.2670],
[-0.0399],
[ 0.1995]])
tensor([2.3258])
tensor([[ 1.1908],
[ 0.0301],
[-0.2003],
[ 0.6922],
[ 2.1972],
[ 0.0633],
[ 0.7101],
[-0.5169],
[ 0.7412],
[ 0.7068]])
Picked
Python-PyTorch
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to Install PIP on Windows ?
Python Classes and Objects
Python OOPs Concepts
Introduction To PYTHON
How to drop one or multiple columns in Pandas Dataframe
Python | os.path.join() method
How To Convert Python Dictionary To JSON?
Check if element exists in list in Python
Python | datetime.timedelta() function
Python | Get unique values from a list | [
{
"code": null,
"e": 28,
"s": 0,
"text": "\n29 Jun, 2021"
},
{
"code": null,
"e": 274,
"s": 28,
"text": "PyTorch is a python library developed by Facebook to run and train the machine and deep learning algorithms. In a neural network, we have to perform backpropagation which involves optimizing the parameter to minimize the error in its prediction."
},
{
"code": null,
"e": 701,
"s": 274,
"text": "For this PyTorch offers torch.autograd that does automatic differentiation by collecting all gradients. Autograd does this by keeping a record of data(tensors) & all executed operations in a directed acyclic graph consisting of function objects. In this DAG, leaves are the input tensors, roots are the output tensors. By tracing this graph from roots to leaves we can automatically compute the gradients using the chain rule."
},
{
"code": null,
"e": 1065,
"s": 701,
"text": "A variable is an automatic differentiation tool given a forward formulation. It wraps a variable. Variable supports nearly all the APIs defined by a Tensor. While defining a variable we pass the parameter requires_grad which indicates if the variable is trainable or not. By default, it is set to false. An example is depicted below to understand it more clearly."
},
{
"code": null,
"e": 1077,
"s": 1065,
"text": "Example 1: "
},
{
"code": null,
"e": 1085,
"s": 1077,
"text": "Python3"
},
{
"code": "# importing librariesimport torchfrom torch.autograd import Variable # packing the tensors with Variablea = Variable(torch.tensor([5., 4.]), requires_grad=True)b = Variable(torch.tensor([6., 8.])) # polynomial function with a,b as variabley = ((a**2)+(5*b))z = y.mean()print('Z value is:', z)",
"e": 1380,
"s": 1085,
"text": null
},
{
"code": null,
"e": 1388,
"s": 1380,
"text": "Output:"
},
{
"code": null,
"e": 1441,
"s": 1388,
"text": "Z value is: tensor(55.5000, grad_fn=<MeanBackward0>)"
},
{
"code": null,
"e": 1734,
"s": 1441,
"text": "Thus, in the above forward pass, we compute a resulting tensor maintaining the gradient function in DAG. After that when backward is called, it follows backward with the links created in the graph to backpropagate the gradient and accumulates them in the respective variable’s grad attribute."
},
{
"code": null,
"e": 1745,
"s": 1734,
"text": "Example 2:"
},
{
"code": null,
"e": 1753,
"s": 1745,
"text": "Python3"
},
{
"code": "# importing librariesimport torchfrom torch.autograd import Variable # packing the tensors with Variablea = Variable(torch.tensor([5., 4.]), requires_grad=True)b = Variable(torch.tensor([6., 8.])) # polynomial function with a,b as variabley = ((a**2)+(5*b))z = y.mean() # dy/da=2*a=10,8# dy/db=5 # computing gradientz.backward() # printing outprint('Gradient of a', a.grad)print('Gradient of b', b.grad)",
"e": 2162,
"s": 1753,
"text": null
},
{
"code": null,
"e": 2170,
"s": 2162,
"text": "Output:"
},
{
"code": null,
"e": 2201,
"s": 2170,
"text": "Gradient of a tensor([5., 4.])"
},
{
"code": null,
"e": 2220,
"s": 2201,
"text": "Gradient of b None"
},
{
"code": null,
"e": 2375,
"s": 2220,
"text": "Above you can notice that b’s gradient is not updated as in this variable requires_grad is not set to true. This is where Autograd comes into the picture."
},
{
"code": null,
"e": 2692,
"s": 2375,
"text": "Autograd is a PyTorch package for the differentiation for all operations on Tensors. It performs the backpropagation starting from a variable. In deep learning, this variable often holds the value of the cost function. Backward executes the backward pass and computes all the backpropagation gradients automatically."
},
{
"code": null,
"e": 3005,
"s": 2692,
"text": "First, we create some random features, e.g., weight and bias vectors. Perform a linear regression by multiplying x, W matrices. Then calculate the squared error and call the backward function to backpropagate, updating the gradient value of each variable. At last, we optimize the weight matrix and print it out."
},
{
"code": null,
"e": 3014,
"s": 3005,
"text": "Example:"
},
{
"code": null,
"e": 3022,
"s": 3014,
"text": "Python3"
},
{
"code": "# importing librariesimport torchfrom torch.autograd import Variable # creating random tensors for weights and wrap them in variablesx = Variable(torch.randn(1, 10), requires_grad=False)W = Variable(torch.randn(10, 1), requires_grad=True) # weight matrixb = Variable(torch.randn(1), requires_grad=True) # bias vectory = Variable(torch.tensor([[0.822]])) # performing matrix multiplication to compute outputy_pred = torch.matmul(x, W)+b # calculating lossloss = (y_pred-y).pow(2)print(loss) # computing gradientloss.backward() print(W.grad)print(b.grad) lr = 0.001 # updating the weight matrix after backpropagationwith torch.no_grad(): W = W-(lr*W.grad.data)print(W)",
"e": 3701,
"s": 3022,
"text": null
},
{
"code": null,
"e": 3709,
"s": 3701,
"text": "Output:"
},
{
"code": null,
"e": 4133,
"s": 3709,
"text": "tensor([[1.3523]], grad_fn=<PowBackward0>)\ntensor([[-0.4488],\n [ 1.8151],\n [ 3.5312],\n [ 1.4467],\n [ 2.8628],\n [-0.9358],\n [-2.7980],\n [ 0.2670],\n [-0.0399],\n [ 0.1995]])\ntensor([2.3258])\ntensor([[ 1.1908],\n [ 0.0301],\n [-0.2003],\n [ 0.6922],\n [ 2.1972],\n [ 0.0633],\n [ 0.7101],\n [-0.5169],\n [ 0.7412],\n [ 0.7068]])"
},
{
"code": null,
"e": 4140,
"s": 4133,
"text": "Picked"
},
{
"code": null,
"e": 4155,
"s": 4140,
"text": "Python-PyTorch"
},
{
"code": null,
"e": 4162,
"s": 4155,
"text": "Python"
},
{
"code": null,
"e": 4260,
"s": 4162,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 4292,
"s": 4260,
"text": "How to Install PIP on Windows ?"
},
{
"code": null,
"e": 4319,
"s": 4292,
"text": "Python Classes and Objects"
},
{
"code": null,
"e": 4340,
"s": 4319,
"text": "Python OOPs Concepts"
},
{
"code": null,
"e": 4363,
"s": 4340,
"text": "Introduction To PYTHON"
},
{
"code": null,
"e": 4419,
"s": 4363,
"text": "How to drop one or multiple columns in Pandas Dataframe"
},
{
"code": null,
"e": 4450,
"s": 4419,
"text": "Python | os.path.join() method"
},
{
"code": null,
"e": 4492,
"s": 4450,
"text": "How To Convert Python Dictionary To JSON?"
},
{
"code": null,
"e": 4534,
"s": 4492,
"text": "Check if element exists in list in Python"
},
{
"code": null,
"e": 4573,
"s": 4534,
"text": "Python | datetime.timedelta() function"
}
] |
Single Responsibility Principle in Java with Examples | 06 Jun, 2021
SOLID is an acronym used to refer to a group of five important principles followed in software development. This principle is an acronym of the five principles which are given below...
Single Responsibility Principle (SRP)Open/Closed PrincipleLiskov’s Substitution Principle (LSP)Interface Segregation Principle (ISP)Dependency Inversion Principle (DIP)
Single Responsibility Principle (SRP)
Open/Closed Principle
Liskov’s Substitution Principle (LSP)
Interface Segregation Principle (ISP)
Dependency Inversion Principle (DIP)
In this post, we will learn more about the Single Responsibility Principle. As the name indicates, it states that all classes and modules should have only 1 well-defined responsibility. As per Robert C Martin,
A class should have one, and only one reason to change.
This means when we design our classes, we need to ensure that our class is responsible only for 1 task or functionality and when there is a change in that task/functionality, only then, that class should change.
In the world of software, change is the only constant factor. When requirements change and when our classes do not adhere to this principle, we would be making too many changes to our classes to make our classes adaptable to the new business requirements. This could involve lots of side effects, retesting, and introducing new bugs. Also, our dependent classes need to change, thereby recompiling the classes and changing test cases. Thus, the whole application will need to be retested to ensure that new functionality did not break the existing working code.
Generally in long-running software applications, as and when new requirements come up, developers are tempted to add new methods and functionality to the existing code which makes the classes bloated and hard to test and understand. It is always a good practice to look into the existing classes and see if the new requirements fit into the existing class or should there be a new class designed for the same.
Benefits of Single Responsibility Principle
When an application has multiple classes, each of them following this principle, then the applicable becomes more maintainable, easier to understand.
The code quality of the application is better, thereby having fewer defects.
Onboarding new members are easy, and they can start contributing much faster.
Testing and writing test cases is much simpler
Examples
In the java world, we have a lot of frameworks that follow this principle. JSR 380 validation API is a good example that follows this principle. It has annotations like @NotNull, @Max, @MIn, @Size which are applied to the bean properties to ensure that the bean attributes meet the specific criteria. Thus, the validation API has just 1 responsibility of applying validation rules on bean properties and notifying with error messages when the bean properties do not match the specific criteria
Another example is Spring Data JPA which takes care of all the CRUD operations. It has one responsibility of defining a standardized way to store, retrieve entity data from persistent storage. It eases development effort by removing the tedious task of writing boilerplate JDBC code to store entities in a database.
Spring Framework in general, is also a great example of Single Responsibility in practice. Spring framework is quite vast, with many modules – each module catering to one specific responsibility/functionality. We only add relevant modules in our dependency pom based on our needs.
Let’s look at one more example to understand this concept better. Consider a food delivery application that takes food orders, calculates the bill, and delivers it to customers. We can have 1 separate class for each of the tasks to be performed, and then the main class can just invoke those classes to get these actions done one after the other.
Java
import java.io.*;import java.util.*; class GFG { public static void main(String[] args) { Customer customer1 = new Customer(); customer1.setName("John"); customer1.setAddress("Pune"); Order order1 = new Order(); order1.setItemName("Pizza"); order1.setQuantity(2); order1.setCustomer(customer1); order1.prepareOrder(); BillCalculation billCalculation = new BillCalculation(order1); billCalculation.calculateBill(); DeliveryApp deliveryApp = new DeliveryApp(order1); deliveryApp.delivery(); }} class Customer { private String name; private String address; public String getName() { return name; } public void setName(String name) { this.name = name; } public String getAddress() { return address; } public void setAddress(String address) { this.address = address; }} class Order { private Customer customer; private String orderId; private String itemName; private int quantity; private int totalBillAmt; public Customer getCustomer() { return customer; } public void setCustomer(Customer customer) { this.customer = customer; } public String getOrderId() { return orderId; } public void setOrderId(String orderId) { Random random = new Random(); this.orderId = orderId + "-" + random.nextInt(500); } public String getItemName() { return itemName; } public void setItemName(String itemName) { this.itemName = itemName; setOrderId(itemName); } public int getQuantity() { return quantity; } public void setQuantity(int quantity) { this.quantity = quantity; } public int getTotalBillAmt() { return totalBillAmt; } public void setTotalBillAmt(int totalBillAmt) { this.totalBillAmt = totalBillAmt; } public void prepareOrder() { System.out.println("Preparing order for customer -" + this.getCustomer().getName() + " who has ordered " + this.getItemName()); }} class BillCalculation { private Order order; public BillCalculation(Order order) { this.order = order; } public void calculateBill() { /* In the real world, we would want a kind of lookup functionality implemented here where we look for the price of each item included in the order, add them up and add taxes, delivery charges, etc on top to reach the total price. We will simulate this behaviour here, by generating a random number for total price. */ Random rand = new Random(); int totalAmt = rand.nextInt(200) * this.order.getQuantity(); this.order.setTotalBillAmt(totalAmt); System.out.println("Order with order id " + this.order.getOrderId() + " has a total bill amount of " + this.order.getTotalBillAmt()); }} class DeliveryApp { private Order order; public DeliveryApp(Order order) { this.order = order; } public void delivery() { // Here, we would want to interface with another // system which actually assigns the task of // delivery to different persons // based on location, etc. System.out.println("Delivering the order"); System.out.println( "Order with order id as " + this.order.getOrderId() + " being delivered to " + this.order.getCustomer().getName()); System.out.println( "Order is to be delivered to: " + this.order.getCustomer().getAddress()); }}
Preparing order for customer -John who has ordered Pizza
Order with order id Pizza-57 has a total bill amount of 46
Delivering the order
Order with order id as Pizza-57 being delivered to John
Order is to be delivered to: Pune
We have a Customer class that has customer attributes like name, address. Order class has all order information like item name, quantity.
The BillCalculation class calculates the total bill sets the bill amount in the order object. The DeliveryApp has 1 task of delivering the order to the customer. In the real world, these classes would be more complex and might require their functionality to be further broken down into multiple classes.
For example, the bill calculation logic might require some kind of lookup functionality to be implemented where we look for the price of each item included in the order against some kind of database, add them up, add taxes, delivery charges, etc and finally reach the total price. Depending on how complex the code starts to become, we might want to move the taxes, database queries etc, to other separate classes. Similarly, the delivery class might want to interface with another task management system that actually assigns the task of delivery to different delivery agents based on location, shift timings, whether that delivery person has actually shown up to work, etc. These individual steps could move to separate classes when they need specialized handling.
If the functionality of bill calculation, as well as order delivery, was added in the same class, then that class gets modified whenever the bill calculation logic or the delivery agent logic needs to change; which goes against the Single Responsibility Principle. As per the example, we have a separate class for handling each of these functions. Any single business requirement change should ideally have an impact on only one class, thus catering to the Single Responsibility Principle.
Picked
Java
Java
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here. | [
{
"code": null,
"e": 52,
"s": 24,
"text": "\n06 Jun, 2021"
},
{
"code": null,
"e": 237,
"s": 52,
"text": "SOLID is an acronym used to refer to a group of five important principles followed in software development. This principle is an acronym of the five principles which are given below..."
},
{
"code": null,
"e": 406,
"s": 237,
"text": "Single Responsibility Principle (SRP)Open/Closed PrincipleLiskov’s Substitution Principle (LSP)Interface Segregation Principle (ISP)Dependency Inversion Principle (DIP)"
},
{
"code": null,
"e": 444,
"s": 406,
"text": "Single Responsibility Principle (SRP)"
},
{
"code": null,
"e": 466,
"s": 444,
"text": "Open/Closed Principle"
},
{
"code": null,
"e": 504,
"s": 466,
"text": "Liskov’s Substitution Principle (LSP)"
},
{
"code": null,
"e": 542,
"s": 504,
"text": "Interface Segregation Principle (ISP)"
},
{
"code": null,
"e": 579,
"s": 542,
"text": "Dependency Inversion Principle (DIP)"
},
{
"code": null,
"e": 791,
"s": 579,
"text": "In this post, we will learn more about the Single Responsibility Principle. As the name indicates, it states that all classes and modules should have only 1 well-defined responsibility. As per Robert C Martin, "
},
{
"code": null,
"e": 847,
"s": 791,
"text": "A class should have one, and only one reason to change."
},
{
"code": null,
"e": 1059,
"s": 847,
"text": "This means when we design our classes, we need to ensure that our class is responsible only for 1 task or functionality and when there is a change in that task/functionality, only then, that class should change."
},
{
"code": null,
"e": 1621,
"s": 1059,
"text": "In the world of software, change is the only constant factor. When requirements change and when our classes do not adhere to this principle, we would be making too many changes to our classes to make our classes adaptable to the new business requirements. This could involve lots of side effects, retesting, and introducing new bugs. Also, our dependent classes need to change, thereby recompiling the classes and changing test cases. Thus, the whole application will need to be retested to ensure that new functionality did not break the existing working code."
},
{
"code": null,
"e": 2032,
"s": 1621,
"text": "Generally in long-running software applications, as and when new requirements come up, developers are tempted to add new methods and functionality to the existing code which makes the classes bloated and hard to test and understand. It is always a good practice to look into the existing classes and see if the new requirements fit into the existing class or should there be a new class designed for the same."
},
{
"code": null,
"e": 2076,
"s": 2032,
"text": "Benefits of Single Responsibility Principle"
},
{
"code": null,
"e": 2226,
"s": 2076,
"text": "When an application has multiple classes, each of them following this principle, then the applicable becomes more maintainable, easier to understand."
},
{
"code": null,
"e": 2303,
"s": 2226,
"text": "The code quality of the application is better, thereby having fewer defects."
},
{
"code": null,
"e": 2381,
"s": 2303,
"text": "Onboarding new members are easy, and they can start contributing much faster."
},
{
"code": null,
"e": 2428,
"s": 2381,
"text": "Testing and writing test cases is much simpler"
},
{
"code": null,
"e": 2437,
"s": 2428,
"text": "Examples"
},
{
"code": null,
"e": 2931,
"s": 2437,
"text": "In the java world, we have a lot of frameworks that follow this principle. JSR 380 validation API is a good example that follows this principle. It has annotations like @NotNull, @Max, @MIn, @Size which are applied to the bean properties to ensure that the bean attributes meet the specific criteria. Thus, the validation API has just 1 responsibility of applying validation rules on bean properties and notifying with error messages when the bean properties do not match the specific criteria"
},
{
"code": null,
"e": 3248,
"s": 2931,
"text": "Another example is Spring Data JPA which takes care of all the CRUD operations. It has one responsibility of defining a standardized way to store, retrieve entity data from persistent storage. It eases development effort by removing the tedious task of writing boilerplate JDBC code to store entities in a database."
},
{
"code": null,
"e": 3530,
"s": 3248,
"text": "Spring Framework in general, is also a great example of Single Responsibility in practice. Spring framework is quite vast, with many modules – each module catering to one specific responsibility/functionality. We only add relevant modules in our dependency pom based on our needs."
},
{
"code": null,
"e": 3877,
"s": 3530,
"text": "Let’s look at one more example to understand this concept better. Consider a food delivery application that takes food orders, calculates the bill, and delivers it to customers. We can have 1 separate class for each of the tasks to be performed, and then the main class can just invoke those classes to get these actions done one after the other."
},
{
"code": null,
"e": 3882,
"s": 3877,
"text": "Java"
},
{
"code": "import java.io.*;import java.util.*; class GFG { public static void main(String[] args) { Customer customer1 = new Customer(); customer1.setName(\"John\"); customer1.setAddress(\"Pune\"); Order order1 = new Order(); order1.setItemName(\"Pizza\"); order1.setQuantity(2); order1.setCustomer(customer1); order1.prepareOrder(); BillCalculation billCalculation = new BillCalculation(order1); billCalculation.calculateBill(); DeliveryApp deliveryApp = new DeliveryApp(order1); deliveryApp.delivery(); }} class Customer { private String name; private String address; public String getName() { return name; } public void setName(String name) { this.name = name; } public String getAddress() { return address; } public void setAddress(String address) { this.address = address; }} class Order { private Customer customer; private String orderId; private String itemName; private int quantity; private int totalBillAmt; public Customer getCustomer() { return customer; } public void setCustomer(Customer customer) { this.customer = customer; } public String getOrderId() { return orderId; } public void setOrderId(String orderId) { Random random = new Random(); this.orderId = orderId + \"-\" + random.nextInt(500); } public String getItemName() { return itemName; } public void setItemName(String itemName) { this.itemName = itemName; setOrderId(itemName); } public int getQuantity() { return quantity; } public void setQuantity(int quantity) { this.quantity = quantity; } public int getTotalBillAmt() { return totalBillAmt; } public void setTotalBillAmt(int totalBillAmt) { this.totalBillAmt = totalBillAmt; } public void prepareOrder() { System.out.println(\"Preparing order for customer -\" + this.getCustomer().getName() + \" who has ordered \" + this.getItemName()); }} class BillCalculation { private Order order; public BillCalculation(Order order) { this.order = order; } public void calculateBill() { /* In the real world, we would want a kind of lookup functionality implemented here where we look for the price of each item included in the order, add them up and add taxes, delivery charges, etc on top to reach the total price. We will simulate this behaviour here, by generating a random number for total price. */ Random rand = new Random(); int totalAmt = rand.nextInt(200) * this.order.getQuantity(); this.order.setTotalBillAmt(totalAmt); System.out.println(\"Order with order id \" + this.order.getOrderId() + \" has a total bill amount of \" + this.order.getTotalBillAmt()); }} class DeliveryApp { private Order order; public DeliveryApp(Order order) { this.order = order; } public void delivery() { // Here, we would want to interface with another // system which actually assigns the task of // delivery to different persons // based on location, etc. System.out.println(\"Delivering the order\"); System.out.println( \"Order with order id as \" + this.order.getOrderId() + \" being delivered to \" + this.order.getCustomer().getName()); System.out.println( \"Order is to be delivered to: \" + this.order.getCustomer().getAddress()); }}",
"e": 7631,
"s": 3882,
"text": null
},
{
"code": null,
"e": 7859,
"s": 7631,
"text": "Preparing order for customer -John who has ordered Pizza\nOrder with order id Pizza-57 has a total bill amount of 46\nDelivering the order\nOrder with order id as Pizza-57 being delivered to John\nOrder is to be delivered to: Pune"
},
{
"code": null,
"e": 7997,
"s": 7859,
"text": "We have a Customer class that has customer attributes like name, address. Order class has all order information like item name, quantity."
},
{
"code": null,
"e": 8302,
"s": 7997,
"text": "The BillCalculation class calculates the total bill sets the bill amount in the order object. The DeliveryApp has 1 task of delivering the order to the customer. In the real world, these classes would be more complex and might require their functionality to be further broken down into multiple classes. "
},
{
"code": null,
"e": 9070,
"s": 8302,
"text": "For example, the bill calculation logic might require some kind of lookup functionality to be implemented where we look for the price of each item included in the order against some kind of database, add them up, add taxes, delivery charges, etc and finally reach the total price. Depending on how complex the code starts to become, we might want to move the taxes, database queries etc, to other separate classes. Similarly, the delivery class might want to interface with another task management system that actually assigns the task of delivery to different delivery agents based on location, shift timings, whether that delivery person has actually shown up to work, etc. These individual steps could move to separate classes when they need specialized handling. "
},
{
"code": null,
"e": 9561,
"s": 9070,
"text": "If the functionality of bill calculation, as well as order delivery, was added in the same class, then that class gets modified whenever the bill calculation logic or the delivery agent logic needs to change; which goes against the Single Responsibility Principle. As per the example, we have a separate class for handling each of these functions. Any single business requirement change should ideally have an impact on only one class, thus catering to the Single Responsibility Principle."
},
{
"code": null,
"e": 9568,
"s": 9561,
"text": "Picked"
},
{
"code": null,
"e": 9573,
"s": 9568,
"text": "Java"
},
{
"code": null,
"e": 9578,
"s": 9573,
"text": "Java"
}
] |
Program to print circle pattern | 09 Apr, 2021
Given a positive integer n i.e, radius of the circle, print a circle using stars. Examples :
Input : n = 3
Output :
***
* *
* *
* *
* *
* *
***
Input : n = 6
Output :
*****
** **
** **
* *
* *
* *
* *
* *
* *
* *
** **
** **
*****
CPP
Java
Python3
C#
PHP
Javascript
// C++ implementation to print circle pattern#include <bits/stdc++.h>using namespace std; // function to print circle patternvoid printPattern(int radius) { // dist represents distance to the center float dist; // for horizontal movement for (int i = 0; i <= 2 * radius; i++) { // for vertical movement for (int j = 0; j <= 2 * radius; j++) { dist = sqrt((i - radius) * (i - radius) + (j - radius) * (j - radius)); // dist should be in the range (radius - 0.5) // and (radius + 0.5) to print stars(*) if (dist > radius - 0.5 && dist < radius + 0.5) cout << "*"; else cout << " "; } cout << "\n"; }} // Driver Codeint main() { int radius = 6; printPattern(radius); return 0;}
// Java implementation to print circle pattern class GFG { // function to print circle patternstatic void printPattern(int radius) { // dist represents distance to the center double dist; // for horizontal movement for (int i = 0; i <= 2 * radius; i++) { // for vertical movement for (int j = 0; j <= 2 * radius; j++) { dist = Math.sqrt((i - radius) * (i - radius) + (j - radius) * (j - radius)); // dist should be in the range (radius - 0.5) // and (radius + 0.5) to print stars(*) if (dist > radius - 0.5 && dist < radius + 0.5) System.out.print("*"); else System.out.print(" "); } System.out.print("\n"); }} // Driver codepublic static void main(String[] args){ int radius = 6; printPattern(radius);}} // This code is contributed by Anant Agarwal.
# Python implementation# to print circle pattern import math # function to print circle patterndef printPattern(radius): # dist represents distance to the center # for horizontal movement for i in range((2 * radius)+1): # for vertical movement for j in range((2 * radius)+1): dist = math.sqrt((i - radius) * (i - radius) + (j - radius) * (j - radius)) # dist should be in the # range (radius - 0.5) # and (radius + 0.5) to print stars(*) if (dist > radius - 0.5 and dist < radius + 0.5): print("*",end="") else: print(" ",end="") print() # Driver code radius = 6printPattern(radius) # This code is contributed# by Anant Agarwal.
// C# implementation to print circle patternusing System; class GFG { // function to print circle pattern static void printPattern(int radius) { // dist represents distance to the center double dist; // for horizontal movement for (int i = 0; i <= 2 * radius; i++) { // for vertical movement for (int j = 0; j <= 2 * radius; j++) { dist = Math.Sqrt((i - radius) * (i - radius) + (j - radius) * (j - radius)); // dist should be in the range // (radius - 0.5) and (radius + 0.5) // to print stars(*) if (dist > radius - 0.5 && dist < radius + 0.5) Console.Write("*"); else Console.Write(" "); } Console.WriteLine(""); } } // Driver code public static void Main() { int radius = 6; printPattern(radius); }} // This code is contributed by vt_m.
<?php// PHP implementation to print// circle pattern // Function to print circle patternfunction printPattern($radius) { // dist represents distance // to the center $dist = 0.0; // for horizontal movement for ($i = 0; $i <= 2 * $radius; $i++) { // for vertical movement for ($j = 0; $j <= 2 * $radius; $j++) { $dist = sqrt(($i - $radius) * ($i - $radius) + ($j - $radius) * ($j - $radius)); // dist should be in the range // (radius - 0.5) and (radius + 0.5) // to print stars(*) if ($dist > $radius - 0.5 && $dist < $radius + 0.5) echo "*"; else echo " "; } echo "\n"; }} // Driver Code$radius = 6;printPattern($radius); // This code is contributed by Mithun Kumar?>
<script> // JavaScript implementation to print circle pattern // function to print circle patternfunction printPattern(radius){// dist represents distance to the center var dist = parseFloat(0); // for horizontal movement for (var i = 0; i <= 2 * radius; i++) { // for vertical movement for (var j = 0; j <= 2 * radius; j++) { dist = Math.sqrt( (i - radius) * (i - radius) + (j - radius) * (j - radius) ); // dist should be in the range (radius - 0.5) // and (radius + 0.5) to print stars(*) if (dist > radius - 0.5 && dist < radius + 0.5) document.write("*"); else document.write(" "); } document.write("<br>"); } } // Driver Code var radius = 6; printPattern(radius); </script>
*****
** **
** **
* *
* *
* *
* *
* *
* *
* *
** **
** **
*****
Mithun Kumar
rdtank
circle
pattern-printing
School Programming
pattern-printing
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Constructors in Java
Exceptions in Java
Python Exception Handling
Python Try Except
Ternary Operator in Python
How JVM Works - JVM Architecture?
Python program to add two numbers
Variables in Java
Data types in Java
Difference between Abstract Class and Interface in Java | [
{
"code": null,
"e": 53,
"s": 25,
"text": "\n09 Apr, 2021"
},
{
"code": null,
"e": 148,
"s": 53,
"text": "Given a positive integer n i.e, radius of the circle, print a circle using stars. Examples : "
},
{
"code": null,
"e": 431,
"s": 148,
"text": "Input : n = 3\nOutput :\n *** \n * * \n* *\n* *\n* *\n * * \n ***\n\nInput : n = 6\nOutput :\n ***** \n ** ** \n ** ** \n * * \n* *\n* *\n* *\n* *\n* *\n * * \n ** ** \n ** ** \n ***** "
},
{
"code": null,
"e": 439,
"s": 435,
"text": "CPP"
},
{
"code": null,
"e": 444,
"s": 439,
"text": "Java"
},
{
"code": null,
"e": 452,
"s": 444,
"text": "Python3"
},
{
"code": null,
"e": 455,
"s": 452,
"text": "C#"
},
{
"code": null,
"e": 459,
"s": 455,
"text": "PHP"
},
{
"code": null,
"e": 470,
"s": 459,
"text": "Javascript"
},
{
"code": "// C++ implementation to print circle pattern#include <bits/stdc++.h>using namespace std; // function to print circle patternvoid printPattern(int radius) { // dist represents distance to the center float dist; // for horizontal movement for (int i = 0; i <= 2 * radius; i++) { // for vertical movement for (int j = 0; j <= 2 * radius; j++) { dist = sqrt((i - radius) * (i - radius) + (j - radius) * (j - radius)); // dist should be in the range (radius - 0.5) // and (radius + 0.5) to print stars(*) if (dist > radius - 0.5 && dist < radius + 0.5) cout << \"*\"; else cout << \" \"; } cout << \"\\n\"; }} // Driver Codeint main() { int radius = 6; printPattern(radius); return 0;}",
"e": 1231,
"s": 470,
"text": null
},
{
"code": "// Java implementation to print circle pattern class GFG { // function to print circle patternstatic void printPattern(int radius) { // dist represents distance to the center double dist; // for horizontal movement for (int i = 0; i <= 2 * radius; i++) { // for vertical movement for (int j = 0; j <= 2 * radius; j++) { dist = Math.sqrt((i - radius) * (i - radius) + (j - radius) * (j - radius)); // dist should be in the range (radius - 0.5) // and (radius + 0.5) to print stars(*) if (dist > radius - 0.5 && dist < radius + 0.5) System.out.print(\"*\"); else System.out.print(\" \"); } System.out.print(\"\\n\"); }} // Driver codepublic static void main(String[] args){ int radius = 6; printPattern(radius);}} // This code is contributed by Anant Agarwal.",
"e": 2097,
"s": 1231,
"text": null
},
{
"code": "# Python implementation# to print circle pattern import math # function to print circle patterndef printPattern(radius): # dist represents distance to the center # for horizontal movement for i in range((2 * radius)+1): # for vertical movement for j in range((2 * radius)+1): dist = math.sqrt((i - radius) * (i - radius) + (j - radius) * (j - radius)) # dist should be in the # range (radius - 0.5) # and (radius + 0.5) to print stars(*) if (dist > radius - 0.5 and dist < radius + 0.5): print(\"*\",end=\"\") else: print(\" \",end=\"\") print() # Driver code radius = 6printPattern(radius) # This code is contributed# by Anant Agarwal.",
"e": 2905,
"s": 2097,
"text": null
},
{
"code": "// C# implementation to print circle patternusing System; class GFG { // function to print circle pattern static void printPattern(int radius) { // dist represents distance to the center double dist; // for horizontal movement for (int i = 0; i <= 2 * radius; i++) { // for vertical movement for (int j = 0; j <= 2 * radius; j++) { dist = Math.Sqrt((i - radius) * (i - radius) + (j - radius) * (j - radius)); // dist should be in the range // (radius - 0.5) and (radius + 0.5) // to print stars(*) if (dist > radius - 0.5 && dist < radius + 0.5) Console.Write(\"*\"); else Console.Write(\" \"); } Console.WriteLine(\"\"); } } // Driver code public static void Main() { int radius = 6; printPattern(radius); }} // This code is contributed by vt_m.",
"e": 4028,
"s": 2905,
"text": null
},
{
"code": "<?php// PHP implementation to print// circle pattern // Function to print circle patternfunction printPattern($radius) { // dist represents distance // to the center $dist = 0.0; // for horizontal movement for ($i = 0; $i <= 2 * $radius; $i++) { // for vertical movement for ($j = 0; $j <= 2 * $radius; $j++) { $dist = sqrt(($i - $radius) * ($i - $radius) + ($j - $radius) * ($j - $radius)); // dist should be in the range // (radius - 0.5) and (radius + 0.5) // to print stars(*) if ($dist > $radius - 0.5 && $dist < $radius + 0.5) echo \"*\"; else echo \" \"; } echo \"\\n\"; }} // Driver Code$radius = 6;printPattern($radius); // This code is contributed by Mithun Kumar?>",
"e": 4981,
"s": 4028,
"text": null
},
{
"code": "<script> // JavaScript implementation to print circle pattern // function to print circle patternfunction printPattern(radius){// dist represents distance to the center var dist = parseFloat(0); // for horizontal movement for (var i = 0; i <= 2 * radius; i++) { // for vertical movement for (var j = 0; j <= 2 * radius; j++) { dist = Math.sqrt( (i - radius) * (i - radius) + (j - radius) * (j - radius) ); // dist should be in the range (radius - 0.5) // and (radius + 0.5) to print stars(*) if (dist > radius - 0.5 && dist < radius + 0.5) document.write(\"*\"); else document.write(\" \"); } document.write(\"<br>\"); } } // Driver Code var radius = 6; printPattern(radius); </script>",
"e": 5900,
"s": 4981,
"text": null
},
{
"code": null,
"e": 6080,
"s": 5900,
"text": " ***** \n ** ** \n ** ** \n * * \n* *\n* *\n* *\n* *\n* *\n * * \n ** ** \n ** ** \n ***** "
},
{
"code": null,
"e": 6095,
"s": 6082,
"text": "Mithun Kumar"
},
{
"code": null,
"e": 6102,
"s": 6095,
"text": "rdtank"
},
{
"code": null,
"e": 6109,
"s": 6102,
"text": "circle"
},
{
"code": null,
"e": 6126,
"s": 6109,
"text": "pattern-printing"
},
{
"code": null,
"e": 6145,
"s": 6126,
"text": "School Programming"
},
{
"code": null,
"e": 6162,
"s": 6145,
"text": "pattern-printing"
},
{
"code": null,
"e": 6260,
"s": 6162,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 6281,
"s": 6260,
"text": "Constructors in Java"
},
{
"code": null,
"e": 6300,
"s": 6281,
"text": "Exceptions in Java"
},
{
"code": null,
"e": 6326,
"s": 6300,
"text": "Python Exception Handling"
},
{
"code": null,
"e": 6344,
"s": 6326,
"text": "Python Try Except"
},
{
"code": null,
"e": 6371,
"s": 6344,
"text": "Ternary Operator in Python"
},
{
"code": null,
"e": 6405,
"s": 6371,
"text": "How JVM Works - JVM Architecture?"
},
{
"code": null,
"e": 6439,
"s": 6405,
"text": "Python program to add two numbers"
},
{
"code": null,
"e": 6457,
"s": 6439,
"text": "Variables in Java"
},
{
"code": null,
"e": 6476,
"s": 6457,
"text": "Data types in Java"
}
] |
Find the maximum number of handshakes | 02 May, 2022
There are N persons in a room. Find the maximum number of Handshakes possible. Given the fact that any two persons shake hand exactly once.
Examples :
Input : N = 2
Output : 1.
There are only 2 persons in the room. 1 handshake take place.
Input : N = 10
Output : 45.
To maximize the number of handshakes, each person should shake hand with every other person in the room. For the first person, there would be N-1 handshakes. For second person there would N-1 person available but he had already shaken hand with the first person. So there would be N-2 handshakes and so on. So, Total number of handshake = N-1 + N-2 +....+ 1 + 0, which is equivalent to ((N-1)*N)/2 (using the formula of sum of first N natural number).
Below is the implementation of this problem.
C++
C
Java
Python3
C#
PHP
Javascript
// C++ program to find maximum number of handshakes.#include <bits/stdc++.h>using namespace std; // Calculating the maximum number of handshake using derived formula.int maxHandshake(int n) { return (n * (n - 1)) / 2; } // Driver Codeint main(){ int n = 10; cout << maxHandshake(n) << endl; return 0;} // This code is contributed by Aditya Kumar (adityakumar129)
// C program to find maximum number of handshakes.#include <stdio.h>// Calculating the maximum number of handshake using derived formula.int maxHandshake(int n) { return (n * (n - 1)) / 2; } // Driver Codeint main(){ int n = 10; printf("%d\n", maxHandshake(n)); return 0;} // This code is contributed by Aditya Kumar (adityakumar129)
// Java program to find maximum number of handshakes. class GFG { // Calculating the maximum number of handshake using // derived formula. static int maxHandshake(int n) { return (n * (n - 1)) / 2; } // Driver code public static void main(String[] args) { int n = 10; System.out.println(maxHandshake(n)); }} // This code is contributed by Aditya Kumar (adityakumar129)
# Python3 program to find maximum# number of handshakes. # Calculating the maximum number# of handshake using derived formula.def maxHandshake(n): return int((n * (n - 1)) / 2) # Driver Coden = 10print(maxHandshake(n)) # This code is contributed by Smitha Dinesh Semwal.
// C# program to find maximum number of// handshakes.using System; class GFG{ // Calculating the maximum number of // handshake using derived formula. static int maxHandshake(int n) { return (n * (n - 1)) / 2; } // Driver code public static void Main () { int n = 10; Console.Write( maxHandshake(n)); }} // This code is contributed by nitin mittal.
<?php// PHP program to// find maximum number// of handshakes. // Calculating the maximum// number of handshake// using derived formula.function maxHandshake($n){ return ($n * ($n - 1))/ 2;} // Driver Code$n = 10;echo maxHandshake($n); // This code is contributed by anuj_67.?>
<script> // JavaScript program to find maximum// number of handshakes. // Calculating the maximum number of// handshake using derived formula.function maxHandshake(n){ return (n * (n - 1)) / 2;} // Driver Codelet n = 10; document.write( maxHandshake(n)); // This code is contributed by souravghosh0416 </script>
Output:
45
Time Complexity : O(1)
This article is contributed by Anuj Chauhan(anuj0503). 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.
nitin mittal
vt_m
souravghosh0416
adityakumar129
Mathematical
Mathematical
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here. | [
{
"code": null,
"e": 53,
"s": 25,
"text": "\n02 May, 2022"
},
{
"code": null,
"e": 193,
"s": 53,
"text": "There are N persons in a room. Find the maximum number of Handshakes possible. Given the fact that any two persons shake hand exactly once."
},
{
"code": null,
"e": 205,
"s": 193,
"text": "Examples : "
},
{
"code": null,
"e": 322,
"s": 205,
"text": "Input : N = 2\nOutput : 1.\nThere are only 2 persons in the room. 1 handshake take place.\n\nInput : N = 10\nOutput : 45."
},
{
"code": null,
"e": 774,
"s": 322,
"text": "To maximize the number of handshakes, each person should shake hand with every other person in the room. For the first person, there would be N-1 handshakes. For second person there would N-1 person available but he had already shaken hand with the first person. So there would be N-2 handshakes and so on. So, Total number of handshake = N-1 + N-2 +....+ 1 + 0, which is equivalent to ((N-1)*N)/2 (using the formula of sum of first N natural number)."
},
{
"code": null,
"e": 821,
"s": 774,
"text": "Below is the implementation of this problem. "
},
{
"code": null,
"e": 825,
"s": 821,
"text": "C++"
},
{
"code": null,
"e": 827,
"s": 825,
"text": "C"
},
{
"code": null,
"e": 832,
"s": 827,
"text": "Java"
},
{
"code": null,
"e": 840,
"s": 832,
"text": "Python3"
},
{
"code": null,
"e": 843,
"s": 840,
"text": "C#"
},
{
"code": null,
"e": 847,
"s": 843,
"text": "PHP"
},
{
"code": null,
"e": 858,
"s": 847,
"text": "Javascript"
},
{
"code": "// C++ program to find maximum number of handshakes.#include <bits/stdc++.h>using namespace std; // Calculating the maximum number of handshake using derived formula.int maxHandshake(int n) { return (n * (n - 1)) / 2; } // Driver Codeint main(){ int n = 10; cout << maxHandshake(n) << endl; return 0;} // This code is contributed by Aditya Kumar (adityakumar129)",
"e": 1231,
"s": 858,
"text": null
},
{
"code": "// C program to find maximum number of handshakes.#include <stdio.h>// Calculating the maximum number of handshake using derived formula.int maxHandshake(int n) { return (n * (n - 1)) / 2; } // Driver Codeint main(){ int n = 10; printf(\"%d\\n\", maxHandshake(n)); return 0;} // This code is contributed by Aditya Kumar (adityakumar129)",
"e": 1575,
"s": 1231,
"text": null
},
{
"code": "// Java program to find maximum number of handshakes. class GFG { // Calculating the maximum number of handshake using // derived formula. static int maxHandshake(int n) { return (n * (n - 1)) / 2; } // Driver code public static void main(String[] args) { int n = 10; System.out.println(maxHandshake(n)); }} // This code is contributed by Aditya Kumar (adityakumar129)",
"e": 1993,
"s": 1575,
"text": null
},
{
"code": "# Python3 program to find maximum# number of handshakes. # Calculating the maximum number# of handshake using derived formula.def maxHandshake(n): return int((n * (n - 1)) / 2) # Driver Coden = 10print(maxHandshake(n)) # This code is contributed by Smitha Dinesh Semwal.",
"e": 2268,
"s": 1993,
"text": null
},
{
"code": "// C# program to find maximum number of// handshakes.using System; class GFG{ // Calculating the maximum number of // handshake using derived formula. static int maxHandshake(int n) { return (n * (n - 1)) / 2; } // Driver code public static void Main () { int n = 10; Console.Write( maxHandshake(n)); }} // This code is contributed by nitin mittal.",
"e": 2675,
"s": 2268,
"text": null
},
{
"code": "<?php// PHP program to// find maximum number// of handshakes. // Calculating the maximum// number of handshake// using derived formula.function maxHandshake($n){ return ($n * ($n - 1))/ 2;} // Driver Code$n = 10;echo maxHandshake($n); // This code is contributed by anuj_67.?>",
"e": 2955,
"s": 2675,
"text": null
},
{
"code": "<script> // JavaScript program to find maximum// number of handshakes. // Calculating the maximum number of// handshake using derived formula.function maxHandshake(n){ return (n * (n - 1)) / 2;} // Driver Codelet n = 10; document.write( maxHandshake(n)); // This code is contributed by souravghosh0416 </script>",
"e": 3272,
"s": 2955,
"text": null
},
{
"code": null,
"e": 3281,
"s": 3272,
"text": "Output: "
},
{
"code": null,
"e": 3284,
"s": 3281,
"text": "45"
},
{
"code": null,
"e": 3307,
"s": 3284,
"text": "Time Complexity : O(1)"
},
{
"code": null,
"e": 3738,
"s": 3307,
"text": "This article is contributed by Anuj Chauhan(anuj0503). 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": 3751,
"s": 3738,
"text": "nitin mittal"
},
{
"code": null,
"e": 3756,
"s": 3751,
"text": "vt_m"
},
{
"code": null,
"e": 3772,
"s": 3756,
"text": "souravghosh0416"
},
{
"code": null,
"e": 3787,
"s": 3772,
"text": "adityakumar129"
},
{
"code": null,
"e": 3800,
"s": 3787,
"text": "Mathematical"
},
{
"code": null,
"e": 3813,
"s": 3800,
"text": "Mathematical"
}
] |
Python | Pandas Series.pct_change() | 21 Jul, 2021
Pandas pct_change() method is applied on series with numeric data to calculate Percentage change after n number of elements. By default, it calculates percentage change of current element from the previous element. (Current-Previous/Previous) * 100.First, n(n=period) values are always NaN, since there is no previous value to calculate change.
Syntax: Series.pct_change(periods=1, fill_method=’pad’, limit=None)Parameters: periods: Defines gap between current and previous value. Default is 1 fill_method: Defines method used to handle null values limit: Number of consecutive NaN values to fill before stopping.Return type: Numeric series with percentage change
Example #1: In this method, a Series is created from Python list using Pandas Series(). The series doesn’t contain any null value and hence pct_change() method is called directly with default value of period parameter, that is 1.
Python3
# importing pandas moduleimport pandas as pd # importing numpy moduleimport numpy as np # creating listlist = [10, 14, 20, 25, 12.5, 13, 0, 50] # creating seriesseries = pd.Series(list) # calling methodresult = series.pct_change() # displayresult
Output:
0 NaN
1 0.400000
2 0.428571
3 0.250000
4 -0.500000
5 0.040000
6 -1.000000
7 inf
dtype: float64
As shown in output, first n values are always equal to NaN. Rest of the values are equal to the percentage change in Old values and are stored at the same position as caller series. Note: Since second last value was 0, the Percentage change is inf. inf stands for infinite. Using the formula, pct_change= x-0/0 = Infinite Example #2: Handling Null valuesIn this example, some null values are also created using Numpy’s np.nan method and passed to the list. ‘bfill‘ is passed to fill_method. bfill stands for Back fill and will fill Null values with values at their very next position.
Python3
# importing pandas moduleimport pandas as pd # importing numpy moduleimport numpy as np # creating listlist =[10, np.nan, 14, 20, 25, 12.5, 13, 0, 50] # creating seriesseries = pd.Series(list) # calling methodresult = series.pct_change(fill_method ='bfill') # displayresult
Output:
0 NaN
1 0.400000
2 0.000000
3 0.428571
4 0.250000
5 -0.500000
6 0.040000
7 -1.000000
8 inf
dtype: float64
As it can be seen in output, value at position 1 is 40 because NaN was replaced by 14. Hence, (14-10/10) *100 = 40. The very next value is 0 because percentage change in 14 and 14 is 0.
sweetyty
Python pandas-series
Python pandas-series-methods
Python-pandas
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Python Dictionary
Different ways to create Pandas Dataframe
Enumerate() in Python
How to Install PIP on Windows ?
*args and **kwargs in Python
Python Classes and Objects
Convert integer to string in Python
Python | os.path.join() method
Create a Pandas DataFrame from Lists
Introduction To PYTHON | [
{
"code": null,
"e": 28,
"s": 0,
"text": "\n21 Jul, 2021"
},
{
"code": null,
"e": 374,
"s": 28,
"text": "Pandas pct_change() method is applied on series with numeric data to calculate Percentage change after n number of elements. By default, it calculates percentage change of current element from the previous element. (Current-Previous/Previous) * 100.First, n(n=period) values are always NaN, since there is no previous value to calculate change. "
},
{
"code": null,
"e": 695,
"s": 374,
"text": "Syntax: Series.pct_change(periods=1, fill_method=’pad’, limit=None)Parameters: periods: Defines gap between current and previous value. Default is 1 fill_method: Defines method used to handle null values limit: Number of consecutive NaN values to fill before stopping.Return type: Numeric series with percentage change "
},
{
"code": null,
"e": 927,
"s": 695,
"text": "Example #1: In this method, a Series is created from Python list using Pandas Series(). The series doesn’t contain any null value and hence pct_change() method is called directly with default value of period parameter, that is 1. "
},
{
"code": null,
"e": 935,
"s": 927,
"text": "Python3"
},
{
"code": "# importing pandas moduleimport pandas as pd # importing numpy moduleimport numpy as np # creating listlist = [10, 14, 20, 25, 12.5, 13, 0, 50] # creating seriesseries = pd.Series(list) # calling methodresult = series.pct_change() # displayresult",
"e": 1186,
"s": 935,
"text": null
},
{
"code": null,
"e": 1196,
"s": 1186,
"text": "Output: "
},
{
"code": null,
"e": 1323,
"s": 1196,
"text": "0 NaN\n1 0.400000\n2 0.428571\n3 0.250000\n4 -0.500000\n5 0.040000\n6 -1.000000\n7 inf\ndtype: float64"
},
{
"code": null,
"e": 1910,
"s": 1323,
"text": "As shown in output, first n values are always equal to NaN. Rest of the values are equal to the percentage change in Old values and are stored at the same position as caller series. Note: Since second last value was 0, the Percentage change is inf. inf stands for infinite. Using the formula, pct_change= x-0/0 = Infinite Example #2: Handling Null valuesIn this example, some null values are also created using Numpy’s np.nan method and passed to the list. ‘bfill‘ is passed to fill_method. bfill stands for Back fill and will fill Null values with values at their very next position. "
},
{
"code": null,
"e": 1918,
"s": 1910,
"text": "Python3"
},
{
"code": "# importing pandas moduleimport pandas as pd # importing numpy moduleimport numpy as np # creating listlist =[10, np.nan, 14, 20, 25, 12.5, 13, 0, 50] # creating seriesseries = pd.Series(list) # calling methodresult = series.pct_change(fill_method ='bfill') # displayresult",
"e": 2196,
"s": 1918,
"text": null
},
{
"code": null,
"e": 2206,
"s": 2196,
"text": "Output: "
},
{
"code": null,
"e": 2347,
"s": 2206,
"text": "0 NaN\n1 0.400000\n2 0.000000\n3 0.428571\n4 0.250000\n5 -0.500000\n6 0.040000\n7 -1.000000\n8 inf\ndtype: float64"
},
{
"code": null,
"e": 2534,
"s": 2347,
"text": "As it can be seen in output, value at position 1 is 40 because NaN was replaced by 14. Hence, (14-10/10) *100 = 40. The very next value is 0 because percentage change in 14 and 14 is 0. "
},
{
"code": null,
"e": 2543,
"s": 2534,
"text": "sweetyty"
},
{
"code": null,
"e": 2564,
"s": 2543,
"text": "Python pandas-series"
},
{
"code": null,
"e": 2593,
"s": 2564,
"text": "Python pandas-series-methods"
},
{
"code": null,
"e": 2607,
"s": 2593,
"text": "Python-pandas"
},
{
"code": null,
"e": 2614,
"s": 2607,
"text": "Python"
},
{
"code": null,
"e": 2712,
"s": 2614,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 2730,
"s": 2712,
"text": "Python Dictionary"
},
{
"code": null,
"e": 2772,
"s": 2730,
"text": "Different ways to create Pandas Dataframe"
},
{
"code": null,
"e": 2794,
"s": 2772,
"text": "Enumerate() in Python"
},
{
"code": null,
"e": 2826,
"s": 2794,
"text": "How to Install PIP on Windows ?"
},
{
"code": null,
"e": 2855,
"s": 2826,
"text": "*args and **kwargs in Python"
},
{
"code": null,
"e": 2882,
"s": 2855,
"text": "Python Classes and Objects"
},
{
"code": null,
"e": 2918,
"s": 2882,
"text": "Convert integer to string in Python"
},
{
"code": null,
"e": 2949,
"s": 2918,
"text": "Python | os.path.join() method"
},
{
"code": null,
"e": 2986,
"s": 2949,
"text": "Create a Pandas DataFrame from Lists"
}
] |
Fix "Execution Failed for task :app:compileDebugJavaWithJavac" in Android Studio - GeeksforGeeks | 19 Jun, 2021
Working on some important java project with Java code involved, and just when you hit that Build hammer icon, you get this:
Error:Execution failed for task ':app:compileDebugJavaWithJavac'.
> Compilation failed; see the compiler error output for details.
* What went wrong:
Execution failed for task ':app:compileDebugJavaWithJavac'.
> Compilation failed; see the compiler error output for details.
Figure 1: The Error
Well, let’s fix this error and get you up and working in no time, just follow the below methods chronologically and it will be a breeze!
GeekTip: Please download the buildTools for this version with SDKManager as a hint if you haven’t already.
and then just change these in your build.gradle file
compileSdkVersion 23
buildToolsVersion "23.0.1"
then sync the Gradle file and rebuild!
Sometimes, it might be the slightest error in your $JAVA_HOME configuration which is tabbing this error, just fix it like this:
export JAVA_HOME="/Library/Java/JavaVirtualMachines/jdk1.8.0_65.jdk/Contents/Home"
GeekTip: Make Change this in the .bash profile
Double-check the build of your app. gradle. It adds an extra.jar file as a dependency that didn’t exist in your project. As a result, remove that and you’re back on track!
If you happen to be running the latest version of Android Studio or the Canary Flavor of the IDE then maybe the issue is there with the certain sdkVersions of your project. Change it this way:
Navigate to File > Project Structure
then
change the compileSdkVersion to any value (like 24) which works with your project like
compileSdkVersion 24
If you’re using the retrolambda build script then you may change its configuration in the build.gradle and your error might be resolved
retrolambda {
jdk System.getenv("JAVA_HOME")
oldJdk System.getenv("JAVA7_HOME")
javaVersion JavaVersion.VERSION_1_8
}
GeekTip: You can also establish a new environment variable named JAVA8 HOME that points to the correct JDK location.
That’s it if you followed the methods given in this article you would’ve resolved this issue and would be back on the track with that project building perfectly as intended!
Android-Studio
Picked
Android
Android
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Flutter - Custom Bottom Navigation Bar
How to Read Data from SQLite Database in Android?
Android Listview in Java with Example
How to Post Data to API using Retrofit in Android?
Retrofit with Kotlin Coroutine in Android
How to Add Image to Drawable Folder in Android Studio?
How to Retrieve Data from the Firebase Realtime Database in Android?
How to Change the Background Color After Clicking the Button in Android?
GridView in Android with Example
ImageView in Android with Example | [
{
"code": null,
"e": 24725,
"s": 24697,
"text": "\n19 Jun, 2021"
},
{
"code": null,
"e": 24849,
"s": 24725,
"text": "Working on some important java project with Java code involved, and just when you hit that Build hammer icon, you get this:"
},
{
"code": null,
"e": 25125,
"s": 24849,
"text": "Error:Execution failed for task ':app:compileDebugJavaWithJavac'.\n> Compilation failed; see the compiler error output for details.\n\n* What went wrong:\nExecution failed for task ':app:compileDebugJavaWithJavac'.\n> Compilation failed; see the compiler error output for details."
},
{
"code": null,
"e": 25145,
"s": 25125,
"text": "Figure 1: The Error"
},
{
"code": null,
"e": 25282,
"s": 25145,
"text": "Well, let’s fix this error and get you up and working in no time, just follow the below methods chronologically and it will be a breeze!"
},
{
"code": null,
"e": 25389,
"s": 25282,
"text": "GeekTip: Please download the buildTools for this version with SDKManager as a hint if you haven’t already."
},
{
"code": null,
"e": 25442,
"s": 25389,
"text": "and then just change these in your build.gradle file"
},
{
"code": null,
"e": 25490,
"s": 25442,
"text": "compileSdkVersion 23\nbuildToolsVersion \"23.0.1\""
},
{
"code": null,
"e": 25529,
"s": 25490,
"text": "then sync the Gradle file and rebuild!"
},
{
"code": null,
"e": 25657,
"s": 25529,
"text": "Sometimes, it might be the slightest error in your $JAVA_HOME configuration which is tabbing this error, just fix it like this:"
},
{
"code": null,
"e": 25740,
"s": 25657,
"text": "export JAVA_HOME=\"/Library/Java/JavaVirtualMachines/jdk1.8.0_65.jdk/Contents/Home\""
},
{
"code": null,
"e": 25787,
"s": 25740,
"text": "GeekTip: Make Change this in the .bash profile"
},
{
"code": null,
"e": 25959,
"s": 25787,
"text": "Double-check the build of your app. gradle. It adds an extra.jar file as a dependency that didn’t exist in your project. As a result, remove that and you’re back on track!"
},
{
"code": null,
"e": 26152,
"s": 25959,
"text": "If you happen to be running the latest version of Android Studio or the Canary Flavor of the IDE then maybe the issue is there with the certain sdkVersions of your project. Change it this way:"
},
{
"code": null,
"e": 26189,
"s": 26152,
"text": "Navigate to File > Project Structure"
},
{
"code": null,
"e": 26194,
"s": 26189,
"text": "then"
},
{
"code": null,
"e": 26281,
"s": 26194,
"text": "change the compileSdkVersion to any value (like 24) which works with your project like"
},
{
"code": null,
"e": 26302,
"s": 26281,
"text": "compileSdkVersion 24"
},
{
"code": null,
"e": 26438,
"s": 26302,
"text": "If you’re using the retrolambda build script then you may change its configuration in the build.gradle and your error might be resolved"
},
{
"code": null,
"e": 26568,
"s": 26438,
"text": "retrolambda {\n jdk System.getenv(\"JAVA_HOME\")\n oldJdk System.getenv(\"JAVA7_HOME\")\n javaVersion JavaVersion.VERSION_1_8\n}"
},
{
"code": null,
"e": 26685,
"s": 26568,
"text": "GeekTip: You can also establish a new environment variable named JAVA8 HOME that points to the correct JDK location."
},
{
"code": null,
"e": 26859,
"s": 26685,
"text": "That’s it if you followed the methods given in this article you would’ve resolved this issue and would be back on the track with that project building perfectly as intended!"
},
{
"code": null,
"e": 26874,
"s": 26859,
"text": "Android-Studio"
},
{
"code": null,
"e": 26881,
"s": 26874,
"text": "Picked"
},
{
"code": null,
"e": 26889,
"s": 26881,
"text": "Android"
},
{
"code": null,
"e": 26897,
"s": 26889,
"text": "Android"
},
{
"code": null,
"e": 26995,
"s": 26897,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 27004,
"s": 26995,
"text": "Comments"
},
{
"code": null,
"e": 27017,
"s": 27004,
"text": "Old Comments"
},
{
"code": null,
"e": 27056,
"s": 27017,
"text": "Flutter - Custom Bottom Navigation Bar"
},
{
"code": null,
"e": 27106,
"s": 27056,
"text": "How to Read Data from SQLite Database in Android?"
},
{
"code": null,
"e": 27144,
"s": 27106,
"text": "Android Listview in Java with Example"
},
{
"code": null,
"e": 27195,
"s": 27144,
"text": "How to Post Data to API using Retrofit in Android?"
},
{
"code": null,
"e": 27237,
"s": 27195,
"text": "Retrofit with Kotlin Coroutine in Android"
},
{
"code": null,
"e": 27292,
"s": 27237,
"text": "How to Add Image to Drawable Folder in Android Studio?"
},
{
"code": null,
"e": 27361,
"s": 27292,
"text": "How to Retrieve Data from the Firebase Realtime Database in Android?"
},
{
"code": null,
"e": 27434,
"s": 27361,
"text": "How to Change the Background Color After Clicking the Button in Android?"
},
{
"code": null,
"e": 27467,
"s": 27434,
"text": "GridView in Android with Example"
}
] |
Python Risk Management: Kelly Criterion | by Lester Leong | Towards Data Science | From the recent events in the financial market correction, I thought it would be a fun time to talk about risk management. Specifically, we’ll go over the Kelly Criterion with a concrete example in Python. First, we’ll discuss a brief overview of the Kelly Criterion. Next, we’ll go over a simple coin flip example. Lastly, we’ll take that simple example and apply it to a financial index.
Data for this article was gathered from: https://www.investing.com/etfs/spdr-s-p-500-historical-data
John Kelly was a scientist in AT&T Bell Labs. At that time, Kelly heard about professional gamblers and became curious on how gamblers managed their capital in the face of uncertainty. Interestingly, he didn’t care about how much money they made, but how they set up their bet sizing to get the most money. Like how most successful gambling stories go, Kelly applied mathematics from information theory to create the Kelly Criterion (KC) [1]. From KC, a gambler could make the best bet size to get the most money in the long run, if she knew her odds of winning and losing.
There are two main parts to the Kelly Criterion (KC): win probability and win/loss ratio. In math formula form, that would be [2]:
But the KC has more applications than just gambling. It can apply to any decision where we know the values of the variables.
From a quick Google search, you’ll find a ton of people citing quotes from value investors applying KC such as [3]:
I can’t be involved in 50 or 75 things. That’s a Noah’s Ark way of investing — you end up with a zoo that way. I like to put meaningful amounts of money in a few things. — Warren Buffett
The wise ones bet heavily when the world offers them that opportunity. They bet big when they have the odds. And the rest of the time, they don’t. It’s just that simple. — Charlie Munger
Most of these big name value investors don’t really apply KC directly anymore. Sure, they apply concentrated bets with their portfolios, but the KC requires repeatable bets for optimal return [4]. This is why if you dig further, most of these investors drop KC. Not because KC is bad, but it is a philosophical investment difference. Value investing involves selecting a few companies and holding them for awhile to fair value. In the calculation for fair value, most do not have enough repeatable odds. This is why most investors that do apply KC tend to employ more quantitative strategies that mirror a casino’s edge.
Enough background talk, let’s get to some coding examples! Now, we’ll go over how to apply KC, when you bet with a coin flip that is favored to you by 55% (a fair coin would have a 50% win chance). For our example, let’s assume you win $1 or lose $1 for the heads or tails outcome that is related to how much risked. In other words, we are assuming 1 to 1 payoff relative to our KC or risked amount per bet. Also the code going forward was modified from Python for Finance [5].
#Import librariesimport mathimport timeimport numpy as npimport pandas as pdimport datetime as dtimport cufflinks as cffrom pylab import pltnp.random.seed(1) # For reproducibilityplt.style.use('seaborn') # I think this looks pretty%matplotlib inline # To get out plots#Coin flip variable set upp = 0.55 #Fixes the probability for heads.f = p - (1-p) #Calculates the optimal fraction according to the Kelly criterion.f
f = 0.10
The above is optimal Kelly Criterion bet size (f). This means that for a 1 to 1 payoff and a 55% favored chance to win, we should risk 10% of our total capital for maximizing our profit.
# Preparing our simulation of coin flips with variablesI = 50 #The number of series to be simulated.n = 100 #The number of trials per series.def run_simulation(f): c = np.zeros((n, I)) #Instantiates an ndarray object to store the simulation results. c[0] = 100 #Initializes the starting capital with 100. for i in range(I): #Outer loop for the series simulations. for t in range(1,n): #Inner loop for the series itself. o = np.random.binomial(1, p) #Simulates the tossing of a coin. if o > 0: #If 1, i.e., heads ... c[t, i] = (1+f) * c[t-1,i] #... then add the win to the capital. else: #If 0, i.e., tails ... c[t, i] = (1-f) * c[t-1,i] #... then subtract the loss from the capital. return cc_1 = run_simulation(f) #Runs the simulation.c_1.round(2) #Looking at a simulation
When running simulations, I sometimes like to check how the data looks just to see nothing crazy is going on. We’ll visualize this data to make it easier to understand.
plt.figure(figsize=(10,6))plt.plot(c_1, 'b', lw=0.5) #Plots all 50 series.plt.plot(c_1.mean(axis=1), 'r', lw=2.5); #Plots the average over all 50 series.plt.title('50 Simulations of Rigged Coin Flips');plt.xlabel('Number of trials');plt.ylabel('$ Amount Won/Lost');
For the plot above, the blue lines represent the 50 simulation coin flips we ran, and the red line represents the average of all the simulations. It’s interesting to see how even with a slight edge (55% favored for us to win) that there are few situations where we are still losing. This is probably why a lot of people have problems assessing the profitability of situations that have to do with chance.
Besides betting with 10% of our capital at all times, what would happen with other bet sizes/different KC values?
c_2 = run_simulation(0.05) #Simulation with f = 0.05.c_3 = run_simulation(0.25) #Simulation with f = 0.25.c_4 = run_simulation(0.5) #Simulation with f = 0.5.plt.figure(figsize=(10, 6))plt.plot(c_1.mean(axis=1), 'r', label='$f^*=0.1$')plt.plot(c_2.mean(axis=1), 'b', label='$f=0.05$')plt.plot(c_3.mean(axis=1), 'y', label='$f=0.25$')plt.plot(c_4.mean(axis=1), 'm', label='$f=0.5$')plt.legend(loc=0);plt.title('Varied KC Simulations of Rigged Coin Flips');plt.xlabel('Number of trials');plt.ylabel('$ Amount Won/Lost');
From our varied KC, we can see that returns ($ Amount won) vary greatly. Specifically, the higher we increase KC, we increase the chance of winning more money, but also run higher risk. So far our optimal value of 0.10 does appear best (a consistent profitable return), while higher values have huge changes in returns (f=0.25) or even losing (f=0.5).
Now let’s get out of the simple example and push it into the real world. We’re going to apply KC to the S&P 500 stock index. To apply these changes, our KC formula will look like this [5]:
Mu ( μ) = average returns of SPY r = risk free rate sigma2 (σ2) = variance of SPY Instead of scrolling up for the data link, you can find it here again: https://www.investing.com/etfs/spdr-s-p-500-historical-data [6].
#Loading SPY datadata = pd.read_csv('SPY Historical Data.csv', index_col=0, parse_dates=True)#Light Feature Engineering on Returnsdata['Change %'] = data['Change %'].map(lambda x: x.rstrip('%')).astype(float) / 100data.dropna(inplace=True)data.tail()
Just checking the data to see if our feature engineering worked. Data from Investing.com normally has a % symbol that Python tends to pick up as an object and not a number.
mu = data['Change %'].mean() * 252 #Calculates the annualized return.sigma = (data['Change %'].std() * 252 ** 0.5) #Calculates the annualized volatility.r = 0.0179 #1 year treasury ratef = (mu - r) / sigma ** 2 #Calculates the optimal Kelly fraction to be invested in the strategy.f
f = 4.2
From our calculations, the KC value is 4.2, meaning we should bet 4.2x for every $1 invested in the SPY. For those of you more comfortable with finance, it means we should leverage our trade by 4.2x to maximize our expected return. Intuitively, sounds kind of high to me, but let’s run a few simulations like before.
equs = [] # preallocating space for our simulationsdef kelly_strategy(f): global equs equ = 'equity_{:.2f}'.format(f) equs.append(equ) cap = 'capital_{:.2f}'.format(f) data[equ] = 1 #Generates a new column for equity and sets the initial value to 1. data[cap] = data[equ] * f #Generates a new column for capital and sets the initial value to 1·f∗. for i, t in enumerate(data.index[1:]): t_1 = data.index[i] #Picks the right DatetimeIndex value for the previous values. data.loc[t, cap] = data[cap].loc[t_1] * math.exp(data['Change %'].loc[t]) data.loc[t, equ] = data[cap].loc[t] - data[cap].loc[t_1] + data[equ].loc[t_1] data.loc[t, cap] = data[equ].loc[t] * f kelly_strategy(f * 0.5) # Values for 1/2 KCkelly_strategy(f * 0.66) # Values for 2/3 KCkelly_strategy(f) # Values for optimal KCax = data['Change %'].cumsum().apply(np.exp).plot(legend=True,figsize=(10, 6)) data[equs].plot(ax=ax, legend=True);plt.title('Varied KC Values on SPY, Starting from $1');plt.xlabel('Years');plt.ylabel('$ Return')
Just like in our coin flip example, higher values for KC lead to greater volatility. The optimal amount of 4.2 lost over 50% of its value around the beginning of 2019. That’s pretty scary for most people, which is why practitioners that apply KC normally apply half of KC (equity_2.10 from out plot).
We covered quite a bit of ground today. We went over a brief history of the Kelly Criterion (KC) with how investors apply the formula. Then we maximized our return with a simple rigged coin flip example. Lastly, we applied what we learned from the coin flip example into the S&P 500 stock index. From our little simulation, we learned that, even though KC might recommend a high value, sometimes we will take a reduced KC value to avoid unwanted volatility. There are not a lot of people who can tolerate 50% draw downs (largest loss amount) and don’t get me started on the mental stress of going through one! So take the strategic solution, have more peace of mind by going lower than full KC.
Disclaimer: All things stated in this article are of my own opinion and not of any employer. Investing carries serious risk and consult your investment advisor before taking any investment action. Also, this post contains affiliate links.
References
[1] Finbox, Investing With Kelly (2018), https://www.valuewalk.com/2018/04/investing-with-the-kelly-criterion-model/
[2] J. Kuepper, Using the Kelly Criterion for Asset Allocation and Money Management (2019), https://www.investopedia.com/articles/trading/04/091504.asp
[3] OSV, Apply the Kelly Criterion to Investing and Your Portfolio Sizing (2014), https://www.oldschoolvalue.com/blog/investing-strategy/kelly-criterion-investing-portfolio-sizing/
[4] P. Lindmark, Investing with the Kelly Criterion (2007), https://www.gurufocus.com/news/4883/investing-with-the-kelly-criterion
[5] Y. Hiplisch, Python for Finance: Mastering Data-Driven Finance (2018), O’Reilly Media https://amzn.to/2KuHPRG
[6] Investing.com, SPY 500 Historical Data, https://www.investing.com/etfs/spdr-s-p-500-historical-data | [
{
"code": null,
"e": 562,
"s": 172,
"text": "From the recent events in the financial market correction, I thought it would be a fun time to talk about risk management. Specifically, we’ll go over the Kelly Criterion with a concrete example in Python. First, we’ll discuss a brief overview of the Kelly Criterion. Next, we’ll go over a simple coin flip example. Lastly, we’ll take that simple example and apply it to a financial index."
},
{
"code": null,
"e": 663,
"s": 562,
"text": "Data for this article was gathered from: https://www.investing.com/etfs/spdr-s-p-500-historical-data"
},
{
"code": null,
"e": 1237,
"s": 663,
"text": "John Kelly was a scientist in AT&T Bell Labs. At that time, Kelly heard about professional gamblers and became curious on how gamblers managed their capital in the face of uncertainty. Interestingly, he didn’t care about how much money they made, but how they set up their bet sizing to get the most money. Like how most successful gambling stories go, Kelly applied mathematics from information theory to create the Kelly Criterion (KC) [1]. From KC, a gambler could make the best bet size to get the most money in the long run, if she knew her odds of winning and losing."
},
{
"code": null,
"e": 1368,
"s": 1237,
"text": "There are two main parts to the Kelly Criterion (KC): win probability and win/loss ratio. In math formula form, that would be [2]:"
},
{
"code": null,
"e": 1493,
"s": 1368,
"text": "But the KC has more applications than just gambling. It can apply to any decision where we know the values of the variables."
},
{
"code": null,
"e": 1609,
"s": 1493,
"text": "From a quick Google search, you’ll find a ton of people citing quotes from value investors applying KC such as [3]:"
},
{
"code": null,
"e": 1796,
"s": 1609,
"text": "I can’t be involved in 50 or 75 things. That’s a Noah’s Ark way of investing — you end up with a zoo that way. I like to put meaningful amounts of money in a few things. — Warren Buffett"
},
{
"code": null,
"e": 1983,
"s": 1796,
"text": "The wise ones bet heavily when the world offers them that opportunity. They bet big when they have the odds. And the rest of the time, they don’t. It’s just that simple. — Charlie Munger"
},
{
"code": null,
"e": 2604,
"s": 1983,
"text": "Most of these big name value investors don’t really apply KC directly anymore. Sure, they apply concentrated bets with their portfolios, but the KC requires repeatable bets for optimal return [4]. This is why if you dig further, most of these investors drop KC. Not because KC is bad, but it is a philosophical investment difference. Value investing involves selecting a few companies and holding them for awhile to fair value. In the calculation for fair value, most do not have enough repeatable odds. This is why most investors that do apply KC tend to employ more quantitative strategies that mirror a casino’s edge."
},
{
"code": null,
"e": 3082,
"s": 2604,
"text": "Enough background talk, let’s get to some coding examples! Now, we’ll go over how to apply KC, when you bet with a coin flip that is favored to you by 55% (a fair coin would have a 50% win chance). For our example, let’s assume you win $1 or lose $1 for the heads or tails outcome that is related to how much risked. In other words, we are assuming 1 to 1 payoff relative to our KC or risked amount per bet. Also the code going forward was modified from Python for Finance [5]."
},
{
"code": null,
"e": 3505,
"s": 3082,
"text": "#Import librariesimport mathimport timeimport numpy as npimport pandas as pdimport datetime as dtimport cufflinks as cffrom pylab import pltnp.random.seed(1) # For reproducibilityplt.style.use('seaborn') # I think this looks pretty%matplotlib inline # To get out plots#Coin flip variable set upp = 0.55 #Fixes the probability for heads.f = p - (1-p) #Calculates the optimal fraction according to the Kelly criterion.f"
},
{
"code": null,
"e": 3514,
"s": 3505,
"text": "f = 0.10"
},
{
"code": null,
"e": 3701,
"s": 3514,
"text": "The above is optimal Kelly Criterion bet size (f). This means that for a 1 to 1 payoff and a 55% favored chance to win, we should risk 10% of our total capital for maximizing our profit."
},
{
"code": null,
"e": 4563,
"s": 3701,
"text": "# Preparing our simulation of coin flips with variablesI = 50 #The number of series to be simulated.n = 100 #The number of trials per series.def run_simulation(f): c = np.zeros((n, I)) #Instantiates an ndarray object to store the simulation results. c[0] = 100 #Initializes the starting capital with 100. for i in range(I): #Outer loop for the series simulations. for t in range(1,n): #Inner loop for the series itself. o = np.random.binomial(1, p) #Simulates the tossing of a coin. if o > 0: #If 1, i.e., heads ... c[t, i] = (1+f) * c[t-1,i] #... then add the win to the capital. else: #If 0, i.e., tails ... c[t, i] = (1-f) * c[t-1,i] #... then subtract the loss from the capital. return cc_1 = run_simulation(f) #Runs the simulation.c_1.round(2) #Looking at a simulation"
},
{
"code": null,
"e": 4732,
"s": 4563,
"text": "When running simulations, I sometimes like to check how the data looks just to see nothing crazy is going on. We’ll visualize this data to make it easier to understand."
},
{
"code": null,
"e": 4998,
"s": 4732,
"text": "plt.figure(figsize=(10,6))plt.plot(c_1, 'b', lw=0.5) #Plots all 50 series.plt.plot(c_1.mean(axis=1), 'r', lw=2.5); #Plots the average over all 50 series.plt.title('50 Simulations of Rigged Coin Flips');plt.xlabel('Number of trials');plt.ylabel('$ Amount Won/Lost');"
},
{
"code": null,
"e": 5403,
"s": 4998,
"text": "For the plot above, the blue lines represent the 50 simulation coin flips we ran, and the red line represents the average of all the simulations. It’s interesting to see how even with a slight edge (55% favored for us to win) that there are few situations where we are still losing. This is probably why a lot of people have problems assessing the profitability of situations that have to do with chance."
},
{
"code": null,
"e": 5517,
"s": 5403,
"text": "Besides betting with 10% of our capital at all times, what would happen with other bet sizes/different KC values?"
},
{
"code": null,
"e": 6037,
"s": 5517,
"text": "c_2 = run_simulation(0.05) #Simulation with f = 0.05.c_3 = run_simulation(0.25) #Simulation with f = 0.25.c_4 = run_simulation(0.5) #Simulation with f = 0.5.plt.figure(figsize=(10, 6))plt.plot(c_1.mean(axis=1), 'r', label='$f^*=0.1$')plt.plot(c_2.mean(axis=1), 'b', label='$f=0.05$')plt.plot(c_3.mean(axis=1), 'y', label='$f=0.25$')plt.plot(c_4.mean(axis=1), 'm', label='$f=0.5$')plt.legend(loc=0);plt.title('Varied KC Simulations of Rigged Coin Flips');plt.xlabel('Number of trials');plt.ylabel('$ Amount Won/Lost');"
},
{
"code": null,
"e": 6389,
"s": 6037,
"text": "From our varied KC, we can see that returns ($ Amount won) vary greatly. Specifically, the higher we increase KC, we increase the chance of winning more money, but also run higher risk. So far our optimal value of 0.10 does appear best (a consistent profitable return), while higher values have huge changes in returns (f=0.25) or even losing (f=0.5)."
},
{
"code": null,
"e": 6578,
"s": 6389,
"text": "Now let’s get out of the simple example and push it into the real world. We’re going to apply KC to the S&P 500 stock index. To apply these changes, our KC formula will look like this [5]:"
},
{
"code": null,
"e": 6796,
"s": 6578,
"text": "Mu ( μ) = average returns of SPY r = risk free rate sigma2 (σ2) = variance of SPY Instead of scrolling up for the data link, you can find it here again: https://www.investing.com/etfs/spdr-s-p-500-historical-data [6]."
},
{
"code": null,
"e": 7047,
"s": 6796,
"text": "#Loading SPY datadata = pd.read_csv('SPY Historical Data.csv', index_col=0, parse_dates=True)#Light Feature Engineering on Returnsdata['Change %'] = data['Change %'].map(lambda x: x.rstrip('%')).astype(float) / 100data.dropna(inplace=True)data.tail()"
},
{
"code": null,
"e": 7220,
"s": 7047,
"text": "Just checking the data to see if our feature engineering worked. Data from Investing.com normally has a % symbol that Python tends to pick up as an object and not a number."
},
{
"code": null,
"e": 7504,
"s": 7220,
"text": "mu = data['Change %'].mean() * 252 #Calculates the annualized return.sigma = (data['Change %'].std() * 252 ** 0.5) #Calculates the annualized volatility.r = 0.0179 #1 year treasury ratef = (mu - r) / sigma ** 2 #Calculates the optimal Kelly fraction to be invested in the strategy.f"
},
{
"code": null,
"e": 7512,
"s": 7504,
"text": "f = 4.2"
},
{
"code": null,
"e": 7829,
"s": 7512,
"text": "From our calculations, the KC value is 4.2, meaning we should bet 4.2x for every $1 invested in the SPY. For those of you more comfortable with finance, it means we should leverage our trade by 4.2x to maximize our expected return. Intuitively, sounds kind of high to me, but let’s run a few simulations like before."
},
{
"code": null,
"e": 8898,
"s": 7829,
"text": "equs = [] # preallocating space for our simulationsdef kelly_strategy(f): global equs equ = 'equity_{:.2f}'.format(f) equs.append(equ) cap = 'capital_{:.2f}'.format(f) data[equ] = 1 #Generates a new column for equity and sets the initial value to 1. data[cap] = data[equ] * f #Generates a new column for capital and sets the initial value to 1·f∗. for i, t in enumerate(data.index[1:]): t_1 = data.index[i] #Picks the right DatetimeIndex value for the previous values. data.loc[t, cap] = data[cap].loc[t_1] * math.exp(data['Change %'].loc[t]) data.loc[t, equ] = data[cap].loc[t] - data[cap].loc[t_1] + data[equ].loc[t_1] data.loc[t, cap] = data[equ].loc[t] * f kelly_strategy(f * 0.5) # Values for 1/2 KCkelly_strategy(f * 0.66) # Values for 2/3 KCkelly_strategy(f) # Values for optimal KCax = data['Change %'].cumsum().apply(np.exp).plot(legend=True,figsize=(10, 6)) data[equs].plot(ax=ax, legend=True);plt.title('Varied KC Values on SPY, Starting from $1');plt.xlabel('Years');plt.ylabel('$ Return')"
},
{
"code": null,
"e": 9199,
"s": 8898,
"text": "Just like in our coin flip example, higher values for KC lead to greater volatility. The optimal amount of 4.2 lost over 50% of its value around the beginning of 2019. That’s pretty scary for most people, which is why practitioners that apply KC normally apply half of KC (equity_2.10 from out plot)."
},
{
"code": null,
"e": 9894,
"s": 9199,
"text": "We covered quite a bit of ground today. We went over a brief history of the Kelly Criterion (KC) with how investors apply the formula. Then we maximized our return with a simple rigged coin flip example. Lastly, we applied what we learned from the coin flip example into the S&P 500 stock index. From our little simulation, we learned that, even though KC might recommend a high value, sometimes we will take a reduced KC value to avoid unwanted volatility. There are not a lot of people who can tolerate 50% draw downs (largest loss amount) and don’t get me started on the mental stress of going through one! So take the strategic solution, have more peace of mind by going lower than full KC."
},
{
"code": null,
"e": 10133,
"s": 9894,
"text": "Disclaimer: All things stated in this article are of my own opinion and not of any employer. Investing carries serious risk and consult your investment advisor before taking any investment action. Also, this post contains affiliate links."
},
{
"code": null,
"e": 10144,
"s": 10133,
"text": "References"
},
{
"code": null,
"e": 10261,
"s": 10144,
"text": "[1] Finbox, Investing With Kelly (2018), https://www.valuewalk.com/2018/04/investing-with-the-kelly-criterion-model/"
},
{
"code": null,
"e": 10413,
"s": 10261,
"text": "[2] J. Kuepper, Using the Kelly Criterion for Asset Allocation and Money Management (2019), https://www.investopedia.com/articles/trading/04/091504.asp"
},
{
"code": null,
"e": 10594,
"s": 10413,
"text": "[3] OSV, Apply the Kelly Criterion to Investing and Your Portfolio Sizing (2014), https://www.oldschoolvalue.com/blog/investing-strategy/kelly-criterion-investing-portfolio-sizing/"
},
{
"code": null,
"e": 10725,
"s": 10594,
"text": "[4] P. Lindmark, Investing with the Kelly Criterion (2007), https://www.gurufocus.com/news/4883/investing-with-the-kelly-criterion"
},
{
"code": null,
"e": 10839,
"s": 10725,
"text": "[5] Y. Hiplisch, Python for Finance: Mastering Data-Driven Finance (2018), O’Reilly Media https://amzn.to/2KuHPRG"
}
] |
A Demystifying Introduction to Formal Concept Analysis (FCA) | by Mathieu d'Aquin | Towards Data Science | How often does this happen? A new data repository comes up or someone points you to a nice new dataset from which you could see that there might be something interesting to do. Then you look at it, and well... it is a bunch of numbers. You can run some stats, and poke around, but what does it really mean?
Maybe formal concept analysis (FCA) can help. It might look complicated, but it is based on one rather simple idea: The one of the concept. A concept (kind of like a class in object-oriented programming) represents a set of objects that share a set of attributes. Generally, in FCA, those attributes are binary.
For example, let’s say that we are looking at data about four countries, which can be big or small, and where one might drive on the left, or the right. We can represent the attributes for each of the countries in a binary matrix as below.
That matrix is what is called the formal context and we can see that concepts that make sense here include the ones of big countries, or of big countries driving on the right side. The set of objects (countries) that are included in the first one (called the extent of the concept) are country1, country2 and country3, and the second one only includes country1 and country3. The intent of each concept, i.e. the set of attributes shared is, for the former, [size:big] and, for the later, [size:big,driving:right].
There is one thing we need to add to the definition of a concept and that is at the core of FCA: Concepts have to be closed. What that means is that the set of objects in the extent should be exactly the ones that share the attributes of the intent, and the set of attributes in the intent should be exactly the ones shared by objects in the extent.
From that definition, [size:big] and [size:big,driving:right] are closed, but the concept [size:small] is not. Indeed, only country4 has this attribute, but it also has [driving:right]. Therefore, to make it closed, the concept has to be defined by both attributes shared by elements of the extent: [size:small,driving:right]. The same applies to [driving:left]. The closed concept in this case is [size:big, driving:left].
Now, finding closed concepts is certainly interesting, but what makes the whole thing really powerful is that those concepts are naturally organised by subsumption. Intuitively, a concept subsumes another one if it is more general. More formally, it means that its intent (attributes) are included in the other concept’s intent, and its extent (objects) includes the other concept’s extent. Basically, [size:big] subsumes [size:big,driving:left].
This relation of subsumption is a partial order, which means that one concept might subsume another, be subsumed by another, or neither. Therefore, all the closed concepts for a given dataset (formal context) are naturally organised in a hierarchy (a lattice), from the more general to the more specific.
Of course, for such a small example, it does not really help that much. So, let’s have a look at what it does on a more significant example.
To get a more realistic example, I used Wikidata to retrieve a list of countries and the information (properties) associated with them. Skipping the details (all the code for recreating the dataset is available with the basic implementation of FCA and of the example at github.com/mdaquin/fca.js), the dataset includes information from countries which had values for properties shared by more than 90% of the countries and that had either numerical values, or less than 5 unique categorical values. For each of those countries, the values of properties are transformed into binary attributes by:
For categorical properties, creating an attribute for each possible value, e.g. driving side:left (what machine learning practitioners would call one hot encoding).
For numerical properties, creating attributes for low, medium and high values based on the 33% and 67% percentiles, e.g. population:low (a very basic approach to discretization).
The result is a formal context of 147 objects (countries) and 33 binary attributes. For example, France is represented by the following attributes:
France:[ "area:high", "population:high", "mains voltage:medium", "driving side:right", "inflation rate:low", "total fertility rate:low", "PPP GDP per capita:high", "life expectancy:high", "has quality:free country", "nominal GDP per capita:high", "nominal GDP:high"]
Looking at this formal context feels a bit like looking at the matrix. Columns after columns of Xs which feel kind of random, but also kind of not: There are patterns in there, so let’s try to find them.
Building the concept lattice is a complex task, but for the purpose of this example, I used a basic method. First I built all the close concepts by adding each object by its intent, and any intersection with existing concepts’ intent that wasn’t there already. Then I iterate over the concepts to build the subsumption relations. Finally, I populate each concept with their extent. This is far from the most efficient algorithm to do this (see this paper for a nice list of better ones) and javascript is not quite the best language for it, but on my laptop, it takes just a few minutes to complete, so it is not too bad.
The first thing to notice is that the algorithm finds 8,840 concepts. This might sound like a lot, but it is nowhere near the maximum number of concepts we could have found with that number of attributes! I guess that’s the reason most tutorials and examples on FCA tend to use only very basic examples. It is not the techniques that are complicated, it is the result.
However, even if inspecting all those concepts individually would be tedious and mostly pointless work, the key thing here is that they come not as a list of sets of attributes, but through a navigational structure to explore them. Indeed, starting from the top of the lattice (i.e. the concept with no attribute as intent and all objects as extent), we can focus on the next level down for example on countries with a low life expectancy ([life expectancy:low]), to find that there are 20 subconcepts, including countries which also have a low population (14 of them). At the third level, we find only 5 possible other concepts, which in addition to low life expectancy and population, also have:
a low nominal GDP,
a high total fertility rate,
a medium mains voltage,
a low PPP GDP per capita, or
a high inflation rate
There could have been many other concepts, but that only those five are there, and that FCA is based on closed sets of attributes, mean that those other concepts simply did not exist in the data. In our list of countries, you cannot have a low life expectancy and population, and not be in one of those 5 other categories too. The lattice goes deeper into subdividing this group of countries and provides a convenient way to explore the dataset. But can it do more?
Other than providing a (rather enormous) navigation structure, the lattice once constructed can also be used to identify rules that apply in the data. The simple intuition here is that if a concept C’s intent includes attributes that are not in the intent of any of its parents (i.e. subsuming concept), then those attributes imply the ones of the parents. This is again due to the fact that the concepts are closed: If C’s own attributes (its proper intent) could appear without the ones of the parents, then they would have already shown up at levels above.
Unfortunately, that does not happen in our country dataset. We can, however, see when that almost happens. The support of a concept is the number of objects (countries) in its extent. For example, the support of [life expectancy: low, population: low] is 14, as seen above. If the support of a concept C is almost the same as the support of one of its parent concepts D, that must mean that the attributes of D’s intent almost imply the ones of C’s intent. In other words, if C has a support of 9 with the intent [a,b,c] and S, the subsuming concept, has a support of 10 with the intent [a,b], we can say that any object with attributes a and b also has c in 90% of the cases. We have an association rule stating that a and b imply c, with a confidence of 90% (and a support of 9).
That, our country dataset has a lot of. Only focusing on rules with a confidence higher than 95% and a support of at least 25, we can find for example the following rule:
inflation rate:high,total fertility rate:high -> life expectancy:low s:25 c:0.9615384615384616
which states that, with 96.1% confidence, countries with a high inflation rate and a high fertility rate also have a low life expectancy, and that this applies to 25 countries in our dataset.
There are many more applications of FCA and association rule extraction, but to me, dataset exploration and understanding is among the most significant ones. The rule above and the structure of the lattice might reflect a certain reality of the world, or might be an artefact of the way the dataset was constructed. It might say something about countries or show some bias in the data. Whichever it is, at a time when the explainability of data processes is becoming increasingly crucial, a process that can tell me “here is something that your data says” or “here is a significant pattern I have found in a corner of your dataset” is invaluable to understand the data and the results of whatever we are doing with it. | [
{
"code": null,
"e": 479,
"s": 172,
"text": "How often does this happen? A new data repository comes up or someone points you to a nice new dataset from which you could see that there might be something interesting to do. Then you look at it, and well... it is a bunch of numbers. You can run some stats, and poke around, but what does it really mean?"
},
{
"code": null,
"e": 791,
"s": 479,
"text": "Maybe formal concept analysis (FCA) can help. It might look complicated, but it is based on one rather simple idea: The one of the concept. A concept (kind of like a class in object-oriented programming) represents a set of objects that share a set of attributes. Generally, in FCA, those attributes are binary."
},
{
"code": null,
"e": 1031,
"s": 791,
"text": "For example, let’s say that we are looking at data about four countries, which can be big or small, and where one might drive on the left, or the right. We can represent the attributes for each of the countries in a binary matrix as below."
},
{
"code": null,
"e": 1545,
"s": 1031,
"text": "That matrix is what is called the formal context and we can see that concepts that make sense here include the ones of big countries, or of big countries driving on the right side. The set of objects (countries) that are included in the first one (called the extent of the concept) are country1, country2 and country3, and the second one only includes country1 and country3. The intent of each concept, i.e. the set of attributes shared is, for the former, [size:big] and, for the later, [size:big,driving:right]."
},
{
"code": null,
"e": 1895,
"s": 1545,
"text": "There is one thing we need to add to the definition of a concept and that is at the core of FCA: Concepts have to be closed. What that means is that the set of objects in the extent should be exactly the ones that share the attributes of the intent, and the set of attributes in the intent should be exactly the ones shared by objects in the extent."
},
{
"code": null,
"e": 2319,
"s": 1895,
"text": "From that definition, [size:big] and [size:big,driving:right] are closed, but the concept [size:small] is not. Indeed, only country4 has this attribute, but it also has [driving:right]. Therefore, to make it closed, the concept has to be defined by both attributes shared by elements of the extent: [size:small,driving:right]. The same applies to [driving:left]. The closed concept in this case is [size:big, driving:left]."
},
{
"code": null,
"e": 2766,
"s": 2319,
"text": "Now, finding closed concepts is certainly interesting, but what makes the whole thing really powerful is that those concepts are naturally organised by subsumption. Intuitively, a concept subsumes another one if it is more general. More formally, it means that its intent (attributes) are included in the other concept’s intent, and its extent (objects) includes the other concept’s extent. Basically, [size:big] subsumes [size:big,driving:left]."
},
{
"code": null,
"e": 3071,
"s": 2766,
"text": "This relation of subsumption is a partial order, which means that one concept might subsume another, be subsumed by another, or neither. Therefore, all the closed concepts for a given dataset (formal context) are naturally organised in a hierarchy (a lattice), from the more general to the more specific."
},
{
"code": null,
"e": 3212,
"s": 3071,
"text": "Of course, for such a small example, it does not really help that much. So, let’s have a look at what it does on a more significant example."
},
{
"code": null,
"e": 3808,
"s": 3212,
"text": "To get a more realistic example, I used Wikidata to retrieve a list of countries and the information (properties) associated with them. Skipping the details (all the code for recreating the dataset is available with the basic implementation of FCA and of the example at github.com/mdaquin/fca.js), the dataset includes information from countries which had values for properties shared by more than 90% of the countries and that had either numerical values, or less than 5 unique categorical values. For each of those countries, the values of properties are transformed into binary attributes by:"
},
{
"code": null,
"e": 3973,
"s": 3808,
"text": "For categorical properties, creating an attribute for each possible value, e.g. driving side:left (what machine learning practitioners would call one hot encoding)."
},
{
"code": null,
"e": 4152,
"s": 3973,
"text": "For numerical properties, creating attributes for low, medium and high values based on the 33% and 67% percentiles, e.g. population:low (a very basic approach to discretization)."
},
{
"code": null,
"e": 4300,
"s": 4152,
"text": "The result is a formal context of 147 objects (countries) and 33 binary attributes. For example, France is represented by the following attributes:"
},
{
"code": null,
"e": 4578,
"s": 4300,
"text": "France:[ \"area:high\", \"population:high\", \"mains voltage:medium\", \"driving side:right\", \"inflation rate:low\", \"total fertility rate:low\", \"PPP GDP per capita:high\", \"life expectancy:high\", \"has quality:free country\", \"nominal GDP per capita:high\", \"nominal GDP:high\"]"
},
{
"code": null,
"e": 4782,
"s": 4578,
"text": "Looking at this formal context feels a bit like looking at the matrix. Columns after columns of Xs which feel kind of random, but also kind of not: There are patterns in there, so let’s try to find them."
},
{
"code": null,
"e": 5404,
"s": 4782,
"text": "Building the concept lattice is a complex task, but for the purpose of this example, I used a basic method. First I built all the close concepts by adding each object by its intent, and any intersection with existing concepts’ intent that wasn’t there already. Then I iterate over the concepts to build the subsumption relations. Finally, I populate each concept with their extent. This is far from the most efficient algorithm to do this (see this paper for a nice list of better ones) and javascript is not quite the best language for it, but on my laptop, it takes just a few minutes to complete, so it is not too bad."
},
{
"code": null,
"e": 5773,
"s": 5404,
"text": "The first thing to notice is that the algorithm finds 8,840 concepts. This might sound like a lot, but it is nowhere near the maximum number of concepts we could have found with that number of attributes! I guess that’s the reason most tutorials and examples on FCA tend to use only very basic examples. It is not the techniques that are complicated, it is the result."
},
{
"code": null,
"e": 6471,
"s": 5773,
"text": "However, even if inspecting all those concepts individually would be tedious and mostly pointless work, the key thing here is that they come not as a list of sets of attributes, but through a navigational structure to explore them. Indeed, starting from the top of the lattice (i.e. the concept with no attribute as intent and all objects as extent), we can focus on the next level down for example on countries with a low life expectancy ([life expectancy:low]), to find that there are 20 subconcepts, including countries which also have a low population (14 of them). At the third level, we find only 5 possible other concepts, which in addition to low life expectancy and population, also have:"
},
{
"code": null,
"e": 6490,
"s": 6471,
"text": "a low nominal GDP,"
},
{
"code": null,
"e": 6519,
"s": 6490,
"text": "a high total fertility rate,"
},
{
"code": null,
"e": 6543,
"s": 6519,
"text": "a medium mains voltage,"
},
{
"code": null,
"e": 6572,
"s": 6543,
"text": "a low PPP GDP per capita, or"
},
{
"code": null,
"e": 6594,
"s": 6572,
"text": "a high inflation rate"
},
{
"code": null,
"e": 7060,
"s": 6594,
"text": "There could have been many other concepts, but that only those five are there, and that FCA is based on closed sets of attributes, mean that those other concepts simply did not exist in the data. In our list of countries, you cannot have a low life expectancy and population, and not be in one of those 5 other categories too. The lattice goes deeper into subdividing this group of countries and provides a convenient way to explore the dataset. But can it do more?"
},
{
"code": null,
"e": 7620,
"s": 7060,
"text": "Other than providing a (rather enormous) navigation structure, the lattice once constructed can also be used to identify rules that apply in the data. The simple intuition here is that if a concept C’s intent includes attributes that are not in the intent of any of its parents (i.e. subsuming concept), then those attributes imply the ones of the parents. This is again due to the fact that the concepts are closed: If C’s own attributes (its proper intent) could appear without the ones of the parents, then they would have already shown up at levels above."
},
{
"code": null,
"e": 8402,
"s": 7620,
"text": "Unfortunately, that does not happen in our country dataset. We can, however, see when that almost happens. The support of a concept is the number of objects (countries) in its extent. For example, the support of [life expectancy: low, population: low] is 14, as seen above. If the support of a concept C is almost the same as the support of one of its parent concepts D, that must mean that the attributes of D’s intent almost imply the ones of C’s intent. In other words, if C has a support of 9 with the intent [a,b,c] and S, the subsuming concept, has a support of 10 with the intent [a,b], we can say that any object with attributes a and b also has c in 90% of the cases. We have an association rule stating that a and b imply c, with a confidence of 90% (and a support of 9)."
},
{
"code": null,
"e": 8573,
"s": 8402,
"text": "That, our country dataset has a lot of. Only focusing on rules with a confidence higher than 95% and a support of at least 25, we can find for example the following rule:"
},
{
"code": null,
"e": 8668,
"s": 8573,
"text": "inflation rate:high,total fertility rate:high -> life expectancy:low s:25 c:0.9615384615384616"
},
{
"code": null,
"e": 8860,
"s": 8668,
"text": "which states that, with 96.1% confidence, countries with a high inflation rate and a high fertility rate also have a low life expectancy, and that this applies to 25 countries in our dataset."
}
] |
How to validate XML response in Rest Assured? | We can validate XML response in Rest Assured. For obtaining an XML response, we have to pass the parameter ContentType.XML to the accept method. We shall first send a GET request via Postman on a mock API URL.
Using Rest Assured, we shall validate its XML Response containing the name of the subjects Rest Assured, Postman, and their prices 10 and 6 respectively.
In the above XML Response, we shall obtain the values of the name and price tags by traversing the paths - courses.subject.name and courses.subject.price respectively.
We shall perform the assertion with the help of the Hamcrest framework which uses the Matcher class for assertion. To work with Hamcrest we have to add the Hamcrest Core dependency in the pom.xml in our Maven project. The link to this dependency is available in the below link −
https://mvnrepository.com/artifact/org.hamcrest/hamcrest-core
Code Implementation
import org.hamcrest.Matchers;
import org.testng.annotations.Test;
import static io.restassured.RestAssured.*;
import io.restassured.RestAssured;
import io.restassured.http.ContentType;
public class NewTest {
@Test
void validateXMLResponse() {
//base URI with Rest Assured class
RestAssured.baseURI = "https://run.mocky.io/v3";
//accept XML CONTENT
given().accept(ContentType.XML)
//GET request .when().get("/55889581-
da52-4383-840e-bdf6dde19252")
//validate XML body
.then().assertThat()
//validate subject lists
.body("courses.subject.name", Matchers.hasItems
("Rest Assured", "Postman"))
.and().assertThat()
//validate price lists
.body("courses.subject.price", Matchers.hasItems("10", "6"));
}
} | [
{
"code": null,
"e": 1272,
"s": 1062,
"text": "We can validate XML response in Rest Assured. For obtaining an XML response, we have to pass the parameter ContentType.XML to the accept method. We shall first send a GET request via Postman on a mock API URL."
},
{
"code": null,
"e": 1426,
"s": 1272,
"text": "Using Rest Assured, we shall validate its XML Response containing the name of the subjects Rest Assured, Postman, and their prices 10 and 6 respectively."
},
{
"code": null,
"e": 1594,
"s": 1426,
"text": "In the above XML Response, we shall obtain the values of the name and price tags by traversing the paths - courses.subject.name and courses.subject.price respectively."
},
{
"code": null,
"e": 1873,
"s": 1594,
"text": "We shall perform the assertion with the help of the Hamcrest framework which uses the Matcher class for assertion. To work with Hamcrest we have to add the Hamcrest Core dependency in the pom.xml in our Maven project. The link to this dependency is available in the below link −"
},
{
"code": null,
"e": 1935,
"s": 1873,
"text": "https://mvnrepository.com/artifact/org.hamcrest/hamcrest-core"
},
{
"code": null,
"e": 1955,
"s": 1935,
"text": "Code Implementation"
},
{
"code": null,
"e": 2754,
"s": 1955,
"text": "import org.hamcrest.Matchers;\nimport org.testng.annotations.Test;\nimport static io.restassured.RestAssured.*;\nimport io.restassured.RestAssured;\nimport io.restassured.http.ContentType;\npublic class NewTest {\n @Test\n void validateXMLResponse() {\n\n //base URI with Rest Assured class\n RestAssured.baseURI = \"https://run.mocky.io/v3\";\n\n //accept XML CONTENT\n given().accept(ContentType.XML)\n\n //GET request .when().get(\"/55889581-\n da52-4383-840e-bdf6dde19252\")\n\n //validate XML body\n .then().assertThat()\n\n //validate subject lists\n .body(\"courses.subject.name\", Matchers.hasItems\n (\"Rest Assured\", \"Postman\"))\n .and().assertThat()\n\n //validate price lists\n .body(\"courses.subject.price\", Matchers.hasItems(\"10\", \"6\"));\n }\n}"
}
] |
What is the use of set.seed in R? | The set.seed helps to create the replicate of the random generation. If the name of the object changes that does not mean the replication will be changed but if we change the position then it will. Here, in the below example x4 in the first random generation and the x_4 in the second random generation with the same set.seed are same but x4 and x4 in both are different.
Live Demo
set.seed(101)
x1<−rnorm(50)
x1
[1] −0.3260365 0.5524619 −0.6749438 0.2143595 0.3107692 1.1739663
[7] 0.6187899 −0.1127343 0.9170283 −0.2232594 0.5264481 −0.7948444
[13] 1.4277555 −1.4668197 −0.2366834 −0.1933380 −0.8497547 0.0584655
[19] −0.8176704 −2.0503078 −0.1637557 0.7085221 −0.2679805 −1.4639218
[25] 0.7444358 −1.4103902 0.4670676 −0.1193201 0.4672390 0.4981356
[31] 0.8949372 0.2791520 1.0078658 −2.0731065 1.1898534 −0.7243742
[37] 0.1679838 0.9203352 −1.6716048 0.4484691 0.4824588 0.7582138
[43] −2.3193274 −0.4595048 −1.1053837 0.4029283 0.5689349 −0.7060833
[49] −0.2900906 −1.4838781
Live Demo
x2<−rnorm(50)
x2
[1] −1.150255281 −0.274471162 0.577901003 −1.396902647 0.749057716
[6] −1.051186697 0.165380871 1.129809120 1.173722464 −0.427863232
[11] −0.259802108 −1.411173044 −0.641357554 0.112457509 0.422604331
[16] 0.386835291 −0.687798326 0.148902489 −0.057649748 −0.074823365
[21] 1.509897438 1.619937008 1.153158167 −0.077603595 −1.818934501
[26] −1.037444583 0.302492246 −1.277946167 0.138339048 −0.050984124
[31] 1.852147575 1.111675270 −0.511375322 −0.543881104 −1.728927284
[36] 0.470749539 0.005387122 1.348045786 0.724096713 1.552549165
[41] 1.325469832 −0.034265092 −0.361013398 −0.720165422 0.282014933
[46] −0.790525664 −0.444904551 1.364993169 0.497454338 −0.814396476
Live Demo
x3<−rnorm(50)
x3
[1] 0.26806584 −0.59220831 2.13348636 1.17274867 0.74676099 −0.23050869
[7] 0.08777170 −2.18373968 −0.46663159 1.68595984 −0.56792093 −0.04674302
[13] −0.15698059 1.60224244 0.76865367 −0.77162936 −0.63068198 −0.83028060
[19] −0.59111274 0.98108541 −0.66160527 −0.77241769 −2.01847347 −0.53358542
[25] 0.43472833 −0.77116734 −0.75394082 −0.29935782 1.66396643 −1.24432984
[31] −0.78313437 0.24483056 −0.14388717 −1.60863142 0.95157997 −1.81913169
[37] 1.78367171 1.88713936 1.49071878 −0.38059952 −0.90937501 −0.33809411
[43] −1.41188352 0.21754289 0.67012617 −0.28785938 0.46930350 −0.47007143
[49] −0.23926592 −0.44746249
Live Demo
x4<−rnorm(50)
x4
[1] −0.618829657 0.252963051 −0.753368175 0.732276853 −0.402586713
[6] −2.823000119 0.462973827 2.132869726 −0.270486687 0.248525349
[11] 0.038116475 0.394068950 −1.504085198 −1.586890794 −0.927118077
[16] 0.776197040 −0.780684440 −1.278567024 −0.001428128 −1.850978124
[21] 0.451505335 −0.432947055 0.713602899 0.960695470 0.381535210
[26] 1.218072798 −0.017137261 −0.038209493 1.243734395 −0.955858745
[31] 0.915425235 −0.939337976 0.112124820 0.553012619 0.531741963
[36] −0.873762389 −0.186849273 −0.213710488 −0.204011273 1.719709241
[41] 0.202033482 0.512655778 1.452400012 0.363865465 −0.875848946
[46] −0.014560733 −0.724493165 1.969370094 −0.536402427 −0.026232340
Live Demo
set.seed(101)
x1<−rnorm(50)
x1
[1] −0.3260365 0.5524619 −0.6749438 0.2143595 0.3107692 1.1739663
[7] 0.6187899 −0.1127343 0.9170283 −0.2232594 0.5264481 −0.7948444
[13] 1.4277555 −1.4668197 −0.2366834 −0.1933380 −0.8497547 0.0584655
[19] −0.8176704 −2.0503078 −0.1637557 0.7085221 −0.2679805 −1.4639218
[25] 0.7444358 −1.4103902 0.4670676 −0.1193201 0.4672390 0.4981356
[31] 0.8949372 0.2791520 1.0078658 −2.0731065 1.1898534 −0.7243742
[37] 0.1679838 0.9203352 −1.6716048 0.4484691 0.4824588 0.7582138
[43] −2.3193274 −0.4595048 −1.1053837 0.4029283 0.5689349 −0.7060833
[49] −0.2900906 −1.4838781
Live Demo
x2<−rnorm(50)
x2
[1] −1.150255281 −0.274471162 0.577901003 −1.396902647 0.749057716
[6] −1.051186697 0.165380871 1.129809120 1.173722464 −0.427863232
[11] −0.259802108 −1.411173044 −0.641357554 0.112457509 0.422604331
[16] 0.386835291 −0.687798326 0.148902489 −0.057649748 −0.074823365
[21] 1.509897438 1.619937008 1.153158167 −0.077603595 −1.818934501
[26] −1.037444583 0.302492246 −1.277946167 0.138339048 −0.050984124
[31] 1.852147575 1.111675270 −0.511375322 −0.543881104 −1.728927284
[36] 0.470749539 0.005387122 1.348045786 0.724096713 1.552549165
[41] 1.325469832 −0.034265092 −0.361013398 −0.720165422 0.282014933
[46] −0.790525664 −0.444904551 1.364993169 0.497454338 −0.814396476
Live Demo
x3<−rnorm(50)
x3
[1] 0.26806584 −0.59220831 2.13348636 1.17274867 0.74676099 −0.23050869
[7] 0.08777170 −2.18373968 −0.46663159 1.68595984 −0.56792093 −0.04674302
[13] −0.15698059 1.60224244 0.76865367 −0.77162936 −0.63068198 −0.83028060
[19] −0.59111274 0.98108541 −0.66160527 −0.77241769 −2.01847347 −0.53358542
[25] 0.43472833 −0.77116734 −0.75394082 −0.29935782 1.66396643 −1.24432984
[31] −0.78313437 0.24483056 −0.14388717 −1.60863142 0.95157997 −1.81913169
[37] 1.78367171 1.88713936 1.49071878 −0.38059952 −0.90937501 −0.33809411
[43] −1.41188352 0.21754289 0.67012617 −0.28785938 0.46930350 −0.47007143
[49] −0.23926592 −0.44746249
Live Demo
x_4<−rnorm(50)
x_4
[1] −0.618829657 0.252963051 −0.753368175 0.732276853 −0.402586713
[6] −2.823000119 0.462973827 2.132869726 −0.270486687 0.248525349
[11] 0.038116475 0.394068950 −1.504085198 −1.586890794 −0.927118077
[16] 0.776197040 −0.780684440 −1.278567024 −0.001428128 −1.850978124
[21] 0.451505335 −0.432947055 0.713602899 0.960695470 0.381535210
[26] 1.218072798 −0.017137261 −0.038209493 1.243734395 −0.955858745
[31] 0.915425235 −0.939337976 0.112124820 0.553012619 0.531741963
[36] −0.873762389 −0.186849273 −0.213710488 −0.204011273 1.719709241
[41] 0.202033482 0.512655778 1.452400012 0.363865465 −0.875848946
[46] −0.014560733 −0.724493165 1.969370094 −0.536402427 −0.026232340
Live Demo
x4<−rnorm(50)
x4
[1] −0.16403235 −1.38327506 0.42351126 −0.79048891 1.20992485 0.89451677
[7] −0.10119854 0.29712257 0.19729772 −0.15698374 1.53657101 −2.16766968
[13] 0.59844815 0.04311236 1.29502719 0.70630294 0.34554508 −0.07989665
[19] 0.45480755 1.27625237 1.26483765 0.26925353 −0.12054409 0.79527135
[25] −0.51402764 −0.40659347 1.21971898 0.08371137 0.58990215 −0.51741928
[31] 0.76946349 0.80196974 −0.69686014 1.17785318 0.58584526 −0.46689388
[37] 0.38564964 −0.53460558 1.05666840 −0.20609327 0.60701224 −0.54806386
[43] −2.09997633 0.25081276 −0.05494528 −0.65972781 −1.45585738 0.02372943
[49] 0.54790809 −0.80890140 | [
{
"code": null,
"e": 1434,
"s": 1062,
"text": "The set.seed helps to create the replicate of the random generation. If the name of the object changes that does not mean the replication will be changed but if we change the position then it will. Here, in the below example x4 in the first random generation and the x_4 in the second random generation with the same set.seed are same but x4 and x4 in both are different."
},
{
"code": null,
"e": 1445,
"s": 1434,
"text": " Live Demo"
},
{
"code": null,
"e": 1476,
"s": 1445,
"text": "set.seed(101)\nx1<−rnorm(50)\nx1"
},
{
"code": null,
"e": 2044,
"s": 1476,
"text": "[1] −0.3260365 0.5524619 −0.6749438 0.2143595 0.3107692 1.1739663\n[7] 0.6187899 −0.1127343 0.9170283 −0.2232594 0.5264481 −0.7948444\n[13] 1.4277555 −1.4668197 −0.2366834 −0.1933380 −0.8497547 0.0584655\n[19] −0.8176704 −2.0503078 −0.1637557 0.7085221 −0.2679805 −1.4639218\n[25] 0.7444358 −1.4103902 0.4670676 −0.1193201 0.4672390 0.4981356\n[31] 0.8949372 0.2791520 1.0078658 −2.0731065 1.1898534 −0.7243742\n[37] 0.1679838 0.9203352 −1.6716048 0.4484691 0.4824588 0.7582138\n[43] −2.3193274 −0.4595048 −1.1053837 0.4029283 0.5689349 −0.7060833\n[49] −0.2900906 −1.4838781"
},
{
"code": null,
"e": 2055,
"s": 2044,
"text": " Live Demo"
},
{
"code": null,
"e": 2072,
"s": 2055,
"text": "x2<−rnorm(50)\nx2"
},
{
"code": null,
"e": 2745,
"s": 2072,
"text": "[1] −1.150255281 −0.274471162 0.577901003 −1.396902647 0.749057716\n[6] −1.051186697 0.165380871 1.129809120 1.173722464 −0.427863232\n[11] −0.259802108 −1.411173044 −0.641357554 0.112457509 0.422604331\n[16] 0.386835291 −0.687798326 0.148902489 −0.057649748 −0.074823365\n[21] 1.509897438 1.619937008 1.153158167 −0.077603595 −1.818934501\n[26] −1.037444583 0.302492246 −1.277946167 0.138339048 −0.050984124\n[31] 1.852147575 1.111675270 −0.511375322 −0.543881104 −1.728927284\n[36] 0.470749539 0.005387122 1.348045786 0.724096713 1.552549165\n[41] 1.325469832 −0.034265092 −0.361013398 −0.720165422 0.282014933\n[46] −0.790525664 −0.444904551 1.364993169 0.497454338 −0.814396476"
},
{
"code": null,
"e": 2756,
"s": 2745,
"text": " Live Demo"
},
{
"code": null,
"e": 2773,
"s": 2756,
"text": "x3<−rnorm(50)\nx3"
},
{
"code": null,
"e": 3397,
"s": 2773,
"text": "[1] 0.26806584 −0.59220831 2.13348636 1.17274867 0.74676099 −0.23050869\n[7] 0.08777170 −2.18373968 −0.46663159 1.68595984 −0.56792093 −0.04674302\n[13] −0.15698059 1.60224244 0.76865367 −0.77162936 −0.63068198 −0.83028060\n[19] −0.59111274 0.98108541 −0.66160527 −0.77241769 −2.01847347 −0.53358542\n[25] 0.43472833 −0.77116734 −0.75394082 −0.29935782 1.66396643 −1.24432984\n[31] −0.78313437 0.24483056 −0.14388717 −1.60863142 0.95157997 −1.81913169\n[37] 1.78367171 1.88713936 1.49071878 −0.38059952 −0.90937501 −0.33809411\n[43] −1.41188352 0.21754289 0.67012617 −0.28785938 0.46930350 −0.47007143\n[49] −0.23926592 −0.44746249"
},
{
"code": null,
"e": 3408,
"s": 3397,
"text": " Live Demo"
},
{
"code": null,
"e": 3425,
"s": 3408,
"text": "x4<−rnorm(50)\nx4"
},
{
"code": null,
"e": 4099,
"s": 3425,
"text": "[1] −0.618829657 0.252963051 −0.753368175 0.732276853 −0.402586713\n[6] −2.823000119 0.462973827 2.132869726 −0.270486687 0.248525349\n[11] 0.038116475 0.394068950 −1.504085198 −1.586890794 −0.927118077\n[16] 0.776197040 −0.780684440 −1.278567024 −0.001428128 −1.850978124\n[21] 0.451505335 −0.432947055 0.713602899 0.960695470 0.381535210\n[26] 1.218072798 −0.017137261 −0.038209493 1.243734395 −0.955858745\n[31] 0.915425235 −0.939337976 0.112124820 0.553012619 0.531741963\n[36] −0.873762389 −0.186849273 −0.213710488 −0.204011273 1.719709241\n[41] 0.202033482 0.512655778 1.452400012 0.363865465 −0.875848946\n[46] −0.014560733 −0.724493165 1.969370094 −0.536402427 −0.026232340"
},
{
"code": null,
"e": 4110,
"s": 4099,
"text": " Live Demo"
},
{
"code": null,
"e": 4141,
"s": 4110,
"text": "set.seed(101)\nx1<−rnorm(50)\nx1"
},
{
"code": null,
"e": 4709,
"s": 4141,
"text": "[1] −0.3260365 0.5524619 −0.6749438 0.2143595 0.3107692 1.1739663\n[7] 0.6187899 −0.1127343 0.9170283 −0.2232594 0.5264481 −0.7948444\n[13] 1.4277555 −1.4668197 −0.2366834 −0.1933380 −0.8497547 0.0584655\n[19] −0.8176704 −2.0503078 −0.1637557 0.7085221 −0.2679805 −1.4639218\n[25] 0.7444358 −1.4103902 0.4670676 −0.1193201 0.4672390 0.4981356\n[31] 0.8949372 0.2791520 1.0078658 −2.0731065 1.1898534 −0.7243742\n[37] 0.1679838 0.9203352 −1.6716048 0.4484691 0.4824588 0.7582138\n[43] −2.3193274 −0.4595048 −1.1053837 0.4029283 0.5689349 −0.7060833\n[49] −0.2900906 −1.4838781"
},
{
"code": null,
"e": 4720,
"s": 4709,
"text": " Live Demo"
},
{
"code": null,
"e": 4737,
"s": 4720,
"text": "x2<−rnorm(50)\nx2"
},
{
"code": null,
"e": 5410,
"s": 4737,
"text": "[1] −1.150255281 −0.274471162 0.577901003 −1.396902647 0.749057716\n[6] −1.051186697 0.165380871 1.129809120 1.173722464 −0.427863232\n[11] −0.259802108 −1.411173044 −0.641357554 0.112457509 0.422604331\n[16] 0.386835291 −0.687798326 0.148902489 −0.057649748 −0.074823365\n[21] 1.509897438 1.619937008 1.153158167 −0.077603595 −1.818934501\n[26] −1.037444583 0.302492246 −1.277946167 0.138339048 −0.050984124\n[31] 1.852147575 1.111675270 −0.511375322 −0.543881104 −1.728927284\n[36] 0.470749539 0.005387122 1.348045786 0.724096713 1.552549165\n[41] 1.325469832 −0.034265092 −0.361013398 −0.720165422 0.282014933\n[46] −0.790525664 −0.444904551 1.364993169 0.497454338 −0.814396476"
},
{
"code": null,
"e": 5421,
"s": 5410,
"text": " Live Demo"
},
{
"code": null,
"e": 5438,
"s": 5421,
"text": "x3<−rnorm(50)\nx3"
},
{
"code": null,
"e": 6062,
"s": 5438,
"text": "[1] 0.26806584 −0.59220831 2.13348636 1.17274867 0.74676099 −0.23050869\n[7] 0.08777170 −2.18373968 −0.46663159 1.68595984 −0.56792093 −0.04674302\n[13] −0.15698059 1.60224244 0.76865367 −0.77162936 −0.63068198 −0.83028060\n[19] −0.59111274 0.98108541 −0.66160527 −0.77241769 −2.01847347 −0.53358542\n[25] 0.43472833 −0.77116734 −0.75394082 −0.29935782 1.66396643 −1.24432984\n[31] −0.78313437 0.24483056 −0.14388717 −1.60863142 0.95157997 −1.81913169\n[37] 1.78367171 1.88713936 1.49071878 −0.38059952 −0.90937501 −0.33809411\n[43] −1.41188352 0.21754289 0.67012617 −0.28785938 0.46930350 −0.47007143\n[49] −0.23926592 −0.44746249"
},
{
"code": null,
"e": 6073,
"s": 6062,
"text": " Live Demo"
},
{
"code": null,
"e": 6092,
"s": 6073,
"text": "x_4<−rnorm(50)\nx_4"
},
{
"code": null,
"e": 6766,
"s": 6092,
"text": "[1] −0.618829657 0.252963051 −0.753368175 0.732276853 −0.402586713\n[6] −2.823000119 0.462973827 2.132869726 −0.270486687 0.248525349\n[11] 0.038116475 0.394068950 −1.504085198 −1.586890794 −0.927118077\n[16] 0.776197040 −0.780684440 −1.278567024 −0.001428128 −1.850978124\n[21] 0.451505335 −0.432947055 0.713602899 0.960695470 0.381535210\n[26] 1.218072798 −0.017137261 −0.038209493 1.243734395 −0.955858745\n[31] 0.915425235 −0.939337976 0.112124820 0.553012619 0.531741963\n[36] −0.873762389 −0.186849273 −0.213710488 −0.204011273 1.719709241\n[41] 0.202033482 0.512655778 1.452400012 0.363865465 −0.875848946\n[46] −0.014560733 −0.724493165 1.969370094 −0.536402427 −0.026232340"
},
{
"code": null,
"e": 6777,
"s": 6766,
"text": " Live Demo"
},
{
"code": null,
"e": 6794,
"s": 6777,
"text": "x4<−rnorm(50)\nx4"
},
{
"code": null,
"e": 7408,
"s": 6794,
"text": "[1] −0.16403235 −1.38327506 0.42351126 −0.79048891 1.20992485 0.89451677\n[7] −0.10119854 0.29712257 0.19729772 −0.15698374 1.53657101 −2.16766968\n[13] 0.59844815 0.04311236 1.29502719 0.70630294 0.34554508 −0.07989665\n[19] 0.45480755 1.27625237 1.26483765 0.26925353 −0.12054409 0.79527135\n[25] −0.51402764 −0.40659347 1.21971898 0.08371137 0.58990215 −0.51741928\n[31] 0.76946349 0.80196974 −0.69686014 1.17785318 0.58584526 −0.46689388\n[37] 0.38564964 −0.53460558 1.05666840 −0.20609327 0.60701224 −0.54806386\n[43] −2.09997633 0.25081276 −0.05494528 −0.65972781 −1.45585738 0.02372943\n[49] 0.54790809 −0.80890140"
}
] |
How to enable or disable the GPS programmatically on Kotlin? | This example demonstrates how to enable or disable the GPS programmatically on Kotlin.
Step 1 − Create a new project in Android Studio, go to File ? New Project and fill all required details to create a new project.
Step 2 &minsu; Add the following code to res/layout/activity_main.xml.
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerHorizontal="true"
android:layout_marginTop="50dp"
android:padding="8dp"
android:text="Tutorials Point"
android:textColor="@android:color/holo_green_dark"
android:textSize="48sp"
android:textStyle="bold" />
<Button
android:id="@+id/button"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerInParent="true"
android:layout_marginTop="70dp"
android:onClick="gpsStatus"
android:text="Click Here to Enable Disable GPS" />
<TextView
android:id="@+id/textView"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="@+id/button"
android:layout_centerInParent="true"
android:textColor="@android:color/holo_green_dark"
android:textSize="24sp"
android:textStyle="bold" />
</RelativeLayout>
Step 3 − Add the following code to src/MainActivity.kt
import android.content.Context
import android.content.Intent
import android.location.LocationManager
import android.os.Bundle
import android.provider.Settings
import android.view.View
import android.widget.TextView
import androidx.appcompat.app.AppCompatActivity
class MainActivity : AppCompatActivity() {
private lateinit var context: Context
var intent1: Intent? = null
lateinit var textView: TextView
private lateinit var locationManager: LocationManager
var gpsStatus = false
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
textView = findViewById(R.id.textView)
title = "KotlinApp"
context = applicationContext
checkGpsStatus()
}
private fun checkGpsStatus() {
locationManager = context.getSystemService(Context.LOCATION_SERVICE) as LocationManager
gpsStatus = locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER)
if (gpsStatus) {
textView.text = "GPS Is Enabled"
} else {
textView.text = "GPS Is Disabled"
}
}
fun gpsStatus(view: View) {
intent1 = Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS);
startActivity(intent1);
}
}
Step 4 − Add the following code to androidManifest.xml
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android" package="app.com.myapplication">
<application
android:allowBackup="true"
android:icon="@mipmap/ic_launcher"
android:label="@string/app_name"
android:roundIcon="@mipmap/ic_launcher_round"
android:supportsRtl="true"
android:theme="@style/AppTheme">
<activity android:name=".MainActivity">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
</manifest>
Let's try to run your application. I assume you have connected your actual Android Mobile device with your computer. To run the app from android studio, open one of your project's activity files and click the Run icon from the toolbar. Select your mobile device as an option and then check your mobile device which will display your default screen | [
{
"code": null,
"e": 1149,
"s": 1062,
"text": "This example demonstrates how to enable or disable the GPS programmatically on Kotlin."
},
{
"code": null,
"e": 1278,
"s": 1149,
"text": "Step 1 − Create a new project in Android Studio, go to File ? New Project and fill all required details to create a new project."
},
{
"code": null,
"e": 1349,
"s": 1278,
"text": "Step 2 &minsu; Add the following code to res/layout/activity_main.xml."
},
{
"code": null,
"e": 2698,
"s": 1349,
"text": "<?xml version=\"1.0\" encoding=\"utf-8\"?>\n<RelativeLayout xmlns:android=\"http://schemas.android.com/apk/res/android\" 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=\".MainActivity\">\n <TextView\n android:layout_width=\"wrap_content\"\n android:layout_height=\"wrap_content\"\n android:layout_centerHorizontal=\"true\"\n android:layout_marginTop=\"50dp\"\n android:padding=\"8dp\"\n android:text=\"Tutorials Point\"\n android:textColor=\"@android:color/holo_green_dark\"\n android:textSize=\"48sp\"\n android:textStyle=\"bold\" />\n <Button\n android:id=\"@+id/button\"\n android:layout_width=\"wrap_content\"\n android:layout_height=\"wrap_content\"\n android:layout_centerInParent=\"true\"\n android:layout_marginTop=\"70dp\"\n android:onClick=\"gpsStatus\"\n android:text=\"Click Here to Enable Disable GPS\" />\n <TextView\n android:id=\"@+id/textView\"\n android:layout_width=\"wrap_content\"\n android:layout_height=\"wrap_content\"\n android:layout_below=\"@+id/button\"\n android:layout_centerInParent=\"true\"\n android:textColor=\"@android:color/holo_green_dark\"\n android:textSize=\"24sp\"\n android:textStyle=\"bold\" />\n</RelativeLayout>"
},
{
"code": null,
"e": 2753,
"s": 2698,
"text": "Step 3 − Add the following code to src/MainActivity.kt"
},
{
"code": null,
"e": 4004,
"s": 2753,
"text": "import android.content.Context\nimport android.content.Intent\nimport android.location.LocationManager\nimport android.os.Bundle\nimport android.provider.Settings\nimport android.view.View\nimport android.widget.TextView\nimport androidx.appcompat.app.AppCompatActivity\nclass MainActivity : AppCompatActivity() {\n private lateinit var context: Context\n var intent1: Intent? = null\n lateinit var textView: TextView\n private lateinit var locationManager: LocationManager\n var gpsStatus = false\n override fun onCreate(savedInstanceState: Bundle?) {\n super.onCreate(savedInstanceState)\n setContentView(R.layout.activity_main)\n textView = findViewById(R.id.textView)\n title = \"KotlinApp\"\n context = applicationContext\n checkGpsStatus()\n }\n private fun checkGpsStatus() {\n locationManager = context.getSystemService(Context.LOCATION_SERVICE) as LocationManager\n gpsStatus = locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER)\n if (gpsStatus) {\n textView.text = \"GPS Is Enabled\"\n } else {\n textView.text = \"GPS Is Disabled\"\n }\n }\n fun gpsStatus(view: View) {\n intent1 = Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS);\n startActivity(intent1);\n }\n}"
},
{
"code": null,
"e": 4059,
"s": 4004,
"text": "Step 4 − Add the following code to androidManifest.xml"
},
{
"code": null,
"e": 4736,
"s": 4059,
"text": "<?xml version=\"1.0\" encoding=\"utf-8\"?>\n<manifest xmlns:android=\"http://schemas.android.com/apk/res/android\" package=\"app.com.myapplication\">\n <application\n android:allowBackup=\"true\"\n android:icon=\"@mipmap/ic_launcher\"\n android:label=\"@string/app_name\"\n android:roundIcon=\"@mipmap/ic_launcher_round\"\n android:supportsRtl=\"true\"\n android:theme=\"@style/AppTheme\">\n <activity android:name=\".MainActivity\">\n <intent-filter>\n <action android:name=\"android.intent.action.MAIN\" />\n <category android:name=\"android.intent.category.LAUNCHER\" />\n </intent-filter>\n </activity>\n </application>\n</manifest>"
},
{
"code": null,
"e": 5084,
"s": 4736,
"text": "Let's try to run your application. I assume you have connected your actual Android Mobile device with your computer. To run the app from android studio, open one of your project's activity files and click the Run icon from the toolbar. Select your mobile device as an option and then check your mobile device which will display your default screen"
}
] |
Selenium - Exception Handling | When we are developing tests, we should ensure that the scripts can continue their execution even if the test fails. An unexpected exception would be thrown if the worst case scenarios are not handled properly.
If an exception occurs due to an element not found or if the expected result doesn't match with actuals, we should catch that exception and end the test in a logical way rather than terminating the script abruptly.
The actual code should be placed in the try block and the action after exception should be placed in the catch block. Note that the 'finally' block executes regardless of whether the script had thrown an exception or NOT.
try {
//Perform Action
} catch(ExceptionType1 exp1) {
//Catch block 1
} catch(ExceptionType2 exp2) {
//Catch block 2
} catch(ExceptionType3 exp3) {
//Catch block 3
} finally {
//The finally block always executes.
}
If an element is not found (due to some reason), we should step out of the function smoothly. So we always need to have a try-catch block if we want to exit smoothly from a function.
public static WebElement lnk_percent_calc(WebDriver driver)throws Exception {
try {
element = driver.findElement(By.xpath(".//*[@id='menu']/div[4]/div[3]/a"));
return element;
} catch (Exception e1) {
// Add a message to your Log File to capture the error
Logger.error("Link is not found.");
// Take a screenshot which will be helpful for analysis.
File screenshot = ((TakesScreenshot)driver).getScreenshotAs(OutputType.FILE);
FileUtils.copyFile(screenshot, new File("D:\\framework\\screenshots.jpg"));
throw(e1);
}
}
46 Lectures
5.5 hours
Aditya Dua
296 Lectures
146 hours
Arun Motoori
411 Lectures
38.5 hours
In28Minutes Official
22 Lectures
7 hours
Arun Motoori
118 Lectures
17 hours
Arun Motoori
278 Lectures
38.5 hours
Lets Kode It
Print
Add Notes
Bookmark this page | [
{
"code": null,
"e": 2086,
"s": 1875,
"text": "When we are developing tests, we should ensure that the scripts can continue their execution even if the test fails. An unexpected exception would be thrown if the worst case scenarios are not handled properly."
},
{
"code": null,
"e": 2301,
"s": 2086,
"text": "If an exception occurs due to an element not found or if the expected result doesn't match with actuals, we should catch that exception and end the test in a logical way rather than terminating the script abruptly."
},
{
"code": null,
"e": 2523,
"s": 2301,
"text": "The actual code should be placed in the try block and the action after exception should be placed in the catch block. Note that the 'finally' block executes regardless of whether the script had thrown an exception or NOT."
},
{
"code": null,
"e": 2755,
"s": 2523,
"text": "try {\n //Perform Action\n} catch(ExceptionType1 exp1) {\n //Catch block 1\n} catch(ExceptionType2 exp2) {\n //Catch block 2\n} catch(ExceptionType3 exp3) {\n //Catch block 3 \n} finally {\n //The finally block always executes.\n}"
},
{
"code": null,
"e": 2938,
"s": 2755,
"text": "If an element is not found (due to some reason), we should step out of the function smoothly. So we always need to have a try-catch block if we want to exit smoothly from a function."
},
{
"code": null,
"e": 3521,
"s": 2938,
"text": "public static WebElement lnk_percent_calc(WebDriver driver)throws Exception {\n try {\n element = driver.findElement(By.xpath(\".//*[@id='menu']/div[4]/div[3]/a\")); \n return element;\n } catch (Exception e1) {\n // Add a message to your Log File to capture the error\n Logger.error(\"Link is not found.\");\n \n // Take a screenshot which will be helpful for analysis.\n File screenshot = ((TakesScreenshot)driver).getScreenshotAs(OutputType.FILE);\n FileUtils.copyFile(screenshot, new File(\"D:\\\\framework\\\\screenshots.jpg\"));\n throw(e1);\n }\n}"
},
{
"code": null,
"e": 3556,
"s": 3521,
"text": "\n 46 Lectures \n 5.5 hours \n"
},
{
"code": null,
"e": 3568,
"s": 3556,
"text": " Aditya Dua"
},
{
"code": null,
"e": 3604,
"s": 3568,
"text": "\n 296 Lectures \n 146 hours \n"
},
{
"code": null,
"e": 3618,
"s": 3604,
"text": " Arun Motoori"
},
{
"code": null,
"e": 3655,
"s": 3618,
"text": "\n 411 Lectures \n 38.5 hours \n"
},
{
"code": null,
"e": 3677,
"s": 3655,
"text": " In28Minutes Official"
},
{
"code": null,
"e": 3710,
"s": 3677,
"text": "\n 22 Lectures \n 7 hours \n"
},
{
"code": null,
"e": 3724,
"s": 3710,
"text": " Arun Motoori"
},
{
"code": null,
"e": 3759,
"s": 3724,
"text": "\n 118 Lectures \n 17 hours \n"
},
{
"code": null,
"e": 3773,
"s": 3759,
"text": " Arun Motoori"
},
{
"code": null,
"e": 3810,
"s": 3773,
"text": "\n 278 Lectures \n 38.5 hours \n"
},
{
"code": null,
"e": 3824,
"s": 3810,
"text": " Lets Kode It"
},
{
"code": null,
"e": 3831,
"s": 3824,
"text": " Print"
},
{
"code": null,
"e": 3842,
"s": 3831,
"text": " Add Notes"
}
] |
numpy.select() function | Python | 22 Apr, 2020
numpy.select()() function return an array drawn from elements in choicelist, depending on conditions.
Syntax : numpy.select(condlist, choicelist, default = 0)Parameters :condlist : [list of bool ndarrays] It determine from which array in choicelist the output elements are taken. When multiple conditions are satisfied, the first one encountered in condlist is used.choicelist : [list of ndarrays] The list of arrays from which the output elements are taken. It has to be of the same length as condlist.default : [scalar, optional] The element inserted in output when all conditions evaluate to False.Return : [ndarray] An array drawn from elements in choicelist, depending on conditions.
Code #1 :
# Python program explaining# numpy.select() function # importing numpy as geek import numpy as geek arr = geek.arange(8) condlist = [arr<3, arr>4]choicelist = [arr, arr**3] gfg = geek.select(condlist, choicelist) print (gfg)
Output :
[ 0, 1, 2, 0, 0, 125, 216, 343]
Code #2 :
# Python program explaining# numpy.select() function # importing numpy as geek import numpy as geek arr = geek.arange(8) condlist = [arr<4, arr>6]choicelist = [arr, arr**2] gfg = geek.select(condlist, choicelist) print (gfg)
Output :
[ 0, 1, 2, 3, 0, 0, 0, 49]
Python numpy-arrayManipulation
Python-numpy
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Python Dictionary
Enumerate() in Python
Read a file line by line in Python
How to Install PIP on Windows ?
*args and **kwargs in Python
Python Classes and Objects
Iterate over a list in Python
Python OOPs Concepts
Introduction To PYTHON
Convert integer to string in Python | [
{
"code": null,
"e": 28,
"s": 0,
"text": "\n22 Apr, 2020"
},
{
"code": null,
"e": 130,
"s": 28,
"text": "numpy.select()() function return an array drawn from elements in choicelist, depending on conditions."
},
{
"code": null,
"e": 717,
"s": 130,
"text": "Syntax : numpy.select(condlist, choicelist, default = 0)Parameters :condlist : [list of bool ndarrays] It determine from which array in choicelist the output elements are taken. When multiple conditions are satisfied, the first one encountered in condlist is used.choicelist : [list of ndarrays] The list of arrays from which the output elements are taken. It has to be of the same length as condlist.default : [scalar, optional] The element inserted in output when all conditions evaluate to False.Return : [ndarray] An array drawn from elements in choicelist, depending on conditions."
},
{
"code": null,
"e": 727,
"s": 717,
"text": "Code #1 :"
},
{
"code": "# Python program explaining# numpy.select() function # importing numpy as geek import numpy as geek arr = geek.arange(8) condlist = [arr<3, arr>4]choicelist = [arr, arr**3] gfg = geek.select(condlist, choicelist) print (gfg)",
"e": 957,
"s": 727,
"text": null
},
{
"code": null,
"e": 966,
"s": 957,
"text": "Output :"
},
{
"code": null,
"e": 1000,
"s": 966,
"text": "[ 0, 1, 2, 0, 0, 125, 216, 343]\n"
},
{
"code": null,
"e": 1011,
"s": 1000,
"text": " Code #2 :"
},
{
"code": "# Python program explaining# numpy.select() function # importing numpy as geek import numpy as geek arr = geek.arange(8) condlist = [arr<4, arr>6]choicelist = [arr, arr**2] gfg = geek.select(condlist, choicelist) print (gfg)",
"e": 1241,
"s": 1011,
"text": null
},
{
"code": null,
"e": 1250,
"s": 1241,
"text": "Output :"
},
{
"code": null,
"e": 1278,
"s": 1250,
"text": "[ 0, 1, 2, 3, 0, 0, 0, 49]\n"
},
{
"code": null,
"e": 1309,
"s": 1278,
"text": "Python numpy-arrayManipulation"
},
{
"code": null,
"e": 1322,
"s": 1309,
"text": "Python-numpy"
},
{
"code": null,
"e": 1329,
"s": 1322,
"text": "Python"
},
{
"code": null,
"e": 1427,
"s": 1329,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 1445,
"s": 1427,
"text": "Python Dictionary"
},
{
"code": null,
"e": 1467,
"s": 1445,
"text": "Enumerate() in Python"
},
{
"code": null,
"e": 1502,
"s": 1467,
"text": "Read a file line by line in Python"
},
{
"code": null,
"e": 1534,
"s": 1502,
"text": "How to Install PIP on Windows ?"
},
{
"code": null,
"e": 1563,
"s": 1534,
"text": "*args and **kwargs in Python"
},
{
"code": null,
"e": 1590,
"s": 1563,
"text": "Python Classes and Objects"
},
{
"code": null,
"e": 1620,
"s": 1590,
"text": "Iterate over a list in Python"
},
{
"code": null,
"e": 1641,
"s": 1620,
"text": "Python OOPs Concepts"
},
{
"code": null,
"e": 1664,
"s": 1641,
"text": "Introduction To PYTHON"
}
] |
Fill an array with specific values in Julia | Array fill() method | 27 Jan, 2022
The fill() is an inbuilt function in julia which is used to return an array of specified dimensions filled with a specific value passed to it as parameter.
Syntax: fill(Value, Dimension)Parameters:
Value: To be filled in the array
Dimension: Required size of the array
Returns: It returns an array of nXn dimension with each element as the specified value.
Example:
Python
# Julia program to illustrate# the use of Array fill() method # Creating a 1D array of size 4# with each element filled with value 5A = fill(5, 4)println(A) # Creating a 2D array of size 2X3# with each element filled with value 5B = fill(5, (2, 3))println(B) # Creating a 3D array of size 2X2X2# with each element filled with value 5C = fill(5, (2, 2, 2))println(C)
Output:
fill!() method works exactly like fill() method i.e. it fills an array with a specific value passed to it as argument, but the only difference is that, fill!() method takes an existing array as argument and fills it with a new specified value. While the fill() method takes array dimensions and creates a new array of its own.
Syntax: fill!(Array, Value)Parameters:
Array: It is the array of specified dimension.
Value: It is the value to be filled in the array.
Returns: It returns the array passed to it as argument with the specified value filled at each index.
Example: Below code is using one dimension array of 3 elements.
Python
# Julia program to illustrate# the use of Array fill() method # Creating a 1D array of size 5Array1 = [1, 2, 3, 4, 5] # Filling array with fill!()Array1 = fill!(Array1, 10)println(Array1) # Creating a 2D array of size 2X2Array2 = [1 2; 3 4]Array2 = fill!(Array2, 10)println(Array2) # Creating a 3D array of size 2X2X2Array3 = cat([1 2; 3 4], [5, 6; 7 8], dims=3)Array3 = fill!(Array3, 10)println(Array3)
Output:
clintra
julia-array
Julia
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Vectors in Julia
Getting rounded value of a number in Julia - round() Method
Manipulating matrices in Julia
Reshaping array dimensions in Julia | Array reshape() Method
Storing Output on a File in Julia
Exception handling in Julia
Formatting of Strings in Julia
Creating array with repeated elements in Julia - repeat() Method
Get array dimensions and size of a dimension in Julia - size() Method
Get number of elements of array in Julia - length() Method | [
{
"code": null,
"e": 28,
"s": 0,
"text": "\n27 Jan, 2022"
},
{
"code": null,
"e": 185,
"s": 28,
"text": "The fill() is an inbuilt function in julia which is used to return an array of specified dimensions filled with a specific value passed to it as parameter. "
},
{
"code": null,
"e": 229,
"s": 185,
"text": "Syntax: fill(Value, Dimension)Parameters: "
},
{
"code": null,
"e": 262,
"s": 229,
"text": "Value: To be filled in the array"
},
{
"code": null,
"e": 300,
"s": 262,
"text": "Dimension: Required size of the array"
},
{
"code": null,
"e": 390,
"s": 300,
"text": "Returns: It returns an array of nXn dimension with each element as the specified value. "
},
{
"code": null,
"e": 401,
"s": 390,
"text": "Example: "
},
{
"code": null,
"e": 408,
"s": 401,
"text": "Python"
},
{
"code": "# Julia program to illustrate# the use of Array fill() method # Creating a 1D array of size 4# with each element filled with value 5A = fill(5, 4)println(A) # Creating a 2D array of size 2X3# with each element filled with value 5B = fill(5, (2, 3))println(B) # Creating a 3D array of size 2X2X2# with each element filled with value 5C = fill(5, (2, 2, 2))println(C)",
"e": 774,
"s": 408,
"text": null
},
{
"code": null,
"e": 784,
"s": 774,
"text": "Output: "
},
{
"code": null,
"e": 1115,
"s": 786,
"text": "fill!() method works exactly like fill() method i.e. it fills an array with a specific value passed to it as argument, but the only difference is that, fill!() method takes an existing array as argument and fills it with a new specified value. While the fill() method takes array dimensions and creates a new array of its own. "
},
{
"code": null,
"e": 1156,
"s": 1115,
"text": "Syntax: fill!(Array, Value)Parameters: "
},
{
"code": null,
"e": 1203,
"s": 1156,
"text": "Array: It is the array of specified dimension."
},
{
"code": null,
"e": 1253,
"s": 1203,
"text": "Value: It is the value to be filled in the array."
},
{
"code": null,
"e": 1357,
"s": 1253,
"text": "Returns: It returns the array passed to it as argument with the specified value filled at each index. "
},
{
"code": null,
"e": 1423,
"s": 1357,
"text": "Example: Below code is using one dimension array of 3 elements. "
},
{
"code": null,
"e": 1430,
"s": 1423,
"text": "Python"
},
{
"code": "# Julia program to illustrate# the use of Array fill() method # Creating a 1D array of size 5Array1 = [1, 2, 3, 4, 5] # Filling array with fill!()Array1 = fill!(Array1, 10)println(Array1) # Creating a 2D array of size 2X2Array2 = [1 2; 3 4]Array2 = fill!(Array2, 10)println(Array2) # Creating a 3D array of size 2X2X2Array3 = cat([1 2; 3 4], [5, 6; 7 8], dims=3)Array3 = fill!(Array3, 10)println(Array3)",
"e": 1834,
"s": 1430,
"text": null
},
{
"code": null,
"e": 1844,
"s": 1834,
"text": "Output: "
},
{
"code": null,
"e": 1854,
"s": 1846,
"text": "clintra"
},
{
"code": null,
"e": 1866,
"s": 1854,
"text": "julia-array"
},
{
"code": null,
"e": 1872,
"s": 1866,
"text": "Julia"
},
{
"code": null,
"e": 1970,
"s": 1872,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 1987,
"s": 1970,
"text": "Vectors in Julia"
},
{
"code": null,
"e": 2047,
"s": 1987,
"text": "Getting rounded value of a number in Julia - round() Method"
},
{
"code": null,
"e": 2078,
"s": 2047,
"text": "Manipulating matrices in Julia"
},
{
"code": null,
"e": 2139,
"s": 2078,
"text": "Reshaping array dimensions in Julia | Array reshape() Method"
},
{
"code": null,
"e": 2173,
"s": 2139,
"text": "Storing Output on a File in Julia"
},
{
"code": null,
"e": 2201,
"s": 2173,
"text": "Exception handling in Julia"
},
{
"code": null,
"e": 2232,
"s": 2201,
"text": "Formatting of Strings in Julia"
},
{
"code": null,
"e": 2297,
"s": 2232,
"text": "Creating array with repeated elements in Julia - repeat() Method"
},
{
"code": null,
"e": 2367,
"s": 2297,
"text": "Get array dimensions and size of a dimension in Julia - size() Method"
}
] |
Compute Variance and Standard Deviation of a value in R Programming – var() and sd() Function | 26 May, 2020
var() function in R Language computes the sample variance of a vector. It is the measure of how much value is away from the mean value.
Syntax: var(x)
Parameters:x : numeric vector
Example 1: Computing variance of a vector
# R program to illustrate# variance of vector # Create example vectorx <- c(1, 2, 3, 4, 5, 6, 7) # Apply var function in R var(x) print(x)
Output:
4.667
Here in the above code, we took an example vector “x1” and calculated its variance.
sd() function is used to compute the standard deviation of given values in R. It is the square root of its variance.
Syntax: sd(x)
Parameters:
x: numeric vector
Example 1: Computing standard deviation of a vector
# R program to illustrate# standard deviation of vector # Create example vectorx2 <- c(1, 2, 3, 4, 5, 6, 7) # Compare with sd functionsd(x2) print(x2)
Output: 2.200
Here in the above code, we took an example vector “x2” and calculated its standard deviation.
R-Functions
Programming Language
R Language
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here. | [
{
"code": null,
"e": 52,
"s": 24,
"text": "\n26 May, 2020"
},
{
"code": null,
"e": 188,
"s": 52,
"text": "var() function in R Language computes the sample variance of a vector. It is the measure of how much value is away from the mean value."
},
{
"code": null,
"e": 203,
"s": 188,
"text": "Syntax: var(x)"
},
{
"code": null,
"e": 233,
"s": 203,
"text": "Parameters:x : numeric vector"
},
{
"code": null,
"e": 275,
"s": 233,
"text": "Example 1: Computing variance of a vector"
},
{
"code": "# R program to illustrate# variance of vector # Create example vectorx <- c(1, 2, 3, 4, 5, 6, 7) # Apply var function in R var(x) print(x)",
"e": 443,
"s": 275,
"text": null
},
{
"code": null,
"e": 451,
"s": 443,
"text": "Output:"
},
{
"code": null,
"e": 458,
"s": 451,
"text": " 4.667"
},
{
"code": null,
"e": 542,
"s": 458,
"text": "Here in the above code, we took an example vector “x1” and calculated its variance."
},
{
"code": null,
"e": 659,
"s": 542,
"text": "sd() function is used to compute the standard deviation of given values in R. It is the square root of its variance."
},
{
"code": null,
"e": 705,
"s": 659,
"text": "Syntax: sd(x)\n\nParameters:\nx: numeric vector\n"
},
{
"code": null,
"e": 757,
"s": 705,
"text": "Example 1: Computing standard deviation of a vector"
},
{
"code": "# R program to illustrate# standard deviation of vector # Create example vectorx2 <- c(1, 2, 3, 4, 5, 6, 7) # Compare with sd functionsd(x2) print(x2)",
"e": 938,
"s": 757,
"text": null
},
{
"code": null,
"e": 952,
"s": 938,
"text": "Output: 2.200"
},
{
"code": null,
"e": 1046,
"s": 952,
"text": "Here in the above code, we took an example vector “x2” and calculated its standard deviation."
},
{
"code": null,
"e": 1058,
"s": 1046,
"text": "R-Functions"
},
{
"code": null,
"e": 1079,
"s": 1058,
"text": "Programming Language"
},
{
"code": null,
"e": 1090,
"s": 1079,
"text": "R Language"
}
] |
React-Bootstrap Tables Component | 23 Sep, 2021
React-Bootstrap is a front-end framework that was designed keeping react in mind. Bootstrap was re-built and revamped for React, hence it is known as React-Bootstrap.
Tables in react-bootstrap come with predefined style classes which are both responsive and reliable.
Table props:
bordered: Adds borders on all sides of the tables and cells.
borderless: Removes borders on all sides including table header.
variant: It is used to invert the colors of the table from dark to light and vice versa.
size: It is used to set the size of the table. When we set it as ‘sm’ the cell padding is reduced by half.
bsPrefix: It is an escape hatch for working with strongly customized bootstrap CSS.
Creating React Application And Installing Module:
Step 1: Create a React application using the following command:
npx create-react-app foldername
Step 2: After creating your project folder i.e. foldername, move to it using the following command:
cd foldername
Step 3: After creating the ReactJS application, Install the required modules using the following command:
npm install react-bootstrap bootstrap
Step 4: Add the below line in index.js file:
import 'bootstrap/dist/css/bootstrap.css';
Project Structure: It will look like the following.
Example: Now write down the following code in the App.js file. Here, App is our default component where we have written our code.
Filename: App.js
Javascript
import React from 'react';import Table from 'react-bootstrap/Table' export default function TableExample() { return ( <> <h3>Default Variant Small Size Theme Table</h3> <Table stripped bordered hover size="sm"> <thead> <tr> <th width="170">Student Name</th> <th width="170">Reg.no</th> <th width="170">Course</th> <th width="870">City Name</th> <th width="1950">Percentage</th> </tr> </thead> <tbody> <tr> <td>Rakesh</td> <td>1123</td> <td>CSE</td> <td>Mumbai</td> <td>86.9%</td> </tr> <tr> <td>Jackson</td> <td>1124</td> <td>ECE</td> <td>Hyderabad</td> <td>72.4%</td> </tr> <tr> <td>Keshav</td> <td>1124</td> <td>CSE</td> <td>Chennai</td> <td>88%</td> </tr> <tr> <td>Neilesh Jain</td> <td>1125</td> <td>EEE</td> <td>Gwalior</td> <td>66.9%</td> </tr> <tr> <td>Akbar sheikh</td> <td>1126</td> <td>Mechanical</td> <td>Indore</td> <td>96.5%</td> </tr> <tr> <td>Sarita</td> <td>1127</td> <td>CSE</td> <td>Delhi</td> <td>96.9%</td> </tr> </tbody></Table> <h3>Dark Variant Small Size Table</h3> <Table stripped bordered hover variant="dark" size="sm"> <thead> <tr> <th width="170">Student Name</th> <th width="170">Reg.no</th> <th width="170">Course</th> <th width="870">City Name</th> <th width="1950">Percentage</th> </tr> </thead> <tbody> <tr> <td>Rakesh</td> <td>1123</td> <td>CSE</td> <td>Mumbai</td> <td>86.9%</td> </tr> <tr> <td>Jackson</td> <td>1124</td> <td>ECE</td> <td>Hyderabad</td> <td>72.4%</td> </tr> <tr> <td>Keshav</td> <td>1124</td> <td>CSE</td> <td>Chennai</td> <td>88%</td> </tr> <tr> <td>Neilesh Jain</td> <td>1125</td> <td>EEE</td> <td>Gwalior</td> <td>66.9%</td> </tr> <tr> <td>Akbar sheikh</td> <td>1126</td> <td>Mechanical</td> <td>Indore</td> <td>96.5%</td> </tr> <tr> <td>Sarita</td> <td>1127</td> <td>CSE</td> <td>Delhi</td> <td>96.9%</td> </tr> </tbody></Table> </> );}
Step to Run Application: Run the application using the following command from the root directory of the project:
npm start
Output: Now open your browser and go to http://localhost:3000/, you will see the following output.
Reference: https://react-bootstrap.netlify.app/components/table/#tables
akshaysingh98088
Picked
React-Bootstrap
ReactJS
Web Technologies
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here. | [
{
"code": null,
"e": 28,
"s": 0,
"text": "\n23 Sep, 2021"
},
{
"code": null,
"e": 196,
"s": 28,
"text": "React-Bootstrap is a front-end framework that was designed keeping react in mind. Bootstrap was re-built and revamped for React, hence it is known as React-Bootstrap. "
},
{
"code": null,
"e": 297,
"s": 196,
"text": "Tables in react-bootstrap come with predefined style classes which are both responsive and reliable."
},
{
"code": null,
"e": 310,
"s": 297,
"text": "Table props:"
},
{
"code": null,
"e": 371,
"s": 310,
"text": "bordered: Adds borders on all sides of the tables and cells."
},
{
"code": null,
"e": 436,
"s": 371,
"text": "borderless: Removes borders on all sides including table header."
},
{
"code": null,
"e": 525,
"s": 436,
"text": "variant: It is used to invert the colors of the table from dark to light and vice versa."
},
{
"code": null,
"e": 632,
"s": 525,
"text": "size: It is used to set the size of the table. When we set it as ‘sm’ the cell padding is reduced by half."
},
{
"code": null,
"e": 716,
"s": 632,
"text": "bsPrefix: It is an escape hatch for working with strongly customized bootstrap CSS."
},
{
"code": null,
"e": 766,
"s": 716,
"text": "Creating React Application And Installing Module:"
},
{
"code": null,
"e": 830,
"s": 766,
"text": "Step 1: Create a React application using the following command:"
},
{
"code": null,
"e": 862,
"s": 830,
"text": "npx create-react-app foldername"
},
{
"code": null,
"e": 962,
"s": 862,
"text": "Step 2: After creating your project folder i.e. foldername, move to it using the following command:"
},
{
"code": null,
"e": 976,
"s": 962,
"text": "cd foldername"
},
{
"code": null,
"e": 1082,
"s": 976,
"text": "Step 3: After creating the ReactJS application, Install the required modules using the following command:"
},
{
"code": null,
"e": 1120,
"s": 1082,
"text": "npm install react-bootstrap bootstrap"
},
{
"code": null,
"e": 1165,
"s": 1120,
"text": "Step 4: Add the below line in index.js file:"
},
{
"code": null,
"e": 1208,
"s": 1165,
"text": "import 'bootstrap/dist/css/bootstrap.css';"
},
{
"code": null,
"e": 1260,
"s": 1208,
"text": "Project Structure: It will look like the following."
},
{
"code": null,
"e": 1390,
"s": 1260,
"text": "Example: Now write down the following code in the App.js file. Here, App is our default component where we have written our code."
},
{
"code": null,
"e": 1407,
"s": 1390,
"text": "Filename: App.js"
},
{
"code": null,
"e": 1418,
"s": 1407,
"text": "Javascript"
},
{
"code": "import React from 'react';import Table from 'react-bootstrap/Table' export default function TableExample() { return ( <> <h3>Default Variant Small Size Theme Table</h3> <Table stripped bordered hover size=\"sm\"> <thead> <tr> <th width=\"170\">Student Name</th> <th width=\"170\">Reg.no</th> <th width=\"170\">Course</th> <th width=\"870\">City Name</th> <th width=\"1950\">Percentage</th> </tr> </thead> <tbody> <tr> <td>Rakesh</td> <td>1123</td> <td>CSE</td> <td>Mumbai</td> <td>86.9%</td> </tr> <tr> <td>Jackson</td> <td>1124</td> <td>ECE</td> <td>Hyderabad</td> <td>72.4%</td> </tr> <tr> <td>Keshav</td> <td>1124</td> <td>CSE</td> <td>Chennai</td> <td>88%</td> </tr> <tr> <td>Neilesh Jain</td> <td>1125</td> <td>EEE</td> <td>Gwalior</td> <td>66.9%</td> </tr> <tr> <td>Akbar sheikh</td> <td>1126</td> <td>Mechanical</td> <td>Indore</td> <td>96.5%</td> </tr> <tr> <td>Sarita</td> <td>1127</td> <td>CSE</td> <td>Delhi</td> <td>96.9%</td> </tr> </tbody></Table> <h3>Dark Variant Small Size Table</h3> <Table stripped bordered hover variant=\"dark\" size=\"sm\"> <thead> <tr> <th width=\"170\">Student Name</th> <th width=\"170\">Reg.no</th> <th width=\"170\">Course</th> <th width=\"870\">City Name</th> <th width=\"1950\">Percentage</th> </tr> </thead> <tbody> <tr> <td>Rakesh</td> <td>1123</td> <td>CSE</td> <td>Mumbai</td> <td>86.9%</td> </tr> <tr> <td>Jackson</td> <td>1124</td> <td>ECE</td> <td>Hyderabad</td> <td>72.4%</td> </tr> <tr> <td>Keshav</td> <td>1124</td> <td>CSE</td> <td>Chennai</td> <td>88%</td> </tr> <tr> <td>Neilesh Jain</td> <td>1125</td> <td>EEE</td> <td>Gwalior</td> <td>66.9%</td> </tr> <tr> <td>Akbar sheikh</td> <td>1126</td> <td>Mechanical</td> <td>Indore</td> <td>96.5%</td> </tr> <tr> <td>Sarita</td> <td>1127</td> <td>CSE</td> <td>Delhi</td> <td>96.9%</td> </tr> </tbody></Table> </> );}",
"e": 3680,
"s": 1418,
"text": null
},
{
"code": null,
"e": 3793,
"s": 3680,
"text": "Step to Run Application: Run the application using the following command from the root directory of the project:"
},
{
"code": null,
"e": 3803,
"s": 3793,
"text": "npm start"
},
{
"code": null,
"e": 3902,
"s": 3803,
"text": "Output: Now open your browser and go to http://localhost:3000/, you will see the following output."
},
{
"code": null,
"e": 3974,
"s": 3902,
"text": "Reference: https://react-bootstrap.netlify.app/components/table/#tables"
},
{
"code": null,
"e": 3991,
"s": 3974,
"text": "akshaysingh98088"
},
{
"code": null,
"e": 3998,
"s": 3991,
"text": "Picked"
},
{
"code": null,
"e": 4014,
"s": 3998,
"text": "React-Bootstrap"
},
{
"code": null,
"e": 4022,
"s": 4014,
"text": "ReactJS"
},
{
"code": null,
"e": 4039,
"s": 4022,
"text": "Web Technologies"
}
] |
Linear Congruence method for generating Pseudo Random Numbers | 17 Jul, 2021
Linear Congruential Method is a class of Pseudo Random Number Generator (PRNG) algorithms used for generating sequences of random-like numbers in a specific range. This method can be defined as:
where,
X, is the sequence of pseudo-random numbersm, ( > 0) the modulusa, (0, m) the multiplierc, (0, m) the incrementX0, [0, m) – Initial value of sequence known as seed
m, a, c, and X0 should be chosen appropriately to get a period almost equal to m.
For a = 1, it will be the additive congruence method.For c = 0, it will be the multiplicative congruence method.
Approach:
Choose the seed value X0, Modulus parameter m, Multiplier term a, and increment term c.
Initialize the required amount of random numbers to generate (say, an integer variable noOfRandomNums).
Define a storage to keep the generated random numbers (here, vector is considered) of size noOfRandomNums.
Initialize the 0th index of the vector with the seed value.
For rest of the indexes follow the Linear Congruential Method to generate the random numbers.
randomNums[i] = ((randomNums[i – 1] * a) + c) % m
Finally, return the random numbers.
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 generate random numbersvoid linearCongruentialMethod( int Xo, int m, int a, int c, vector<int>& randomNums, int noOfRandomNums){ // Initialize the seed state randomNums[0] = Xo; // Traverse to generate required // numbers of random numbers for (int i = 1; i < noOfRandomNums; i++) { // Follow the linear congruential method randomNums[i] = ((randomNums[i - 1] * a) + c) % m; }} // Driver Codeint main(){ int Xo = 5; // Seed value int m = 7; // Modulus parameter int a = 3; // Multiplier term int c = 3; // Increment term // Number of Random numbers // to be generated int noOfRandomNums = 10; // To store random numbers vector<int> randomNums( noOfRandomNums); // Function Call linearCongruentialMethod( Xo, m, a, c, randomNums, noOfRandomNums); // Print the generated random numbers for (int i = 0; i < noOfRandomNums; i++) { cout << randomNums[i] << " "; } return 0;}
// Java implementation of the above approachimport java.util.*; class GFG{ // Function to generate random numbersstatic void linearCongruentialMethod(int Xo, int m, int a, int c, int[] randomNums, int noOfRandomNums){ // Initialize the seed state randomNums[0] = Xo; // Traverse to generate required // numbers of random numbers for(int i = 1; i < noOfRandomNums; i++) { // Follow the linear congruential method randomNums[i] = ((randomNums[i - 1] * a) + c) % m; }} // Driver codepublic static void main(String[] args){ // Seed value int Xo = 5; // Modulus parameter int m = 7; // Multiplier term int a = 3; // Increment term int c = 3; // Number of Random numbers // to be generated int noOfRandomNums = 10; // To store random numbers int[] randomNums = new int[noOfRandomNums]; // Function Call linearCongruentialMethod(Xo, m, a, c, randomNums, noOfRandomNums); // Print the generated random numbers for(int i = 0; i < noOfRandomNums; i++) { System.out.print(randomNums[i] + " "); }}} // This code is contributed by offbeat
# Python3 implementation of the# above approach # Function to generate random numbersdef linearCongruentialMethod(Xo, m, a, c, randomNums, noOfRandomNums): # Initialize the seed state randomNums[0] = Xo # Traverse to generate required # numbers of random numbers for i in range(1, noOfRandomNums): # Follow the linear congruential method randomNums[i] = ((randomNums[i - 1] * a) + c) % m # Driver Codeif __name__ == '__main__': # Seed value Xo = 5 # Modulus parameter m = 7 # Multiplier term a = 3 # Increment term c = 3 # Number of Random numbers # to be generated noOfRandomNums = 10 # To store random numbers randomNums = [0] * (noOfRandomNums) # Function Call linearCongruentialMethod(Xo, m, a, c, randomNums, noOfRandomNums) # Print the generated random numbers for i in randomNums: print(i, end = " ") # This code is contributed by mohit kumar 29
// C# implementation of the above approachusing System; class GFG{ // Function to generate random numbersstatic void linearCongruentialMethod(int Xo, int m, int a, int c, int[] randomNums, int noOfRandomNums){ // Initialize the seed state randomNums[0] = Xo; // Traverse to generate required // numbers of random numbers for(int i = 1; i < noOfRandomNums; i++) { // Follow the linear congruential method randomNums[i] = ((randomNums[i - 1] * a) + c) % m; }} // Driver codepublic static void Main(String[] args){ // Seed value int Xo = 5; // Modulus parameter int m = 7; // Multiplier term int a = 3; // Increment term int c = 3; // Number of Random numbers // to be generated int noOfRandomNums = 10; // To store random numbers int[] randomNums = new int[noOfRandomNums]; // Function call linearCongruentialMethod(Xo, m, a, c, randomNums, noOfRandomNums); // Print the generated random numbers for(int i = 0; i < noOfRandomNums; i++) { Console.Write(randomNums[i] + " "); }}} // This code is contributed by sapnasingh4991
<script> // Javascript program to implement// the above approach // Function to generate random numbersfunction linearCongruentialMethod(Xo, m, a, c, randomNums, noOfRandomNums){ // Initialize the seed state randomNums[0] = Xo; // Traverse to generate required // numbers of random numbers for(let i = 1; i < noOfRandomNums; i++) { // Follow the linear congruential method randomNums[i] = ((randomNums[i - 1] * a) + c) % m; }} // Driver Code // Seed value let Xo = 5; // Modulus parameter let m = 7; // Multiplier term let a = 3; // Increment term let c = 3; // Number of Random numbers // to be generated let noOfRandomNums = 10; // To store random numbers let randomNums = new Array(noOfRandomNums).fill(0); // Function Call linearCongruentialMethod(Xo, m, a, c, randomNums, noOfRandomNums); // Print the generated random numbers for(let i = 0; i < noOfRandomNums; i++) { document.write(randomNums[i] + " "); } </script>
5 4 1 6 0 3 5 4 1 6
The literal meaning of pseudo is false. These random numbers are called pseudo because some known arithmetic procedure is utilized to generate. Even the generated sequence forms a pattern hence the generated number seems to be random but may not be truly random.
mohit kumar 29
offbeat
sapnasingh4991
chinmoy1997pal
saurabh1990aror
Engineering Mathematics
Mathematical
Mathematical
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here. | [
{
"code": null,
"e": 28,
"s": 0,
"text": "\n17 Jul, 2021"
},
{
"code": null,
"e": 224,
"s": 28,
"text": "Linear Congruential Method is a class of Pseudo Random Number Generator (PRNG) algorithms used for generating sequences of random-like numbers in a specific range. This method can be defined as: "
},
{
"code": null,
"e": 231,
"s": 224,
"text": "where,"
},
{
"code": null,
"e": 396,
"s": 231,
"text": "X, is the sequence of pseudo-random numbersm, ( > 0) the modulusa, (0, m) the multiplierc, (0, m) the incrementX0, [0, m) – Initial value of sequence known as seed"
},
{
"code": null,
"e": 479,
"s": 396,
"text": "m, a, c, and X0 should be chosen appropriately to get a period almost equal to m. "
},
{
"code": null,
"e": 593,
"s": 479,
"text": "For a = 1, it will be the additive congruence method.For c = 0, it will be the multiplicative congruence method. "
},
{
"code": null,
"e": 604,
"s": 593,
"text": "Approach: "
},
{
"code": null,
"e": 692,
"s": 604,
"text": "Choose the seed value X0, Modulus parameter m, Multiplier term a, and increment term c."
},
{
"code": null,
"e": 796,
"s": 692,
"text": "Initialize the required amount of random numbers to generate (say, an integer variable noOfRandomNums)."
},
{
"code": null,
"e": 903,
"s": 796,
"text": "Define a storage to keep the generated random numbers (here, vector is considered) of size noOfRandomNums."
},
{
"code": null,
"e": 963,
"s": 903,
"text": "Initialize the 0th index of the vector with the seed value."
},
{
"code": null,
"e": 1057,
"s": 963,
"text": "For rest of the indexes follow the Linear Congruential Method to generate the random numbers."
},
{
"code": null,
"e": 1108,
"s": 1057,
"text": "randomNums[i] = ((randomNums[i – 1] * a) + c) % m "
},
{
"code": null,
"e": 1144,
"s": 1108,
"text": "Finally, return the random numbers."
},
{
"code": null,
"e": 1195,
"s": 1144,
"text": "Below is the implementation of the above approach:"
},
{
"code": null,
"e": 1199,
"s": 1195,
"text": "C++"
},
{
"code": null,
"e": 1204,
"s": 1199,
"text": "Java"
},
{
"code": null,
"e": 1212,
"s": 1204,
"text": "Python3"
},
{
"code": null,
"e": 1215,
"s": 1212,
"text": "C#"
},
{
"code": null,
"e": 1226,
"s": 1215,
"text": "Javascript"
},
{
"code": "// C++ implementation of the// above approach #include <bits/stdc++.h>using namespace std; // Function to generate random numbersvoid linearCongruentialMethod( int Xo, int m, int a, int c, vector<int>& randomNums, int noOfRandomNums){ // Initialize the seed state randomNums[0] = Xo; // Traverse to generate required // numbers of random numbers for (int i = 1; i < noOfRandomNums; i++) { // Follow the linear congruential method randomNums[i] = ((randomNums[i - 1] * a) + c) % m; }} // Driver Codeint main(){ int Xo = 5; // Seed value int m = 7; // Modulus parameter int a = 3; // Multiplier term int c = 3; // Increment term // Number of Random numbers // to be generated int noOfRandomNums = 10; // To store random numbers vector<int> randomNums( noOfRandomNums); // Function Call linearCongruentialMethod( Xo, m, a, c, randomNums, noOfRandomNums); // Print the generated random numbers for (int i = 0; i < noOfRandomNums; i++) { cout << randomNums[i] << \" \"; } return 0;}",
"e": 2334,
"s": 1226,
"text": null
},
{
"code": "// Java implementation of the above approachimport java.util.*; class GFG{ // Function to generate random numbersstatic void linearCongruentialMethod(int Xo, int m, int a, int c, int[] randomNums, int noOfRandomNums){ // Initialize the seed state randomNums[0] = Xo; // Traverse to generate required // numbers of random numbers for(int i = 1; i < noOfRandomNums; i++) { // Follow the linear congruential method randomNums[i] = ((randomNums[i - 1] * a) + c) % m; }} // Driver codepublic static void main(String[] args){ // Seed value int Xo = 5; // Modulus parameter int m = 7; // Multiplier term int a = 3; // Increment term int c = 3; // Number of Random numbers // to be generated int noOfRandomNums = 10; // To store random numbers int[] randomNums = new int[noOfRandomNums]; // Function Call linearCongruentialMethod(Xo, m, a, c, randomNums, noOfRandomNums); // Print the generated random numbers for(int i = 0; i < noOfRandomNums; i++) { System.out.print(randomNums[i] + \" \"); }}} // This code is contributed by offbeat",
"e": 3678,
"s": 2334,
"text": null
},
{
"code": "# Python3 implementation of the# above approach # Function to generate random numbersdef linearCongruentialMethod(Xo, m, a, c, randomNums, noOfRandomNums): # Initialize the seed state randomNums[0] = Xo # Traverse to generate required # numbers of random numbers for i in range(1, noOfRandomNums): # Follow the linear congruential method randomNums[i] = ((randomNums[i - 1] * a) + c) % m # Driver Codeif __name__ == '__main__': # Seed value Xo = 5 # Modulus parameter m = 7 # Multiplier term a = 3 # Increment term c = 3 # Number of Random numbers # to be generated noOfRandomNums = 10 # To store random numbers randomNums = [0] * (noOfRandomNums) # Function Call linearCongruentialMethod(Xo, m, a, c, randomNums, noOfRandomNums) # Print the generated random numbers for i in randomNums: print(i, end = \" \") # This code is contributed by mohit kumar 29",
"e": 4805,
"s": 3678,
"text": null
},
{
"code": "// C# implementation of the above approachusing System; class GFG{ // Function to generate random numbersstatic void linearCongruentialMethod(int Xo, int m, int a, int c, int[] randomNums, int noOfRandomNums){ // Initialize the seed state randomNums[0] = Xo; // Traverse to generate required // numbers of random numbers for(int i = 1; i < noOfRandomNums; i++) { // Follow the linear congruential method randomNums[i] = ((randomNums[i - 1] * a) + c) % m; }} // Driver codepublic static void Main(String[] args){ // Seed value int Xo = 5; // Modulus parameter int m = 7; // Multiplier term int a = 3; // Increment term int c = 3; // Number of Random numbers // to be generated int noOfRandomNums = 10; // To store random numbers int[] randomNums = new int[noOfRandomNums]; // Function call linearCongruentialMethod(Xo, m, a, c, randomNums, noOfRandomNums); // Print the generated random numbers for(int i = 0; i < noOfRandomNums; i++) { Console.Write(randomNums[i] + \" \"); }}} // This code is contributed by sapnasingh4991",
"e": 6145,
"s": 4805,
"text": null
},
{
"code": "<script> // Javascript program to implement// the above approach // Function to generate random numbersfunction linearCongruentialMethod(Xo, m, a, c, randomNums, noOfRandomNums){ // Initialize the seed state randomNums[0] = Xo; // Traverse to generate required // numbers of random numbers for(let i = 1; i < noOfRandomNums; i++) { // Follow the linear congruential method randomNums[i] = ((randomNums[i - 1] * a) + c) % m; }} // Driver Code // Seed value let Xo = 5; // Modulus parameter let m = 7; // Multiplier term let a = 3; // Increment term let c = 3; // Number of Random numbers // to be generated let noOfRandomNums = 10; // To store random numbers let randomNums = new Array(noOfRandomNums).fill(0); // Function Call linearCongruentialMethod(Xo, m, a, c, randomNums, noOfRandomNums); // Print the generated random numbers for(let i = 0; i < noOfRandomNums; i++) { document.write(randomNums[i] + \" \"); } </script>",
"e": 7331,
"s": 6145,
"text": null
},
{
"code": null,
"e": 7351,
"s": 7331,
"text": "5 4 1 6 0 3 5 4 1 6"
},
{
"code": null,
"e": 7615,
"s": 7351,
"text": "The literal meaning of pseudo is false. These random numbers are called pseudo because some known arithmetic procedure is utilized to generate. Even the generated sequence forms a pattern hence the generated number seems to be random but may not be truly random. "
},
{
"code": null,
"e": 7630,
"s": 7615,
"text": "mohit kumar 29"
},
{
"code": null,
"e": 7638,
"s": 7630,
"text": "offbeat"
},
{
"code": null,
"e": 7653,
"s": 7638,
"text": "sapnasingh4991"
},
{
"code": null,
"e": 7668,
"s": 7653,
"text": "chinmoy1997pal"
},
{
"code": null,
"e": 7684,
"s": 7668,
"text": "saurabh1990aror"
},
{
"code": null,
"e": 7708,
"s": 7684,
"text": "Engineering Mathematics"
},
{
"code": null,
"e": 7721,
"s": 7708,
"text": "Mathematical"
},
{
"code": null,
"e": 7734,
"s": 7721,
"text": "Mathematical"
}
] |
C++ Program to Find all triplets with zero sum | 06 Jan, 2022
Given an array of distinct elements. The task is to find triplets in the array whose sum is zero.
Examples :
Input : arr[] = {0, -1, 2, -3, 1}
Output : (0 -1 1), (2 -3 1)
Explanation : The triplets with zero sum are
0 + -1 + 1 = 0 and 2 + -3 + 1 = 0
Input : arr[] = {1, -2, 1, 0, 5}
Output : 1 -2 1
Explanation : The triplets with zero sum is
1 + -2 + 1 = 0
Method 1: This is a simple method that takes O(n3) time to arrive at the result.
Approach: The naive approach runs three loops and check one by one that sum of three elements is zero or not. If the sum of three elements is zero then print elements otherwise print not found.
Algorithm: Run three nested loops with loop counter i, j, kThe first loops will run from 0 to n-3 and second loop from i+1 to n-2 and the third loop from j+1 to n-1. The loop counter represents the three elements of the triplet.Check if the sum of elements at i’th, j’th, k’th is equal to zero or not. If yes print the sum else continue.
Run three nested loops with loop counter i, j, kThe first loops will run from 0 to n-3 and second loop from i+1 to n-2 and the third loop from j+1 to n-1. The loop counter represents the three elements of the triplet.Check if the sum of elements at i’th, j’th, k’th is equal to zero or not. If yes print the sum else continue.
Run three nested loops with loop counter i, j, k
The first loops will run from 0 to n-3 and second loop from i+1 to n-2 and the third loop from j+1 to n-1. The loop counter represents the three elements of the triplet.
Check if the sum of elements at i’th, j’th, k’th is equal to zero or not. If yes print the sum else continue.
Below is the implementation of the above approach:
// Prints all triplets in arr[] with 0 sumvoid findTriplets(int arr[], int n){bool found = false;for (int i=0; iOutput
0 -1 1
2 -3 1
Complexity Analysis:
Time Complexity: O(n3). As three nested loops are required, so the time complexity is O(n3).
Auxiliary Space: O(1). Since no extra space is required, so the space complexity is constant.
Method 2: The second method uses the process of Hashing to arrive at the result and is solved at a lesser time of O(n2).
Approach: This involves traversing through the array. For every element arr[i], find a pair with sum “-arr[i]”. This problem reduces to pair sum and can be solved in O(n) time using hashing.
Algorithm:
Create a hashmap to store a key-value pair.Run a nested loop with two loops, the outer loop from 0 to n-2 and the inner loop from i+1 to n-1Check if the sum of ith and jth element multiplied with -1 is present in the hashmap or notIf the element is present in the hashmap, print the triplet else insert the j’th element in the hashmap.
Create a hashmap to store a key-value pair.
Run a nested loop with two loops, the outer loop from 0 to n-2 and the inner loop from i+1 to n-1
Check if the sum of ith and jth element multiplied with -1 is present in the hashmap or not
If the element is present in the hashmap, print the triplet else insert the j’th element in the hashmap.
Below is the implementation of the above approach:
// function to print triplets with 0 sumvoid findTriplets(int arr[], int n){bool found = false;
for (int i=0; i-1 0 1
-3 2 1
-1 0 1
-3 2 1
Complexity Analysis:
Time Complexity: O(n2). Since two nested loops are required, so the time complexity is O(n2).
Auxiliary Space: O(n). Since a hashmap is required, so the space complexity is linear.
Method 3: This method uses Sorting to arrive at the correct result and is solved in O(n2) time.
Approach: The above method requires extra space. The idea is based on method 2 of this post. For every element check that there is a pair whose sum is equal to the negative value of that element.
Algorithm:
Sort the array in ascending order.Traverse the array from start to end.For every index i, create two variables l = i + 1 and r = n – 1Run a loop until l is less than r if the sum of array[i], array[l] and array[r] is equal to zero then print the triplet and break the loopIf the sum is less than zero then increment the value of l, by increasing the value of l the sum will increase as the array is sorted, so array[l+1] > array [l]If the sum is greater than zero then decrement the value of r, by increasing the value of l the sum will decrease as the array is sorted, so array[r-1] < array [r].
Sort the array in ascending order.
Traverse the array from start to end.
For every index i, create two variables l = i + 1 and r = n – 1
Run a loop until l is less than r if the sum of array[i], array[l] and array[r] is equal to zero then print the triplet and break the loop
If the sum is less than zero then increment the value of l, by increasing the value of l the sum will increase as the array is sorted, so array[l+1] > array [l]
If the sum is greater than zero then decrement the value of r, by increasing the value of l the sum will decrease as the array is sorted, so array[r-1] < array [r].
Below is the implementation of the above approach:
// function to print triplets with 0 sumvoid findTriplets(int arr[], int n){bool found = false;
// sort array elementssort(arr, arr+n);
for (int i=0; iOutput
-3 1 2
-1 0 1
Complexity Analysis:
Time Complexity : O(n2). Only two nested loops are required, so the time complexity is O(n2).
Auxiliary Space : O(1), no extra space is required, so the time complexity is constant.
Please refer complete article on Find all triplets with zero sum for more details!
Facebook
Google
two-pointer-algorithm
Arrays
C Programs
C++
Hash
Searching
Sorting
Google
Facebook
two-pointer-algorithm
Arrays
Searching
Hash
Sorting
CPP
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Introduction to Data Structures
Search, insert and delete in an unsorted array
Window Sliding Technique
Chocolate Distribution Problem
Longest Consecutive Subsequence
Strings in C
Arrow operator -> in C/C++ with Examples
Basics of File Handling in C
UDP Server-Client implementation in C
Header files in C/C++ and its uses | [
{
"code": null,
"e": 28,
"s": 0,
"text": "\n06 Jan, 2022"
},
{
"code": null,
"e": 126,
"s": 28,
"text": "Given an array of distinct elements. The task is to find triplets in the array whose sum is zero."
},
{
"code": null,
"e": 138,
"s": 126,
"text": "Examples : "
},
{
"code": null,
"e": 395,
"s": 138,
"text": "Input : arr[] = {0, -1, 2, -3, 1}\nOutput : (0 -1 1), (2 -3 1)\n\nExplanation : The triplets with zero sum are\n0 + -1 + 1 = 0 and 2 + -3 + 1 = 0 \n\nInput : arr[] = {1, -2, 1, 0, 5}\nOutput : 1 -2 1\nExplanation : The triplets with zero sum is\n1 + -2 + 1 = 0 "
},
{
"code": null,
"e": 476,
"s": 395,
"text": "Method 1: This is a simple method that takes O(n3) time to arrive at the result."
},
{
"code": null,
"e": 670,
"s": 476,
"text": "Approach: The naive approach runs three loops and check one by one that sum of three elements is zero or not. If the sum of three elements is zero then print elements otherwise print not found."
},
{
"code": null,
"e": 1008,
"s": 670,
"text": "Algorithm: Run three nested loops with loop counter i, j, kThe first loops will run from 0 to n-3 and second loop from i+1 to n-2 and the third loop from j+1 to n-1. The loop counter represents the three elements of the triplet.Check if the sum of elements at i’th, j’th, k’th is equal to zero or not. If yes print the sum else continue."
},
{
"code": null,
"e": 1335,
"s": 1008,
"text": "Run three nested loops with loop counter i, j, kThe first loops will run from 0 to n-3 and second loop from i+1 to n-2 and the third loop from j+1 to n-1. The loop counter represents the three elements of the triplet.Check if the sum of elements at i’th, j’th, k’th is equal to zero or not. If yes print the sum else continue."
},
{
"code": null,
"e": 1384,
"s": 1335,
"text": "Run three nested loops with loop counter i, j, k"
},
{
"code": null,
"e": 1554,
"s": 1384,
"text": "The first loops will run from 0 to n-3 and second loop from i+1 to n-2 and the third loop from j+1 to n-1. The loop counter represents the three elements of the triplet."
},
{
"code": null,
"e": 1664,
"s": 1554,
"text": "Check if the sum of elements at i’th, j’th, k’th is equal to zero or not. If yes print the sum else continue."
},
{
"code": null,
"e": 1716,
"s": 1664,
"text": "Below is the implementation of the above approach: "
},
{
"code": null,
"e": 1835,
"s": 1716,
"text": "// Prints all triplets in arr[] with 0 sumvoid findTriplets(int arr[], int n){bool found = false;for (int i=0; iOutput"
},
{
"code": null,
"e": 1849,
"s": 1835,
"text": "0 -1 1\n2 -3 1"
},
{
"code": null,
"e": 1871,
"s": 1849,
"text": "Complexity Analysis: "
},
{
"code": null,
"e": 1964,
"s": 1871,
"text": "Time Complexity: O(n3). As three nested loops are required, so the time complexity is O(n3)."
},
{
"code": null,
"e": 2058,
"s": 1964,
"text": "Auxiliary Space: O(1). Since no extra space is required, so the space complexity is constant."
},
{
"code": null,
"e": 2181,
"s": 2058,
"text": " Method 2: The second method uses the process of Hashing to arrive at the result and is solved at a lesser time of O(n2). "
},
{
"code": null,
"e": 2372,
"s": 2181,
"text": "Approach: This involves traversing through the array. For every element arr[i], find a pair with sum “-arr[i]”. This problem reduces to pair sum and can be solved in O(n) time using hashing."
},
{
"code": null,
"e": 2384,
"s": 2372,
"text": "Algorithm: "
},
{
"code": null,
"e": 2720,
"s": 2384,
"text": "Create a hashmap to store a key-value pair.Run a nested loop with two loops, the outer loop from 0 to n-2 and the inner loop from i+1 to n-1Check if the sum of ith and jth element multiplied with -1 is present in the hashmap or notIf the element is present in the hashmap, print the triplet else insert the j’th element in the hashmap."
},
{
"code": null,
"e": 2764,
"s": 2720,
"text": "Create a hashmap to store a key-value pair."
},
{
"code": null,
"e": 2862,
"s": 2764,
"text": "Run a nested loop with two loops, the outer loop from 0 to n-2 and the inner loop from i+1 to n-1"
},
{
"code": null,
"e": 2954,
"s": 2862,
"text": "Check if the sum of ith and jth element multiplied with -1 is present in the hashmap or not"
},
{
"code": null,
"e": 3059,
"s": 2954,
"text": "If the element is present in the hashmap, print the triplet else insert the j’th element in the hashmap."
},
{
"code": null,
"e": 3111,
"s": 3059,
"text": "Below is the implementation of the above approach: "
},
{
"code": null,
"e": 3207,
"s": 3111,
"text": "// function to print triplets with 0 sumvoid findTriplets(int arr[], int n){bool found = false;"
},
{
"code": null,
"e": 3236,
"s": 3207,
"text": "for (int i=0; i-1 0 1\n-3 2 1"
},
{
"code": null,
"e": 3250,
"s": 3236,
"text": "-1 0 1\n-3 2 1"
},
{
"code": null,
"e": 3272,
"s": 3250,
"text": "Complexity Analysis: "
},
{
"code": null,
"e": 3366,
"s": 3272,
"text": "Time Complexity: O(n2). Since two nested loops are required, so the time complexity is O(n2)."
},
{
"code": null,
"e": 3453,
"s": 3366,
"text": "Auxiliary Space: O(n). Since a hashmap is required, so the space complexity is linear."
},
{
"code": null,
"e": 3552,
"s": 3453,
"text": " Method 3: This method uses Sorting to arrive at the correct result and is solved in O(n2) time. "
},
{
"code": null,
"e": 3748,
"s": 3552,
"text": "Approach: The above method requires extra space. The idea is based on method 2 of this post. For every element check that there is a pair whose sum is equal to the negative value of that element."
},
{
"code": null,
"e": 3760,
"s": 3748,
"text": "Algorithm: "
},
{
"code": null,
"e": 4357,
"s": 3760,
"text": "Sort the array in ascending order.Traverse the array from start to end.For every index i, create two variables l = i + 1 and r = n – 1Run a loop until l is less than r if the sum of array[i], array[l] and array[r] is equal to zero then print the triplet and break the loopIf the sum is less than zero then increment the value of l, by increasing the value of l the sum will increase as the array is sorted, so array[l+1] > array [l]If the sum is greater than zero then decrement the value of r, by increasing the value of l the sum will decrease as the array is sorted, so array[r-1] < array [r]."
},
{
"code": null,
"e": 4392,
"s": 4357,
"text": "Sort the array in ascending order."
},
{
"code": null,
"e": 4430,
"s": 4392,
"text": "Traverse the array from start to end."
},
{
"code": null,
"e": 4494,
"s": 4430,
"text": "For every index i, create two variables l = i + 1 and r = n – 1"
},
{
"code": null,
"e": 4633,
"s": 4494,
"text": "Run a loop until l is less than r if the sum of array[i], array[l] and array[r] is equal to zero then print the triplet and break the loop"
},
{
"code": null,
"e": 4794,
"s": 4633,
"text": "If the sum is less than zero then increment the value of l, by increasing the value of l the sum will increase as the array is sorted, so array[l+1] > array [l]"
},
{
"code": null,
"e": 4959,
"s": 4794,
"text": "If the sum is greater than zero then decrement the value of r, by increasing the value of l the sum will decrease as the array is sorted, so array[r-1] < array [r]."
},
{
"code": null,
"e": 5011,
"s": 4959,
"text": "Below is the implementation of the above approach: "
},
{
"code": null,
"e": 5107,
"s": 5011,
"text": "// function to print triplets with 0 sumvoid findTriplets(int arr[], int n){bool found = false;"
},
{
"code": null,
"e": 5147,
"s": 5107,
"text": "// sort array elementssort(arr, arr+n);"
},
{
"code": null,
"e": 5169,
"s": 5147,
"text": "for (int i=0; iOutput"
},
{
"code": null,
"e": 5183,
"s": 5169,
"text": "-3 1 2\n-1 0 1"
},
{
"code": null,
"e": 5205,
"s": 5183,
"text": "Complexity Analysis: "
},
{
"code": null,
"e": 5299,
"s": 5205,
"text": "Time Complexity : O(n2). Only two nested loops are required, so the time complexity is O(n2)."
},
{
"code": null,
"e": 5387,
"s": 5299,
"text": "Auxiliary Space : O(1), no extra space is required, so the time complexity is constant."
},
{
"code": null,
"e": 5470,
"s": 5387,
"text": "Please refer complete article on Find all triplets with zero sum for more details!"
},
{
"code": null,
"e": 5479,
"s": 5470,
"text": "Facebook"
},
{
"code": null,
"e": 5486,
"s": 5479,
"text": "Google"
},
{
"code": null,
"e": 5508,
"s": 5486,
"text": "two-pointer-algorithm"
},
{
"code": null,
"e": 5515,
"s": 5508,
"text": "Arrays"
},
{
"code": null,
"e": 5526,
"s": 5515,
"text": "C Programs"
},
{
"code": null,
"e": 5530,
"s": 5526,
"text": "C++"
},
{
"code": null,
"e": 5535,
"s": 5530,
"text": "Hash"
},
{
"code": null,
"e": 5545,
"s": 5535,
"text": "Searching"
},
{
"code": null,
"e": 5553,
"s": 5545,
"text": "Sorting"
},
{
"code": null,
"e": 5560,
"s": 5553,
"text": "Google"
},
{
"code": null,
"e": 5569,
"s": 5560,
"text": "Facebook"
},
{
"code": null,
"e": 5591,
"s": 5569,
"text": "two-pointer-algorithm"
},
{
"code": null,
"e": 5598,
"s": 5591,
"text": "Arrays"
},
{
"code": null,
"e": 5608,
"s": 5598,
"text": "Searching"
},
{
"code": null,
"e": 5613,
"s": 5608,
"text": "Hash"
},
{
"code": null,
"e": 5621,
"s": 5613,
"text": "Sorting"
},
{
"code": null,
"e": 5625,
"s": 5621,
"text": "CPP"
},
{
"code": null,
"e": 5723,
"s": 5625,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 5755,
"s": 5723,
"text": "Introduction to Data Structures"
},
{
"code": null,
"e": 5802,
"s": 5755,
"text": "Search, insert and delete in an unsorted array"
},
{
"code": null,
"e": 5827,
"s": 5802,
"text": "Window Sliding Technique"
},
{
"code": null,
"e": 5858,
"s": 5827,
"text": "Chocolate Distribution Problem"
},
{
"code": null,
"e": 5890,
"s": 5858,
"text": "Longest Consecutive Subsequence"
},
{
"code": null,
"e": 5903,
"s": 5890,
"text": "Strings in C"
},
{
"code": null,
"e": 5944,
"s": 5903,
"text": "Arrow operator -> in C/C++ with Examples"
},
{
"code": null,
"e": 5973,
"s": 5944,
"text": "Basics of File Handling in C"
},
{
"code": null,
"e": 6011,
"s": 5973,
"text": "UDP Server-Client implementation in C"
}
] |
Length of the longest valid substring | 28 Feb, 2022
Given a string consisting of opening and closing parenthesis, find the length of the longest valid parenthesis substring.
Examples:
Input : ((()
Output : 2
Explanation : ()
Input: )()())
Output : 4
Explanation: ()()
Input: ()(()))))
Output: 6
Explanation: ()(())
A Simple Approach is to find all the substrings of given string. For every string, check if it is a valid string or not. If valid and length is more than maximum length so far, then update maximum length. We can check whether a substring is valid or not in linear time using a stack (See this for details). Time complexity of this solution is O(n2.
An Efficient Solution can solve this problem in O(n) time. The idea is to store indexes of previous starting brackets in a stack. The first element of the stack is a special element that provides index before the beginning of valid substring (base for next valid string).
1) Create an empty stack and push -1 to it.
The first element of the stack is used
to provide a base for the next valid string.
2) Initialize result as 0.
3) If the character is '(' i.e. str[i] == '('),
push index'i' to the stack.
2) Else (if the character is ')')
a) Pop an item from the stack (Most of the
time an opening bracket)
b) If the stack is not empty, then find the
length of current valid substring by taking
the difference between the current index and
top of the stack. If current length is more
than the result, then update the result.
c) If the stack is empty, push the current index
as a base for the next valid substring.
3) Return result.
Below is the implementation of the above algorithm.
C++
Java
Python3
C#
Javascript
// C++ program to find length of the// longest valid substring#include <bits/stdc++.h>using namespace std; int findMaxLen(string str){ int n = str.length(); // Create a stack and push -1 as // initial index to it. stack<int> stk; stk.push(-1); // Initialize result int result = 0; // Traverse all characters of given string for (int i = 0; i < n; i++) { // If opening bracket, push index of it if (str[i] == '(') stk.push(i); // If closing bracket, i.e.,str[i] = ')' else { // Pop the previous opening // bracket's index if (!stk.empty()) { stk.pop(); } // Check if this length formed with base of // current valid substring is more than max // so far if (!stk.empty()) result = max(result, i - stk.top()); // If stack is empty. push current index as // base for next valid substring (if any) else stk.push(i); } } return result;} // Driver codeint main(){ string str = "((()()"; // Function call cout << findMaxLen(str) << endl; str = "()(()))))"; // Function call cout << findMaxLen(str) << endl; return 0;}
// Java program to find length of the longest valid// substring import java.util.Stack; class Test{ // method to get length of the longest valid static int findMaxLen(String str) { int n = str.length(); // Create a stack and push -1 // as initial index to it. Stack<Integer> stk = new Stack<>(); stk.push(-1); // Initialize result int result = 0; // Traverse all characters of given string for (int i = 0; i < n; i++) { // If opening bracket, push index of it if (str.charAt(i) == '(') stk.push(i); // // If closing bracket, i.e.,str[i] = ')' else { // Pop the previous // opening bracket's index if(!stk.empty()) stk.pop(); // Check if this length // formed with base of // current valid substring // is more than max // so far if (!stk.empty()) result = Math.max(result, i - stk.peek()); // If stack is empty. push // current index as base // for next valid substring (if any) else stk.push(i); } } return result; } // Driver code public static void main(String[] args) { String str = "((()()"; // Function call System.out.println(findMaxLen(str)); str = "()(()))))"; // Function call System.out.println(findMaxLen(str)); }}
# Python program to find length of the longest valid# substring def findMaxLen(string): n = len(string) # Create a stack and push -1 # as initial index to it. stk = [] stk.append(-1) # Initialize result result = 0 # Traverse all characters of given string for i in range(n): # If opening bracket, push index of it if string[i] == '(': stk.append(i) # If closing bracket, i.e., str[i] = ')' else: # Pop the previous opening bracket's index if len(stk) != 0: stk.pop() # Check if this length formed with base of # current valid substring is more than max # so far if len(stk) != 0: result = max(result, i - stk[len(stk)-1]) # If stack is empty. push current index as # base for next valid substring (if any) else: stk.append(i) return result # Driver codestring = "((()()" # Function callprint (findMaxLen(string)) string = "()(()))))" # Function callprint (findMaxLen(string)) # This code is contributed by Bhavya Jain
// C# program to find length of// the longest valid substringusing System;using System.Collections.Generic; class GFG { // method to get length of // the longest valid public static int findMaxLen(string str) { int n = str.Length; // Create a stack and push -1 as // initial index to it. Stack<int> stk = new Stack<int>(); stk.Push(-1); // Initialize result int result = 0; // Traverse all characters of // given string for (int i = 0; i < n; i++) { // If opening bracket, push // index of it if (str[i] == '(') { stk.Push(i); } else // If closing bracket, // i.e.,str[i] = ')' { // Pop the previous opening // bracket's index if (stk.Count > 0) stk.Pop(); // Check if this length formed // with base of current valid // substring is more than max // so far if (stk.Count > 0) { result = Math.Max(result, i - stk.Peek()); } // If stack is empty. push current // index as base for next valid // substring (if any) else { stk.Push(i); } } } return result; } // Driver Code public static void Main(string[] args) { string str = "((()()"; // Function call Console.WriteLine(findMaxLen(str)); str = "()(()))))"; // Function call Console.WriteLine(findMaxLen(str)); }} // This code is contributed by Shrikant13
<script> // JavaScript Program for the above approach function findMaxLen(str) { let n = str.length; // Create a stack and push -1 as // initial index to it. let stk = []; stk.push(-1); // Initialize result let result = 0; // Traverse all characters of given string for (let i = 0; i < n; i++) { // If opening bracket, push index of it if (str.charAt(i) == '(') { stk.push(i); } // If closing bracket, i.e.,str[i] = ')' else { // Pop the previous opening // bracket's index if (stk.length != 0) { stk.pop(); } // Check if this length formed with base of // current valid substring is more than max // so far if (stk.length != 0) { result = Math.max(result, i - stk[stk.length - 1]); } // If stack is empty. push current index as // base for next valid substring (if any) else { stk.push(i); } } } return result; } // Driver code let str = "((()()"; // Function call document.write(findMaxLen(str) + "<br>"); str = "()(()))))"; // Function call document.write(findMaxLen(str) + "<br>"); // This code is contributed by Potta Lokesh </script>
4
6
Explanation with example:
Input: str = "(()()"
Initialize result as 0 and stack with one item -1.
For i = 0, str[0] = '(', we push 0 in stack
For i = 1, str[1] = '(', we push 1 in stack
For i = 2, str[2] = ')', currently stack has
[-1, 0, 1], we pop from the stack and the stack
now is [-1, 0] and length of current valid substring
becomes 2 (we get this 2 by subtracting stack top from
current index).
Since the current length is more than the current result,
we update the result.
For i = 3, str[3] = '(', we push again, stack is [-1, 0, 3].
For i = 4, str[4] = ')', we pop from the stack, stack
becomes [-1, 0] and length of current valid substring
becomes 4 (we get this 4 by subtracting stack top from
current index).
Since current length is more than current result,
we update result.
Another Efficient Approach can solve the problem in O(n) time. The idea is to maintain an array that stores the length of the longest valid substring ending at that index. We iterate through the array and return the maximum value.
1) Create an array longest of length n (size of the input
string) initialized to zero.
The array will store the length of the longest valid
substring ending at that index.
2) Initialize result as 0.
3) Iterate through the string from second character
a) If the character is '(' set longest[i]=0 as no
valid sub-string will end with '('.
b) Else
i) if s[i-1] = '('
set longest[i] = longest[i-2] + 2
ii) else
set longest[i] = longest[i-1] + 2 +
longest[i-longest[i-1]-2]
4) In each iteration update result as the maximum of
result and longest[i]
5) Return result.
Below is the implementations of the above algorithm.
C++
Java
Python3
C#
Javascript
// C++ program to find length of the longest valid// substring#include <bits/stdc++.h>using namespace std; int findMaxLen(string s){ if (s.length() <= 1) return 0; // Initialize curMax to zero int curMax = 0; vector<int> longest(s.size(), 0); // Iterate over the string starting from second index for (int i = 1; i < s.length(); i++) { if (s[i] == ')' && i - longest[i - 1] - 1 >= 0 && s[i - longest[i - 1] - 1] == '(') { longest[i] = longest[i - 1] + 2 + ((i - longest[i - 1] - 2 >= 0) ? longest[i - longest[i - 1] - 2] : 0); curMax = max(longest[i], curMax); } } return curMax;} // Driver codeint main(){ string str = "((()()"; // Function call cout << findMaxLen(str) << endl; str = "()(()))))"; // Function call cout << findMaxLen(str) << endl; return 0;}// This code is contributed by Vipul Lohani
// Java program to find length of the longest valid// subStringimport java.util.*;class GFG{ static int findMaxLen(String s) { if (s.length() <= 1) return 0; // Initialize curMax to zero int curMax = 0; int[] longest = new int[s.length()]; // Iterate over the String starting from second index for (int i = 1; i < s.length(); i++) { if (s.charAt(i) == ')' && i - longest[i - 1] - 1 >= 0 && s.charAt(i - longest[i - 1] - 1) == '(') { longest[i] = longest[i - 1] + 2 + ((i - longest[i - 1] - 2 >= 0) ? longest[i - longest[i - 1] - 2] : 0); curMax = Math.max(longest[i], curMax); } } return curMax; } // Driver code public static void main(String[] args) { String str = "((()()"; // Function call System.out.print(findMaxLen(str) +"\n"); str = "()(()))))"; // Function call System.out.print(findMaxLen(str) +"\n"); }} // This code is contributed by aashish1995
# Python3 program to find length of# the longest valid substring def findMaxLen(s): if (len(s) <= 1): return 0 # Initialize curMax to zero curMax = 0 longest = [0] * (len(s)) # Iterate over the string starting # from second index for i in range(1, len(s)): if ((s[i] == ')' and i - longest[i - 1] - 1 >= 0 and s[i - longest[i - 1] - 1] == '(')): longest[i] = longest[i - 1] + 2 if (i - longest[i - 1] - 2 >= 0): longest[i] += (longest[i - longest[i - 1] - 2]) else: longest[i] += 0 curMax = max(longest[i], curMax) return curMax # Driver Codeif __name__ == '__main__': Str = "((()()" # Function call print(findMaxLen(Str)) Str = "()(()))))" # Function call print(findMaxLen(Str)) # This code is contributed by PranchalK
// C# program to find length of the longest valid// subStringusing System; public class GFG { static int findMaxLen(String s) { if (s.Length <= 1) return 0; // Initialize curMax to zero int curMax = 0; int[] longest = new int[s.Length]; // Iterate over the String starting from second index for (int i = 1; i < s.Length; i++) { if (s[i] == ')' && i - longest[i - 1] - 1 >= 0 && s[i - longest[i - 1] - 1] == '(') { longest[i] = longest[i - 1] + 2 + ((i - longest[i - 1] - 2 >= 0) ? longest[i - longest[i - 1] - 2] : 0); curMax = Math.Max(longest[i], curMax); } } return curMax; } // Driver code public static void Main(String[] args) { String str = "((()()"; // Function call Console.Write(findMaxLen(str) + "\n"); str = "()(()))))"; // Function call Console.Write(findMaxLen(str) + "\n"); }} // This code is contributed by aashish1995
<script>// javascript program to find length of the longest valid// subString function findMaxLen( s) { if (s.length <= 1) return 0; // Initialize curMax to zero var curMax = 0; var longest = Array(s.length).fill(0); // Iterate over the String starting from second index for (var i = 1; i < s.length; i++) { if (s[i] == ')' && i - longest[i - 1] - 1 >= 0 && s[i - longest[i - 1] - 1] == '(') { longest[i] = longest[i - 1] + 2 + ((i - longest[i - 1] - 2 >= 0) ? longest[i - longest[i - 1] - 2] : 0); curMax = Math.max(longest[i], curMax); } } return curMax; } // Driver code var str = "((()()"; // Function call document.write(findMaxLen(str) + "<br\>"); str = "()(()))))"; // Function call document.write(findMaxLen(str) + "<br\>"); // This code is contributed by umadevi9616</script>
4
6
Thanks to Gaurav Ahirwar and Ekta Goel for suggesting above approach.
Another approach in O(1) auxiliary space and O(N) Time complexity:
The idea to solve this problem is to traverse the string on and keep track of the count of open parentheses and close parentheses with the help of two counters left and right respectively.First, the string is traversed from the left towards the right and for every “(” encountered, the left counter is incremented by 1 and for every “)” the right counter is incremented by 1.Whenever the left becomes equal to right, the length of the current valid string is calculated and if it greater than the current longest substring, then value of required longest substring is updated with current string length.If the right counter becomes greater than the left counter, then the set of parentheses has become invalid and hence the left and right counters are set to 0.After the above process, the string is similarly traversed from right to left and similar procedure is applied.
The idea to solve this problem is to traverse the string on and keep track of the count of open parentheses and close parentheses with the help of two counters left and right respectively.
First, the string is traversed from the left towards the right and for every “(” encountered, the left counter is incremented by 1 and for every “)” the right counter is incremented by 1.
Whenever the left becomes equal to right, the length of the current valid string is calculated and if it greater than the current longest substring, then value of required longest substring is updated with current string length.
If the right counter becomes greater than the left counter, then the set of parentheses has become invalid and hence the left and right counters are set to 0.
After the above process, the string is similarly traversed from right to left and similar procedure is applied.
Below is the implementation of the above approach:
C++
Java
Python3
C#
Javascript
// C++ program to implement the above approach #include <bits/stdc++.h>using namespace std; // Function to return the length of// the longest valid substringint solve(string s, int n){ // Variables for left and right counter. // maxlength to store the maximum length found so far int left = 0, right = 0, maxlength = 0; // Iterating the string from left to right for (int i = 0; i < n; i++) { // If "(" is encountered, // then left counter is incremented // else right counter is incremented if (s[i] == '(') left++; else right++; // Whenever left is equal to right, it signifies // that the subsequence is valid and if (left == right) maxlength = max(maxlength, 2 * right); // Resetting the counters when the subsequence // becomes invalid else if (right > left) left = right = 0; } left = right = 0; // Iterating the string from right to left for (int i = n - 1; i >= 0; i--) { // If "(" is encountered, // then left counter is incremented // else right counter is incremented if (s[i] == '(') left++; else right++; // Whenever left is equal to right, it signifies // that the subsequence is valid and if (left == right) maxlength = max(maxlength, 2 * left); // Resetting the counters when the subsequence // becomes invalid else if (left > right) left = right = 0; } return maxlength;} //A much shorter and concise version of the above codeint solve2(string s, int n){ int left=0,right=0,maxlength=0,t=2; while(t--){ left=0; right=0; for(int i=0;i<n;i++){ if(s[i]=='(')left++; else right++; if(left==right){ maxlength=max(maxlength,2*left); } //when travelling from 0 to n-1 if(t%2==1 && right>left){ left=0; right=0; } //when travelling from n-1 to 0 if(t%2==0 && left>right){ left=0; right=0; } } //now we need to do the same thing from the other side; reverse(s.begin(),s.end()); } return maxlength;} // Driver codeint main(){ // Function call cout << solve("((()()()()(((())", 16); return 0;}
// Java program to implement the above approachimport java.util.Scanner;import java.util.Arrays; class GFG { // Function to return the length // of the longest valid substring public static int solve(String s, int n) { // Variables for left and right // counter maxlength to store // the maximum length found so far int left = 0, right = 0; int maxlength = 0; // Iterating the string from left to right for (int i = 0; i < n; i++) { // If "(" is encountered, then // left counter is incremented // else right counter is incremented if (s.charAt(i) == '(') left++; else right++; // Whenever left is equal to right, // it signifies that the subsequence // is valid and if (left == right) maxlength = Math.max(maxlength, 2 * right); // Resetting the counters when the // subsequence becomes invalid else if (right > left) left = right = 0; } left = right = 0; // Iterating the string from right to left for (int i = n - 1; i >= 0; i--) { // If "(" is encountered, then // left counter is incremented // else right counter is incremented if (s.charAt(i) == '(') left++; else right++; // Whenever left is equal to right, // it signifies that the subsequence // is valid and if (left == right) maxlength = Math.max(maxlength, 2 * left); // Resetting the counters when the // subsequence becomes invalid else if (left > right) left = right = 0; } return maxlength; } // Driver code public static void main(String args[]) { // Function call System.out.print(solve("((()()()()(((())", 16)); }} // This code is contributed by SoumikMondal
# Python3 program to implement the above approach # Function to return the length of# the longest valid substring def solve(s, n): # Variables for left and right counter. # maxlength to store the maximum length found so far left = 0 right = 0 maxlength = 0 # Iterating the string from left to right for i in range(n): # If "(" is encountered, # then left counter is incremented # else right counter is incremented if (s[i] == '('): left += 1 else: right += 1 # Whenever left is equal to right, it signifies # that the subsequence is valid and if (left == right): maxlength = max(maxlength, 2 * right) # Resetting the counters when the subsequence # becomes invalid elif (right > left): left = right = 0 left = right = 0 # Iterating the string from right to left for i in range(n - 1, -1, -1): # If "(" is encountered, # then left counter is incremented # else right counter is incremented if (s[i] == '('): left += 1 else: right += 1 # Whenever left is equal to right, it signifies # that the subsequence is valid and if (left == right): maxlength = max(maxlength, 2 * left) # Resetting the counters when the subsequence # becomes invalid elif (left > right): left = right = 0 return maxlength # Driver code# Function callprint(solve("((()()()()(((())", 16)) # This code is contributed by shubhamsingh10
// C# program to implement the above approachusing System; public class GFG { // Function to return the length // of the longest valid substring public static int solve(String s, int n) { // Variables for left and right // counter maxlength to store // the maximum length found so far int left = 0, right = 0; int maxlength = 0; // Iterating the string from left to right for (int i = 0; i < n; i++) { // If "(" is encountered, then // left counter is incremented // else right counter is incremented if (s[i] == '(') left++; else right++; // Whenever left is equal to right, // it signifies that the subsequence // is valid and if (left == right) maxlength = Math.Max(maxlength, 2 * right); // Resetting the counters when the // subsequence becomes invalid else if (right > left) left = right = 0; } left = right = 0; // Iterating the string from right to left for (int i = n - 1; i >= 0; i--) { // If "(" is encountered, then // left counter is incremented // else right counter is incremented if (s[i] == '(') left++; else right++; // Whenever left is equal to right, // it signifies that the subsequence // is valid and if (left == right) maxlength = Math.Max(maxlength, 2 * left); // Resetting the counters when the // subsequence becomes invalid else if (left > right) left = right = 0; } return maxlength; } // Driver code public static void Main(String []args) { // Function call Console.Write(solve("((()()()()(((())", 16)); }} // This code is contributed by Rajput-Ji
<script> // JavaScript program to implement the above approach // Function to return the length of// the longest valid substringfunction solve(s, n){ // Variables for left and right counter. // maxlength to store the maximum length found so far let left = 0, right = 0, maxlength = 0; // Iterating the string from left to right for (let i = 0; i < n; i++) { // If "(" is encountered, // then left counter is incremented // else right counter is incremented if (s[i] == '(') left++; else right++; // Whenever left is equal to right, it signifies // that the subsequence is valid and if (left == right) maxlength = max(maxlength, 2 * right); // Resetting the counters when the subsequence // becomes invalid else if (right > left) left = right = 0; } left = right = 0; // Iterating the string from right to left for (let i = n - 1; i >= 0; i--) { // If "(" is encountered, // then left counter is incremented // else right counter is incremented if (s[i] == '(') left++; else right++; // Whenever left is equal to right, it signifies // that the subsequence is valid and if (left == right) maxlength = Math.max(maxlength, 2 * left); // Resetting the counters when the subsequence // becomes invalid else if (left > right) left = right = 0; } return maxlength;} // Driver code // Function call document.write( solve("((()()()()(((())", 16)); //This code is contributed by Manoj</script>
8
Length of the longest valid substring | GeeksforGeeks - YouTubeGeeksforGeeks528K subscribersLength of the longest valid substring | GeeksforGeeksWatch laterShareCopy linkInfoShoppingTap to unmuteIf playback doesn't begin shortly, try restarting your device.More videosMore videosYou're signed outVideos you watch may be added to the TV's watch history and influence TV recommendations. To avoid this, cancel and sign in to YouTube on your computer.CancelConfirmSwitch cameraShareInclude playlistAn error occurred while retrieving sharing information. Please try again later.Watch on0:000:000:00 / 5:23•Live•<div class="player-unavailable"><h1 class="message">An error occurred.</h1><div class="submessage"><a href="https://www.youtube.com/watch?v=AIhyd8lMpIo" target="_blank">Try watching this video on www.youtube.com</a>, or enable JavaScript if it is disabled in your browser.</div></div>
Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.
Vipul Lohani
shrikanth13
PranchalKatiyar
guptaakshit21
SHUBHAMSINGH10
SoumikMondal
rsaini9416624750
Rajput-Ji
aashish1995
mank1083
lokeshpotta20
rkstrdee
umadevi9616
amartyaghoshgfg
simmytarika5
Amazon
Google
Dynamic Programming
Queue
Stack
Strings
Amazon
Google
Strings
Dynamic Programming
Stack
Queue
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Find if there is a path between two vertices in an undirected graph
Floyd Warshall Algorithm | DP-16
Bellman–Ford Algorithm | DP-23
Travelling Salesman Problem | Set 1 (Naive and Dynamic Programming)
Matrix Chain Multiplication | DP-8
Breadth First Search or BFS for a Graph
Level Order Binary Tree Traversal
Queue in Python
Queue Interface In Java
Introduction to Data Structures | [
{
"code": null,
"e": 54,
"s": 26,
"text": "\n28 Feb, 2022"
},
{
"code": null,
"e": 176,
"s": 54,
"text": "Given a string consisting of opening and closing parenthesis, find the length of the longest valid parenthesis substring."
},
{
"code": null,
"e": 187,
"s": 176,
"text": "Examples: "
},
{
"code": null,
"e": 323,
"s": 187,
"text": "Input : ((()\nOutput : 2\nExplanation : ()\n\nInput: )()())\nOutput : 4\nExplanation: ()() \n\nInput: ()(()))))\nOutput: 6\nExplanation: ()(())"
},
{
"code": null,
"e": 672,
"s": 323,
"text": "A Simple Approach is to find all the substrings of given string. For every string, check if it is a valid string or not. If valid and length is more than maximum length so far, then update maximum length. We can check whether a substring is valid or not in linear time using a stack (See this for details). Time complexity of this solution is O(n2."
},
{
"code": null,
"e": 945,
"s": 672,
"text": "An Efficient Solution can solve this problem in O(n) time. The idea is to store indexes of previous starting brackets in a stack. The first element of the stack is a special element that provides index before the beginning of valid substring (base for next valid string). "
},
{
"code": null,
"e": 1672,
"s": 945,
"text": "1) Create an empty stack and push -1 to it. \n The first element of the stack is used \n to provide a base for the next valid string. \n\n2) Initialize result as 0.\n\n3) If the character is '(' i.e. str[i] == '('), \n push index'i' to the stack. \n \n2) Else (if the character is ')')\n a) Pop an item from the stack (Most of the \n time an opening bracket)\n b) If the stack is not empty, then find the\n length of current valid substring by taking \n the difference between the current index and\n top of the stack. If current length is more \n than the result, then update the result.\n c) If the stack is empty, push the current index\n as a base for the next valid substring.\n\n3) Return result."
},
{
"code": null,
"e": 1725,
"s": 1672,
"text": "Below is the implementation of the above algorithm. "
},
{
"code": null,
"e": 1729,
"s": 1725,
"text": "C++"
},
{
"code": null,
"e": 1734,
"s": 1729,
"text": "Java"
},
{
"code": null,
"e": 1742,
"s": 1734,
"text": "Python3"
},
{
"code": null,
"e": 1745,
"s": 1742,
"text": "C#"
},
{
"code": null,
"e": 1756,
"s": 1745,
"text": "Javascript"
},
{
"code": "// C++ program to find length of the// longest valid substring#include <bits/stdc++.h>using namespace std; int findMaxLen(string str){ int n = str.length(); // Create a stack and push -1 as // initial index to it. stack<int> stk; stk.push(-1); // Initialize result int result = 0; // Traverse all characters of given string for (int i = 0; i < n; i++) { // If opening bracket, push index of it if (str[i] == '(') stk.push(i); // If closing bracket, i.e.,str[i] = ')' else { // Pop the previous opening // bracket's index if (!stk.empty()) { stk.pop(); } // Check if this length formed with base of // current valid substring is more than max // so far if (!stk.empty()) result = max(result, i - stk.top()); // If stack is empty. push current index as // base for next valid substring (if any) else stk.push(i); } } return result;} // Driver codeint main(){ string str = \"((()()\"; // Function call cout << findMaxLen(str) << endl; str = \"()(()))))\"; // Function call cout << findMaxLen(str) << endl; return 0;}",
"e": 3088,
"s": 1756,
"text": null
},
{
"code": "// Java program to find length of the longest valid// substring import java.util.Stack; class Test{ // method to get length of the longest valid static int findMaxLen(String str) { int n = str.length(); // Create a stack and push -1 // as initial index to it. Stack<Integer> stk = new Stack<>(); stk.push(-1); // Initialize result int result = 0; // Traverse all characters of given string for (int i = 0; i < n; i++) { // If opening bracket, push index of it if (str.charAt(i) == '(') stk.push(i); // // If closing bracket, i.e.,str[i] = ')' else { // Pop the previous // opening bracket's index if(!stk.empty()) stk.pop(); // Check if this length // formed with base of // current valid substring // is more than max // so far if (!stk.empty()) result = Math.max(result, i - stk.peek()); // If stack is empty. push // current index as base // for next valid substring (if any) else stk.push(i); } } return result; } // Driver code public static void main(String[] args) { String str = \"((()()\"; // Function call System.out.println(findMaxLen(str)); str = \"()(()))))\"; // Function call System.out.println(findMaxLen(str)); }}",
"e": 4778,
"s": 3088,
"text": null
},
{
"code": "# Python program to find length of the longest valid# substring def findMaxLen(string): n = len(string) # Create a stack and push -1 # as initial index to it. stk = [] stk.append(-1) # Initialize result result = 0 # Traverse all characters of given string for i in range(n): # If opening bracket, push index of it if string[i] == '(': stk.append(i) # If closing bracket, i.e., str[i] = ')' else: # Pop the previous opening bracket's index if len(stk) != 0: stk.pop() # Check if this length formed with base of # current valid substring is more than max # so far if len(stk) != 0: result = max(result, i - stk[len(stk)-1]) # If stack is empty. push current index as # base for next valid substring (if any) else: stk.append(i) return result # Driver codestring = \"((()()\" # Function callprint (findMaxLen(string)) string = \"()(()))))\" # Function callprint (findMaxLen(string)) # This code is contributed by Bhavya Jain",
"e": 5957,
"s": 4778,
"text": null
},
{
"code": "// C# program to find length of// the longest valid substringusing System;using System.Collections.Generic; class GFG { // method to get length of // the longest valid public static int findMaxLen(string str) { int n = str.Length; // Create a stack and push -1 as // initial index to it. Stack<int> stk = new Stack<int>(); stk.Push(-1); // Initialize result int result = 0; // Traverse all characters of // given string for (int i = 0; i < n; i++) { // If opening bracket, push // index of it if (str[i] == '(') { stk.Push(i); } else // If closing bracket, // i.e.,str[i] = ')' { // Pop the previous opening // bracket's index if (stk.Count > 0) stk.Pop(); // Check if this length formed // with base of current valid // substring is more than max // so far if (stk.Count > 0) { result = Math.Max(result, i - stk.Peek()); } // If stack is empty. push current // index as base for next valid // substring (if any) else { stk.Push(i); } } } return result; } // Driver Code public static void Main(string[] args) { string str = \"((()()\"; // Function call Console.WriteLine(findMaxLen(str)); str = \"()(()))))\"; // Function call Console.WriteLine(findMaxLen(str)); }} // This code is contributed by Shrikant13",
"e": 7792,
"s": 5957,
"text": null
},
{
"code": "<script> // JavaScript Program for the above approach function findMaxLen(str) { let n = str.length; // Create a stack and push -1 as // initial index to it. let stk = []; stk.push(-1); // Initialize result let result = 0; // Traverse all characters of given string for (let i = 0; i < n; i++) { // If opening bracket, push index of it if (str.charAt(i) == '(') { stk.push(i); } // If closing bracket, i.e.,str[i] = ')' else { // Pop the previous opening // bracket's index if (stk.length != 0) { stk.pop(); } // Check if this length formed with base of // current valid substring is more than max // so far if (stk.length != 0) { result = Math.max(result, i - stk[stk.length - 1]); } // If stack is empty. push current index as // base for next valid substring (if any) else { stk.push(i); } } } return result; } // Driver code let str = \"((()()\"; // Function call document.write(findMaxLen(str) + \"<br>\"); str = \"()(()))))\"; // Function call document.write(findMaxLen(str) + \"<br>\"); // This code is contributed by Potta Lokesh </script>",
"e": 9498,
"s": 7792,
"text": null
},
{
"code": null,
"e": 9505,
"s": 9501,
"text": "4\n6"
},
{
"code": null,
"e": 9534,
"s": 9507,
"text": "Explanation with example: "
},
{
"code": null,
"e": 10316,
"s": 9536,
"text": "Input: str = \"(()()\"\n\nInitialize result as 0 and stack with one item -1.\n\nFor i = 0, str[0] = '(', we push 0 in stack\n\nFor i = 1, str[1] = '(', we push 1 in stack\n\nFor i = 2, str[2] = ')', currently stack has \n[-1, 0, 1], we pop from the stack and the stack\nnow is [-1, 0] and length of current valid substring \nbecomes 2 (we get this 2 by subtracting stack top from \ncurrent index).\n\nSince the current length is more than the current result, \nwe update the result.\n\nFor i = 3, str[3] = '(', we push again, stack is [-1, 0, 3].\nFor i = 4, str[4] = ')', we pop from the stack, stack \nbecomes [-1, 0] and length of current valid substring \nbecomes 4 (we get this 4 by subtracting stack top from \ncurrent index). \nSince current length is more than current result,\nwe update result. "
},
{
"code": null,
"e": 10549,
"s": 10318,
"text": "Another Efficient Approach can solve the problem in O(n) time. The idea is to maintain an array that stores the length of the longest valid substring ending at that index. We iterate through the array and return the maximum value."
},
{
"code": null,
"e": 11193,
"s": 10551,
"text": "1) Create an array longest of length n (size of the input\n string) initialized to zero.\n The array will store the length of the longest valid \n substring ending at that index.\n\n2) Initialize result as 0.\n\n3) Iterate through the string from second character\n a) If the character is '(' set longest[i]=0 as no \n valid sub-string will end with '('.\n b) Else\n i) if s[i-1] = '('\n set longest[i] = longest[i-2] + 2\n ii) else\n set longest[i] = longest[i-1] + 2 + \n longest[i-longest[i-1]-2]\n\n4) In each iteration update result as the maximum of \n result and longest[i]\n\n5) Return result."
},
{
"code": null,
"e": 11250,
"s": 11195,
"text": "Below is the implementations of the above algorithm. "
},
{
"code": null,
"e": 11256,
"s": 11252,
"text": "C++"
},
{
"code": null,
"e": 11261,
"s": 11256,
"text": "Java"
},
{
"code": null,
"e": 11269,
"s": 11261,
"text": "Python3"
},
{
"code": null,
"e": 11272,
"s": 11269,
"text": "C#"
},
{
"code": null,
"e": 11283,
"s": 11272,
"text": "Javascript"
},
{
"code": "// C++ program to find length of the longest valid// substring#include <bits/stdc++.h>using namespace std; int findMaxLen(string s){ if (s.length() <= 1) return 0; // Initialize curMax to zero int curMax = 0; vector<int> longest(s.size(), 0); // Iterate over the string starting from second index for (int i = 1; i < s.length(); i++) { if (s[i] == ')' && i - longest[i - 1] - 1 >= 0 && s[i - longest[i - 1] - 1] == '(') { longest[i] = longest[i - 1] + 2 + ((i - longest[i - 1] - 2 >= 0) ? longest[i - longest[i - 1] - 2] : 0); curMax = max(longest[i], curMax); } } return curMax;} // Driver codeint main(){ string str = \"((()()\"; // Function call cout << findMaxLen(str) << endl; str = \"()(()))))\"; // Function call cout << findMaxLen(str) << endl; return 0;}// This code is contributed by Vipul Lohani",
"e": 12272,
"s": 11283,
"text": null
},
{
"code": "// Java program to find length of the longest valid// subStringimport java.util.*;class GFG{ static int findMaxLen(String s) { if (s.length() <= 1) return 0; // Initialize curMax to zero int curMax = 0; int[] longest = new int[s.length()]; // Iterate over the String starting from second index for (int i = 1; i < s.length(); i++) { if (s.charAt(i) == ')' && i - longest[i - 1] - 1 >= 0 && s.charAt(i - longest[i - 1] - 1) == '(') { longest[i] = longest[i - 1] + 2 + ((i - longest[i - 1] - 2 >= 0) ? longest[i - longest[i - 1] - 2] : 0); curMax = Math.max(longest[i], curMax); } } return curMax; } // Driver code public static void main(String[] args) { String str = \"((()()\"; // Function call System.out.print(findMaxLen(str) +\"\\n\"); str = \"()(()))))\"; // Function call System.out.print(findMaxLen(str) +\"\\n\"); }} // This code is contributed by aashish1995",
"e": 13275,
"s": 12272,
"text": null
},
{
"code": "# Python3 program to find length of# the longest valid substring def findMaxLen(s): if (len(s) <= 1): return 0 # Initialize curMax to zero curMax = 0 longest = [0] * (len(s)) # Iterate over the string starting # from second index for i in range(1, len(s)): if ((s[i] == ')' and i - longest[i - 1] - 1 >= 0 and s[i - longest[i - 1] - 1] == '(')): longest[i] = longest[i - 1] + 2 if (i - longest[i - 1] - 2 >= 0): longest[i] += (longest[i - longest[i - 1] - 2]) else: longest[i] += 0 curMax = max(longest[i], curMax) return curMax # Driver Codeif __name__ == '__main__': Str = \"((()()\" # Function call print(findMaxLen(Str)) Str = \"()(()))))\" # Function call print(findMaxLen(Str)) # This code is contributed by PranchalK",
"e": 14216,
"s": 13275,
"text": null
},
{
"code": "// C# program to find length of the longest valid// subStringusing System; public class GFG { static int findMaxLen(String s) { if (s.Length <= 1) return 0; // Initialize curMax to zero int curMax = 0; int[] longest = new int[s.Length]; // Iterate over the String starting from second index for (int i = 1; i < s.Length; i++) { if (s[i] == ')' && i - longest[i - 1] - 1 >= 0 && s[i - longest[i - 1] - 1] == '(') { longest[i] = longest[i - 1] + 2 + ((i - longest[i - 1] - 2 >= 0) ? longest[i - longest[i - 1] - 2] : 0); curMax = Math.Max(longest[i], curMax); } } return curMax; } // Driver code public static void Main(String[] args) { String str = \"((()()\"; // Function call Console.Write(findMaxLen(str) + \"\\n\"); str = \"()(()))))\"; // Function call Console.Write(findMaxLen(str) + \"\\n\"); }} // This code is contributed by aashish1995",
"e": 15234,
"s": 14216,
"text": null
},
{
"code": "<script>// javascript program to find length of the longest valid// subString function findMaxLen( s) { if (s.length <= 1) return 0; // Initialize curMax to zero var curMax = 0; var longest = Array(s.length).fill(0); // Iterate over the String starting from second index for (var i = 1; i < s.length; i++) { if (s[i] == ')' && i - longest[i - 1] - 1 >= 0 && s[i - longest[i - 1] - 1] == '(') { longest[i] = longest[i - 1] + 2 + ((i - longest[i - 1] - 2 >= 0) ? longest[i - longest[i - 1] - 2] : 0); curMax = Math.max(longest[i], curMax); } } return curMax; } // Driver code var str = \"((()()\"; // Function call document.write(findMaxLen(str) + \"<br\\>\"); str = \"()(()))))\"; // Function call document.write(findMaxLen(str) + \"<br\\>\"); // This code is contributed by umadevi9616</script>",
"e": 16195,
"s": 15234,
"text": null
},
{
"code": null,
"e": 16199,
"s": 16195,
"text": "4\n6"
},
{
"code": null,
"e": 16269,
"s": 16199,
"text": "Thanks to Gaurav Ahirwar and Ekta Goel for suggesting above approach."
},
{
"code": null,
"e": 16337,
"s": 16269,
"text": "Another approach in O(1) auxiliary space and O(N) Time complexity: "
},
{
"code": null,
"e": 17210,
"s": 16337,
"text": "The idea to solve this problem is to traverse the string on and keep track of the count of open parentheses and close parentheses with the help of two counters left and right respectively.First, the string is traversed from the left towards the right and for every “(” encountered, the left counter is incremented by 1 and for every “)” the right counter is incremented by 1.Whenever the left becomes equal to right, the length of the current valid string is calculated and if it greater than the current longest substring, then value of required longest substring is updated with current string length.If the right counter becomes greater than the left counter, then the set of parentheses has become invalid and hence the left and right counters are set to 0.After the above process, the string is similarly traversed from right to left and similar procedure is applied."
},
{
"code": null,
"e": 17399,
"s": 17210,
"text": "The idea to solve this problem is to traverse the string on and keep track of the count of open parentheses and close parentheses with the help of two counters left and right respectively."
},
{
"code": null,
"e": 17587,
"s": 17399,
"text": "First, the string is traversed from the left towards the right and for every “(” encountered, the left counter is incremented by 1 and for every “)” the right counter is incremented by 1."
},
{
"code": null,
"e": 17816,
"s": 17587,
"text": "Whenever the left becomes equal to right, the length of the current valid string is calculated and if it greater than the current longest substring, then value of required longest substring is updated with current string length."
},
{
"code": null,
"e": 17975,
"s": 17816,
"text": "If the right counter becomes greater than the left counter, then the set of parentheses has become invalid and hence the left and right counters are set to 0."
},
{
"code": null,
"e": 18087,
"s": 17975,
"text": "After the above process, the string is similarly traversed from right to left and similar procedure is applied."
},
{
"code": null,
"e": 18139,
"s": 18087,
"text": "Below is the implementation of the above approach: "
},
{
"code": null,
"e": 18143,
"s": 18139,
"text": "C++"
},
{
"code": null,
"e": 18148,
"s": 18143,
"text": "Java"
},
{
"code": null,
"e": 18156,
"s": 18148,
"text": "Python3"
},
{
"code": null,
"e": 18159,
"s": 18156,
"text": "C#"
},
{
"code": null,
"e": 18170,
"s": 18159,
"text": "Javascript"
},
{
"code": "// C++ program to implement the above approach #include <bits/stdc++.h>using namespace std; // Function to return the length of// the longest valid substringint solve(string s, int n){ // Variables for left and right counter. // maxlength to store the maximum length found so far int left = 0, right = 0, maxlength = 0; // Iterating the string from left to right for (int i = 0; i < n; i++) { // If \"(\" is encountered, // then left counter is incremented // else right counter is incremented if (s[i] == '(') left++; else right++; // Whenever left is equal to right, it signifies // that the subsequence is valid and if (left == right) maxlength = max(maxlength, 2 * right); // Resetting the counters when the subsequence // becomes invalid else if (right > left) left = right = 0; } left = right = 0; // Iterating the string from right to left for (int i = n - 1; i >= 0; i--) { // If \"(\" is encountered, // then left counter is incremented // else right counter is incremented if (s[i] == '(') left++; else right++; // Whenever left is equal to right, it signifies // that the subsequence is valid and if (left == right) maxlength = max(maxlength, 2 * left); // Resetting the counters when the subsequence // becomes invalid else if (left > right) left = right = 0; } return maxlength;} //A much shorter and concise version of the above codeint solve2(string s, int n){ int left=0,right=0,maxlength=0,t=2; while(t--){ left=0; right=0; for(int i=0;i<n;i++){ if(s[i]=='(')left++; else right++; if(left==right){ maxlength=max(maxlength,2*left); } //when travelling from 0 to n-1 if(t%2==1 && right>left){ left=0; right=0; } //when travelling from n-1 to 0 if(t%2==0 && left>right){ left=0; right=0; } } //now we need to do the same thing from the other side; reverse(s.begin(),s.end()); } return maxlength;} // Driver codeint main(){ // Function call cout << solve(\"((()()()()(((())\", 16); return 0;}",
"e": 20665,
"s": 18170,
"text": null
},
{
"code": "// Java program to implement the above approachimport java.util.Scanner;import java.util.Arrays; class GFG { // Function to return the length // of the longest valid substring public static int solve(String s, int n) { // Variables for left and right // counter maxlength to store // the maximum length found so far int left = 0, right = 0; int maxlength = 0; // Iterating the string from left to right for (int i = 0; i < n; i++) { // If \"(\" is encountered, then // left counter is incremented // else right counter is incremented if (s.charAt(i) == '(') left++; else right++; // Whenever left is equal to right, // it signifies that the subsequence // is valid and if (left == right) maxlength = Math.max(maxlength, 2 * right); // Resetting the counters when the // subsequence becomes invalid else if (right > left) left = right = 0; } left = right = 0; // Iterating the string from right to left for (int i = n - 1; i >= 0; i--) { // If \"(\" is encountered, then // left counter is incremented // else right counter is incremented if (s.charAt(i) == '(') left++; else right++; // Whenever left is equal to right, // it signifies that the subsequence // is valid and if (left == right) maxlength = Math.max(maxlength, 2 * left); // Resetting the counters when the // subsequence becomes invalid else if (left > right) left = right = 0; } return maxlength; } // Driver code public static void main(String args[]) { // Function call System.out.print(solve(\"((()()()()(((())\", 16)); }} // This code is contributed by SoumikMondal",
"e": 22794,
"s": 20665,
"text": null
},
{
"code": "# Python3 program to implement the above approach # Function to return the length of# the longest valid substring def solve(s, n): # Variables for left and right counter. # maxlength to store the maximum length found so far left = 0 right = 0 maxlength = 0 # Iterating the string from left to right for i in range(n): # If \"(\" is encountered, # then left counter is incremented # else right counter is incremented if (s[i] == '('): left += 1 else: right += 1 # Whenever left is equal to right, it signifies # that the subsequence is valid and if (left == right): maxlength = max(maxlength, 2 * right) # Resetting the counters when the subsequence # becomes invalid elif (right > left): left = right = 0 left = right = 0 # Iterating the string from right to left for i in range(n - 1, -1, -1): # If \"(\" is encountered, # then left counter is incremented # else right counter is incremented if (s[i] == '('): left += 1 else: right += 1 # Whenever left is equal to right, it signifies # that the subsequence is valid and if (left == right): maxlength = max(maxlength, 2 * left) # Resetting the counters when the subsequence # becomes invalid elif (left > right): left = right = 0 return maxlength # Driver code# Function callprint(solve(\"((()()()()(((())\", 16)) # This code is contributed by shubhamsingh10",
"e": 24385,
"s": 22794,
"text": null
},
{
"code": "// C# program to implement the above approachusing System; public class GFG { // Function to return the length // of the longest valid substring public static int solve(String s, int n) { // Variables for left and right // counter maxlength to store // the maximum length found so far int left = 0, right = 0; int maxlength = 0; // Iterating the string from left to right for (int i = 0; i < n; i++) { // If \"(\" is encountered, then // left counter is incremented // else right counter is incremented if (s[i] == '(') left++; else right++; // Whenever left is equal to right, // it signifies that the subsequence // is valid and if (left == right) maxlength = Math.Max(maxlength, 2 * right); // Resetting the counters when the // subsequence becomes invalid else if (right > left) left = right = 0; } left = right = 0; // Iterating the string from right to left for (int i = n - 1; i >= 0; i--) { // If \"(\" is encountered, then // left counter is incremented // else right counter is incremented if (s[i] == '(') left++; else right++; // Whenever left is equal to right, // it signifies that the subsequence // is valid and if (left == right) maxlength = Math.Max(maxlength, 2 * left); // Resetting the counters when the // subsequence becomes invalid else if (left > right) left = right = 0; } return maxlength; } // Driver code public static void Main(String []args) { // Function call Console.Write(solve(\"((()()()()(((())\", 16)); }} // This code is contributed by Rajput-Ji",
"e": 26162,
"s": 24385,
"text": null
},
{
"code": "<script> // JavaScript program to implement the above approach // Function to return the length of// the longest valid substringfunction solve(s, n){ // Variables for left and right counter. // maxlength to store the maximum length found so far let left = 0, right = 0, maxlength = 0; // Iterating the string from left to right for (let i = 0; i < n; i++) { // If \"(\" is encountered, // then left counter is incremented // else right counter is incremented if (s[i] == '(') left++; else right++; // Whenever left is equal to right, it signifies // that the subsequence is valid and if (left == right) maxlength = max(maxlength, 2 * right); // Resetting the counters when the subsequence // becomes invalid else if (right > left) left = right = 0; } left = right = 0; // Iterating the string from right to left for (let i = n - 1; i >= 0; i--) { // If \"(\" is encountered, // then left counter is incremented // else right counter is incremented if (s[i] == '(') left++; else right++; // Whenever left is equal to right, it signifies // that the subsequence is valid and if (left == right) maxlength = Math.max(maxlength, 2 * left); // Resetting the counters when the subsequence // becomes invalid else if (left > right) left = right = 0; } return maxlength;} // Driver code // Function call document.write( solve(\"((()()()()(((())\", 16)); //This code is contributed by Manoj</script>",
"e": 27846,
"s": 26162,
"text": null
},
{
"code": null,
"e": 27848,
"s": 27846,
"text": "8"
},
{
"code": null,
"e": 28740,
"s": 27848,
"text": "Length of the longest valid substring | GeeksforGeeks - YouTubeGeeksforGeeks528K subscribersLength of the longest valid substring | GeeksforGeeksWatch laterShareCopy linkInfoShoppingTap to unmuteIf playback doesn't begin shortly, try restarting your device.More videosMore videosYou're signed outVideos you watch may be added to the TV's watch history and influence TV recommendations. To avoid this, cancel and sign in to YouTube on your computer.CancelConfirmSwitch cameraShareInclude playlistAn error occurred while retrieving sharing information. Please try again later.Watch on0:000:000:00 / 5:23•Live•<div class=\"player-unavailable\"><h1 class=\"message\">An error occurred.</h1><div class=\"submessage\"><a href=\"https://www.youtube.com/watch?v=AIhyd8lMpIo\" target=\"_blank\">Try watching this video on www.youtube.com</a>, or enable JavaScript if it is disabled in your browser.</div></div>"
},
{
"code": null,
"e": 28866,
"s": 28740,
"text": "Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above. "
},
{
"code": null,
"e": 28879,
"s": 28866,
"text": "Vipul Lohani"
},
{
"code": null,
"e": 28891,
"s": 28879,
"text": "shrikanth13"
},
{
"code": null,
"e": 28907,
"s": 28891,
"text": "PranchalKatiyar"
},
{
"code": null,
"e": 28921,
"s": 28907,
"text": "guptaakshit21"
},
{
"code": null,
"e": 28936,
"s": 28921,
"text": "SHUBHAMSINGH10"
},
{
"code": null,
"e": 28949,
"s": 28936,
"text": "SoumikMondal"
},
{
"code": null,
"e": 28966,
"s": 28949,
"text": "rsaini9416624750"
},
{
"code": null,
"e": 28976,
"s": 28966,
"text": "Rajput-Ji"
},
{
"code": null,
"e": 28988,
"s": 28976,
"text": "aashish1995"
},
{
"code": null,
"e": 28997,
"s": 28988,
"text": "mank1083"
},
{
"code": null,
"e": 29011,
"s": 28997,
"text": "lokeshpotta20"
},
{
"code": null,
"e": 29020,
"s": 29011,
"text": "rkstrdee"
},
{
"code": null,
"e": 29032,
"s": 29020,
"text": "umadevi9616"
},
{
"code": null,
"e": 29048,
"s": 29032,
"text": "amartyaghoshgfg"
},
{
"code": null,
"e": 29061,
"s": 29048,
"text": "simmytarika5"
},
{
"code": null,
"e": 29068,
"s": 29061,
"text": "Amazon"
},
{
"code": null,
"e": 29075,
"s": 29068,
"text": "Google"
},
{
"code": null,
"e": 29095,
"s": 29075,
"text": "Dynamic Programming"
},
{
"code": null,
"e": 29101,
"s": 29095,
"text": "Queue"
},
{
"code": null,
"e": 29107,
"s": 29101,
"text": "Stack"
},
{
"code": null,
"e": 29115,
"s": 29107,
"text": "Strings"
},
{
"code": null,
"e": 29122,
"s": 29115,
"text": "Amazon"
},
{
"code": null,
"e": 29129,
"s": 29122,
"text": "Google"
},
{
"code": null,
"e": 29137,
"s": 29129,
"text": "Strings"
},
{
"code": null,
"e": 29157,
"s": 29137,
"text": "Dynamic Programming"
},
{
"code": null,
"e": 29163,
"s": 29157,
"text": "Stack"
},
{
"code": null,
"e": 29169,
"s": 29163,
"text": "Queue"
},
{
"code": null,
"e": 29267,
"s": 29169,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 29335,
"s": 29267,
"text": "Find if there is a path between two vertices in an undirected graph"
},
{
"code": null,
"e": 29368,
"s": 29335,
"text": "Floyd Warshall Algorithm | DP-16"
},
{
"code": null,
"e": 29399,
"s": 29368,
"text": "Bellman–Ford Algorithm | DP-23"
},
{
"code": null,
"e": 29467,
"s": 29399,
"text": "Travelling Salesman Problem | Set 1 (Naive and Dynamic Programming)"
},
{
"code": null,
"e": 29502,
"s": 29467,
"text": "Matrix Chain Multiplication | DP-8"
},
{
"code": null,
"e": 29542,
"s": 29502,
"text": "Breadth First Search or BFS for a Graph"
},
{
"code": null,
"e": 29576,
"s": 29542,
"text": "Level Order Binary Tree Traversal"
},
{
"code": null,
"e": 29592,
"s": 29576,
"text": "Queue in Python"
},
{
"code": null,
"e": 29616,
"s": 29592,
"text": "Queue Interface In Java"
}
] |
JavaScript | Math.round( ) function | 09 Feb, 2022
The Math.round() function in JavaScript is used to round the number passed as parameter to its nearest integer.Syntax
Math.round(value)
Parameters :
The number to be rounded to its nearest integer.
Returns :
Result after rounding the number passed as a parameter to the function passed as parameter.
Below are some examples to illustrate the Math.round() function:
Rounding Off a number to its nearest integer: To round off a number to its nearest integer, the math.round() function should be implemented in the following way:<script type="text/javascript"> var round =Math.round(5.8); document.write("Number after rounding : " + round); </script>Output:Number after rounding : 6Rounding Off a negative number to its nearest integer: The Math.round() function itself rounds off a negative number when passed as parameter to it. To round off a negative number to its nearest integer, the Math.round() function should be implemented in the following way:<script type="text/javascript"> var round =Math.round(-5.8); document.write("Number after rounding : " + round); </script>Output:Number after rounding : -6Math.round() function, when parameter has “.5” as decimal: Below program shows the result of Math.round() function when the parameter has “.5” in decimal.<script type="text/javascript"> var round =Math.round(-12.5); document.write("Number after rounding : " + round); var round =Math.round(12.51); document.write("Number after rounding : " + round); </script>Output:Number after rounding : -12
Number after rounding : 13
Rounding Off a number to its nearest integer: To round off a number to its nearest integer, the math.round() function should be implemented in the following way:<script type="text/javascript"> var round =Math.round(5.8); document.write("Number after rounding : " + round); </script>Output:Number after rounding : 6
<script type="text/javascript"> var round =Math.round(5.8); document.write("Number after rounding : " + round); </script>
Output:
Number after rounding : 6
Rounding Off a negative number to its nearest integer: The Math.round() function itself rounds off a negative number when passed as parameter to it. To round off a negative number to its nearest integer, the Math.round() function should be implemented in the following way:<script type="text/javascript"> var round =Math.round(-5.8); document.write("Number after rounding : " + round); </script>Output:Number after rounding : -6
<script type="text/javascript"> var round =Math.round(-5.8); document.write("Number after rounding : " + round); </script>
Output:
Number after rounding : -6
Math.round() function, when parameter has “.5” as decimal: Below program shows the result of Math.round() function when the parameter has “.5” in decimal.<script type="text/javascript"> var round =Math.round(-12.5); document.write("Number after rounding : " + round); var round =Math.round(12.51); document.write("Number after rounding : " + round); </script>Output:Number after rounding : -12
Number after rounding : 13
<script type="text/javascript"> var round =Math.round(-12.5); document.write("Number after rounding : " + round); var round =Math.round(12.51); document.write("Number after rounding : " + round); </script>
Output:
Number after rounding : -12
Number after rounding : 13
Errors and Exceptions1. A non-numeric string passed as parameter returns NaN2. An array with more than 1 integer passed as parameter returns NaN3. An empty variable passed as parameter returns NaN4. An empty string passed as parameter returns NaN5. An empty array passed as parameter returns NaN
Below are some examples that illustrate the Math.floor() function in JavaScript:
<!-- NEGATIVE NUMBER EXAMPLE --><script type="text/javascript"> document.write(Math.round(-2)); document.write(Math.round(-2.56)); </script>
Output:
-2
-3
<!-- POSITIVE NUMBER EXAMPLE --><script type="text/javascript"> document.write(Math.round(2)); document.write(Math.round(2.56)); </script>
Output:
2
3
<!-- STRING EXAMPLE --><script type="text/javascript"> document.write(Math.floor("Geeksforgeeks")); </script>
Output:
NaN
<!-- ADDITION INSIDE FUNCTION EXAMPLE --><script type="text/javascript"> document.write(Math.floor(7.2+9.3)); </script>
Output:
17
Supported Browsers:
Chrome 1 and above
Edge 12 and above
Firefox 1 and above
Internet Explorer 3 and above
Opera 3 and above
Safari 1 and above
ysachin2314
javascript-math
JavaScript
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here. | [
{
"code": null,
"e": 28,
"s": 0,
"text": "\n09 Feb, 2022"
},
{
"code": null,
"e": 146,
"s": 28,
"text": "The Math.round() function in JavaScript is used to round the number passed as parameter to its nearest integer.Syntax"
},
{
"code": null,
"e": 164,
"s": 146,
"text": "Math.round(value)"
},
{
"code": null,
"e": 177,
"s": 164,
"text": "Parameters :"
},
{
"code": null,
"e": 226,
"s": 177,
"text": "The number to be rounded to its nearest integer."
},
{
"code": null,
"e": 236,
"s": 226,
"text": "Returns :"
},
{
"code": null,
"e": 328,
"s": 236,
"text": "Result after rounding the number passed as a parameter to the function passed as parameter."
},
{
"code": null,
"e": 393,
"s": 328,
"text": "Below are some examples to illustrate the Math.round() function:"
},
{
"code": null,
"e": 1580,
"s": 393,
"text": "Rounding Off a number to its nearest integer: To round off a number to its nearest integer, the math.round() function should be implemented in the following way:<script type=\"text/javascript\"> var round =Math.round(5.8); document.write(\"Number after rounding : \" + round); </script>Output:Number after rounding : 6Rounding Off a negative number to its nearest integer: The Math.round() function itself rounds off a negative number when passed as parameter to it. To round off a negative number to its nearest integer, the Math.round() function should be implemented in the following way:<script type=\"text/javascript\"> var round =Math.round(-5.8); document.write(\"Number after rounding : \" + round); </script>Output:Number after rounding : -6Math.round() function, when parameter has “.5” as decimal: Below program shows the result of Math.round() function when the parameter has “.5” in decimal.<script type=\"text/javascript\"> var round =Math.round(-12.5); document.write(\"Number after rounding : \" + round); var round =Math.round(12.51); document.write(\"Number after rounding : \" + round); </script>Output:Number after rounding : -12\nNumber after rounding : 13"
},
{
"code": null,
"e": 1901,
"s": 1580,
"text": "Rounding Off a number to its nearest integer: To round off a number to its nearest integer, the math.round() function should be implemented in the following way:<script type=\"text/javascript\"> var round =Math.round(5.8); document.write(\"Number after rounding : \" + round); </script>Output:Number after rounding : 6"
},
{
"code": "<script type=\"text/javascript\"> var round =Math.round(5.8); document.write(\"Number after rounding : \" + round); </script>",
"e": 2029,
"s": 1901,
"text": null
},
{
"code": null,
"e": 2037,
"s": 2029,
"text": "Output:"
},
{
"code": null,
"e": 2063,
"s": 2037,
"text": "Number after rounding : 6"
},
{
"code": null,
"e": 2498,
"s": 2063,
"text": "Rounding Off a negative number to its nearest integer: The Math.round() function itself rounds off a negative number when passed as parameter to it. To round off a negative number to its nearest integer, the Math.round() function should be implemented in the following way:<script type=\"text/javascript\"> var round =Math.round(-5.8); document.write(\"Number after rounding : \" + round); </script>Output:Number after rounding : -6"
},
{
"code": "<script type=\"text/javascript\"> var round =Math.round(-5.8); document.write(\"Number after rounding : \" + round); </script>",
"e": 2627,
"s": 2498,
"text": null
},
{
"code": null,
"e": 2635,
"s": 2627,
"text": "Output:"
},
{
"code": null,
"e": 2662,
"s": 2635,
"text": "Number after rounding : -6"
},
{
"code": null,
"e": 3095,
"s": 2662,
"text": "Math.round() function, when parameter has “.5” as decimal: Below program shows the result of Math.round() function when the parameter has “.5” in decimal.<script type=\"text/javascript\"> var round =Math.round(-12.5); document.write(\"Number after rounding : \" + round); var round =Math.round(12.51); document.write(\"Number after rounding : \" + round); </script>Output:Number after rounding : -12\nNumber after rounding : 13"
},
{
"code": "<script type=\"text/javascript\"> var round =Math.round(-12.5); document.write(\"Number after rounding : \" + round); var round =Math.round(12.51); document.write(\"Number after rounding : \" + round); </script>",
"e": 3313,
"s": 3095,
"text": null
},
{
"code": null,
"e": 3321,
"s": 3313,
"text": "Output:"
},
{
"code": null,
"e": 3376,
"s": 3321,
"text": "Number after rounding : -12\nNumber after rounding : 13"
},
{
"code": null,
"e": 3672,
"s": 3376,
"text": "Errors and Exceptions1. A non-numeric string passed as parameter returns NaN2. An array with more than 1 integer passed as parameter returns NaN3. An empty variable passed as parameter returns NaN4. An empty string passed as parameter returns NaN5. An empty array passed as parameter returns NaN"
},
{
"code": null,
"e": 3753,
"s": 3672,
"text": "Below are some examples that illustrate the Math.floor() function in JavaScript:"
},
{
"code": "<!-- NEGATIVE NUMBER EXAMPLE --><script type=\"text/javascript\"> document.write(Math.round(-2)); document.write(Math.round(-2.56)); </script>",
"e": 3910,
"s": 3753,
"text": null
},
{
"code": null,
"e": 3918,
"s": 3910,
"text": "Output:"
},
{
"code": null,
"e": 3925,
"s": 3918,
"text": "-2\n-3\n"
},
{
"code": "<!-- POSITIVE NUMBER EXAMPLE --><script type=\"text/javascript\"> document.write(Math.round(2)); document.write(Math.round(2.56)); </script>",
"e": 4080,
"s": 3925,
"text": null
},
{
"code": null,
"e": 4088,
"s": 4080,
"text": "Output:"
},
{
"code": null,
"e": 4093,
"s": 4088,
"text": "2\n3\n"
},
{
"code": "<!-- STRING EXAMPLE --><script type=\"text/javascript\"> document.write(Math.floor(\"Geeksforgeeks\")); </script>",
"e": 4215,
"s": 4093,
"text": null
},
{
"code": null,
"e": 4223,
"s": 4215,
"text": "Output:"
},
{
"code": null,
"e": 4228,
"s": 4223,
"text": "NaN\n"
},
{
"code": "<!-- ADDITION INSIDE FUNCTION EXAMPLE --><script type=\"text/javascript\"> document.write(Math.floor(7.2+9.3)); </script>",
"e": 4361,
"s": 4228,
"text": null
},
{
"code": null,
"e": 4369,
"s": 4361,
"text": "Output:"
},
{
"code": null,
"e": 4373,
"s": 4369,
"text": "17\n"
},
{
"code": null,
"e": 4393,
"s": 4373,
"text": "Supported Browsers:"
},
{
"code": null,
"e": 4412,
"s": 4393,
"text": "Chrome 1 and above"
},
{
"code": null,
"e": 4430,
"s": 4412,
"text": "Edge 12 and above"
},
{
"code": null,
"e": 4450,
"s": 4430,
"text": "Firefox 1 and above"
},
{
"code": null,
"e": 4480,
"s": 4450,
"text": "Internet Explorer 3 and above"
},
{
"code": null,
"e": 4498,
"s": 4480,
"text": "Opera 3 and above"
},
{
"code": null,
"e": 4517,
"s": 4498,
"text": "Safari 1 and above"
},
{
"code": null,
"e": 4529,
"s": 4517,
"text": "ysachin2314"
},
{
"code": null,
"e": 4545,
"s": 4529,
"text": "javascript-math"
},
{
"code": null,
"e": 4556,
"s": 4545,
"text": "JavaScript"
}
] |
Communication between two process using signals in C | 31 Jan, 2019
Prerequisite : C signal handling
In this post, the communication between child and parent processes is done using kill() and signal(), fork() system call.
fork() creates the child process from the parent. The pid can be checked to decide whether it is the child (if pid == 0) or the parent (pid = child process id).
The parent can then send messages to child using the pid and kill().
The child picks up these signals with signal() and calls appropriate functions.
Example of how 2 processes can talk to each other using kill() and signal():
// C program to implement sighup(), sigint()// and sigquit() signal functions#include <signal.h>#include <stdio.h>#include <stdlib.h>#include <sys/types.h>#include <unistd.h> // function declarationvoid sighup();void sigint();void sigquit(); // driver codevoid main(){ int pid; /* get child process */ if ((pid = fork()) < 0) { perror("fork"); exit(1); } if (pid == 0) { /* child */ signal(SIGHUP, sighup); signal(SIGINT, sigint); signal(SIGQUIT, sigquit); for (;;) ; /* loop for ever */ } else /* parent */ { /* pid hold id of child */ printf("\nPARENT: sending SIGHUP\n\n"); kill(pid, SIGHUP); sleep(3); /* pause for 3 secs */ printf("\nPARENT: sending SIGINT\n\n"); kill(pid, SIGINT); sleep(3); /* pause for 3 secs */ printf("\nPARENT: sending SIGQUIT\n\n"); kill(pid, SIGQUIT); sleep(3); }} // sighup() function definitionvoid sighup() { signal(SIGHUP, sighup); /* reset signal */ printf("CHILD: I have received a SIGHUP\n");} // sigint() function definitionvoid sigint() { signal(SIGINT, sigint); /* reset signal */ printf("CHILD: I have received a SIGINT\n");} // sigquit() function definitionvoid sigquit(){ printf("My DADDY has Killed me!!!\n"); exit(0);}
Output:
C Language
Linux-Unix
Operating Systems
Operating Systems
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here. | [
{
"code": null,
"e": 52,
"s": 24,
"text": "\n31 Jan, 2019"
},
{
"code": null,
"e": 85,
"s": 52,
"text": "Prerequisite : C signal handling"
},
{
"code": null,
"e": 207,
"s": 85,
"text": "In this post, the communication between child and parent processes is done using kill() and signal(), fork() system call."
},
{
"code": null,
"e": 368,
"s": 207,
"text": "fork() creates the child process from the parent. The pid can be checked to decide whether it is the child (if pid == 0) or the parent (pid = child process id)."
},
{
"code": null,
"e": 437,
"s": 368,
"text": "The parent can then send messages to child using the pid and kill()."
},
{
"code": null,
"e": 517,
"s": 437,
"text": "The child picks up these signals with signal() and calls appropriate functions."
},
{
"code": null,
"e": 594,
"s": 517,
"text": "Example of how 2 processes can talk to each other using kill() and signal():"
},
{
"code": "// C program to implement sighup(), sigint()// and sigquit() signal functions#include <signal.h>#include <stdio.h>#include <stdlib.h>#include <sys/types.h>#include <unistd.h> // function declarationvoid sighup();void sigint();void sigquit(); // driver codevoid main(){ int pid; /* get child process */ if ((pid = fork()) < 0) { perror(\"fork\"); exit(1); } if (pid == 0) { /* child */ signal(SIGHUP, sighup); signal(SIGINT, sigint); signal(SIGQUIT, sigquit); for (;;) ; /* loop for ever */ } else /* parent */ { /* pid hold id of child */ printf(\"\\nPARENT: sending SIGHUP\\n\\n\"); kill(pid, SIGHUP); sleep(3); /* pause for 3 secs */ printf(\"\\nPARENT: sending SIGINT\\n\\n\"); kill(pid, SIGINT); sleep(3); /* pause for 3 secs */ printf(\"\\nPARENT: sending SIGQUIT\\n\\n\"); kill(pid, SIGQUIT); sleep(3); }} // sighup() function definitionvoid sighup() { signal(SIGHUP, sighup); /* reset signal */ printf(\"CHILD: I have received a SIGHUP\\n\");} // sigint() function definitionvoid sigint() { signal(SIGINT, sigint); /* reset signal */ printf(\"CHILD: I have received a SIGINT\\n\");} // sigquit() function definitionvoid sigquit(){ printf(\"My DADDY has Killed me!!!\\n\"); exit(0);}",
"e": 1936,
"s": 594,
"text": null
},
{
"code": null,
"e": 1944,
"s": 1936,
"text": "Output:"
},
{
"code": null,
"e": 1955,
"s": 1944,
"text": "C Language"
},
{
"code": null,
"e": 1966,
"s": 1955,
"text": "Linux-Unix"
},
{
"code": null,
"e": 1984,
"s": 1966,
"text": "Operating Systems"
},
{
"code": null,
"e": 2002,
"s": 1984,
"text": "Operating Systems"
}
] |
LISP - Numbers | Common Lisp defines several kinds of numbers. The number data type includes various kinds of numbers supported by LISP.
The number types supported by LISP are −
Integers
Ratios
Floating-point numbers
Complex numbers
The following diagram shows the number hierarchy and various numeric data types available in LISP −
The following table describes various number type data available in LISP −
fixnum
This data type represents integers which are not too large and mostly in the range -215 to 215-1 (it is machine-dependent)
bignum
These are very large numbers with size limited by the amount of memory allocated for LISP, they are not fixnum numbers.
ratio
Represents the ratio of two numbers in the numerator/denominator form. The / function always produce the result in ratios, when its arguments are integers.
float
It represents non-integer numbers. There are four float data types with increasing precision.
complex
It represents complex numbers, which are denoted by #c. The real and imaginary parts could be both either rational or floating point numbers.
Create a new source code file named main.lisp and type the following code in it.
(write (/ 1 2))
(terpri)
(write ( + (/ 1 2) (/ 3 4)))
(terpri)
(write ( + #c( 1 2) #c( 3 -4)))
When you execute the code, it returns the following result −
1/2
5/4
#C(4 -2)
The following table describes some commonly used numeric functions −
+, -, *, /
Respective arithmetic operations
sin, cos, tan, acos, asin, atan
Respective trigonometric functions.
sinh, cosh, tanh, acosh, asinh, atanh
Respective hyperbolic functions.
exp
Exponentiation function. Calculates ex
expt
Exponentiation function, takes base and power both.
sqrt
It calculates the square root of a number.
log
Logarithmic function. It one parameter is given, then it calculates its natural logarithm, otherwise the second parameter is used as base.
conjugate
It calculates the complex conjugate of a number. In case of a real number, it returns the number itself.
abs
It returns the absolute value (or magnitude) of a number.
gcd
It calculates the greatest common divisor of the given numbers.
lcm
It calculates the least common multiple of the given numbers.
isqrt
It gives the greatest integer less than or equal to the exact square root of a given natural number.
floor, ceiling, truncate, round
All these functions take two arguments as a number and returns the quotient; floor returns the largest integer that is not greater than ratio, ceiling chooses the smaller integer that is larger than ratio, truncate chooses the integer of the same sign as ratio with the largest absolute value that is less than absolute value of ratio, and round chooses an integer that is closest to ratio.
ffloor, fceiling, ftruncate, fround
Does the same as above, but returns the quotient as a floating point number.
mod, rem
Returns the remainder in a division operation.
float
Converts a real number to a floating point number.
rational, rationalize
Converts a real number to rational number.
numerator, denominator
Returns the respective parts of a rational number.
realpart, imagpart
Returns the real and imaginary part of a complex number.
Create a new source code file named main.lisp and type the following code in it.
(write (/ 45 78))
(terpri)
(write (floor 45 78))
(terpri)
(write (/ 3456 75))
(terpri)
(write (floor 3456 75))
(terpri)
(write (ceiling 3456 75))
(terpri)
(write (truncate 3456 75))
(terpri)
(write (round 3456 75))
(terpri)
(write (ffloor 3456 75))
(terpri)
(write (fceiling 3456 75))
(terpri)
(write (ftruncate 3456 75))
(terpri)
(write (fround 3456 75))
(terpri)
(write (mod 3456 75))
(terpri)
(setq c (complex 6 7))
(write c)
(terpri)
(write (complex 5 -9))
(terpri)
(write (realpart c))
(terpri)
(write (imagpart c))
When you execute the code, it returns the following result −
15/26
0
1152/25
46
47
46
46
46.0
47.0
46.0
46.0
6
#C(6 7)
#C(5 -9)
6
7
79 Lectures
7 hours
Arnold Higuit
Print
Add Notes
Bookmark this page | [
{
"code": null,
"e": 2180,
"s": 2060,
"text": "Common Lisp defines several kinds of numbers. The number data type includes various kinds of numbers supported by LISP."
},
{
"code": null,
"e": 2221,
"s": 2180,
"text": "The number types supported by LISP are −"
},
{
"code": null,
"e": 2230,
"s": 2221,
"text": "Integers"
},
{
"code": null,
"e": 2237,
"s": 2230,
"text": "Ratios"
},
{
"code": null,
"e": 2260,
"s": 2237,
"text": "Floating-point numbers"
},
{
"code": null,
"e": 2276,
"s": 2260,
"text": "Complex numbers"
},
{
"code": null,
"e": 2376,
"s": 2276,
"text": "The following diagram shows the number hierarchy and various numeric data types available in LISP −"
},
{
"code": null,
"e": 2451,
"s": 2376,
"text": "The following table describes various number type data available in LISP −"
},
{
"code": null,
"e": 2458,
"s": 2451,
"text": "fixnum"
},
{
"code": null,
"e": 2583,
"s": 2458,
"text": "This data type represents integers which are not too large and mostly in the range -215 to 215-1 (it is machine-dependent)"
},
{
"code": null,
"e": 2590,
"s": 2583,
"text": "bignum"
},
{
"code": null,
"e": 2710,
"s": 2590,
"text": "These are very large numbers with size limited by the amount of memory allocated for LISP, they are not fixnum numbers."
},
{
"code": null,
"e": 2716,
"s": 2710,
"text": "ratio"
},
{
"code": null,
"e": 2872,
"s": 2716,
"text": "Represents the ratio of two numbers in the numerator/denominator form. The / function always produce the result in ratios, when its arguments are integers."
},
{
"code": null,
"e": 2878,
"s": 2872,
"text": "float"
},
{
"code": null,
"e": 2972,
"s": 2878,
"text": "It represents non-integer numbers. There are four float data types with increasing precision."
},
{
"code": null,
"e": 2980,
"s": 2972,
"text": "complex"
},
{
"code": null,
"e": 3122,
"s": 2980,
"text": "It represents complex numbers, which are denoted by #c. The real and imaginary parts could be both either rational or floating point numbers."
},
{
"code": null,
"e": 3203,
"s": 3122,
"text": "Create a new source code file named main.lisp and type the following code in it."
},
{
"code": null,
"e": 3298,
"s": 3203,
"text": "(write (/ 1 2))\n(terpri)\n(write ( + (/ 1 2) (/ 3 4)))\n(terpri)\n(write ( + #c( 1 2) #c( 3 -4)))"
},
{
"code": null,
"e": 3359,
"s": 3298,
"text": "When you execute the code, it returns the following result −"
},
{
"code": null,
"e": 3377,
"s": 3359,
"text": "1/2\n5/4\n#C(4 -2)\n"
},
{
"code": null,
"e": 3446,
"s": 3377,
"text": "The following table describes some commonly used numeric functions −"
},
{
"code": null,
"e": 3457,
"s": 3446,
"text": "+, -, *, /"
},
{
"code": null,
"e": 3490,
"s": 3457,
"text": "Respective arithmetic operations"
},
{
"code": null,
"e": 3522,
"s": 3490,
"text": "sin, cos, tan, acos, asin, atan"
},
{
"code": null,
"e": 3558,
"s": 3522,
"text": "Respective trigonometric functions."
},
{
"code": null,
"e": 3596,
"s": 3558,
"text": "sinh, cosh, tanh, acosh, asinh, atanh"
},
{
"code": null,
"e": 3629,
"s": 3596,
"text": "Respective hyperbolic functions."
},
{
"code": null,
"e": 3633,
"s": 3629,
"text": "exp"
},
{
"code": null,
"e": 3672,
"s": 3633,
"text": "Exponentiation function. Calculates ex"
},
{
"code": null,
"e": 3677,
"s": 3672,
"text": "expt"
},
{
"code": null,
"e": 3729,
"s": 3677,
"text": "Exponentiation function, takes base and power both."
},
{
"code": null,
"e": 3734,
"s": 3729,
"text": "sqrt"
},
{
"code": null,
"e": 3777,
"s": 3734,
"text": "It calculates the square root of a number."
},
{
"code": null,
"e": 3781,
"s": 3777,
"text": "log"
},
{
"code": null,
"e": 3920,
"s": 3781,
"text": "Logarithmic function. It one parameter is given, then it calculates its natural logarithm, otherwise the second parameter is used as base."
},
{
"code": null,
"e": 3930,
"s": 3920,
"text": "conjugate"
},
{
"code": null,
"e": 4035,
"s": 3930,
"text": "It calculates the complex conjugate of a number. In case of a real number, it returns the number itself."
},
{
"code": null,
"e": 4039,
"s": 4035,
"text": "abs"
},
{
"code": null,
"e": 4097,
"s": 4039,
"text": "It returns the absolute value (or magnitude) of a number."
},
{
"code": null,
"e": 4101,
"s": 4097,
"text": "gcd"
},
{
"code": null,
"e": 4165,
"s": 4101,
"text": "It calculates the greatest common divisor of the given numbers."
},
{
"code": null,
"e": 4169,
"s": 4165,
"text": "lcm"
},
{
"code": null,
"e": 4231,
"s": 4169,
"text": "It calculates the least common multiple of the given numbers."
},
{
"code": null,
"e": 4237,
"s": 4231,
"text": "isqrt"
},
{
"code": null,
"e": 4338,
"s": 4237,
"text": "It gives the greatest integer less than or equal to the exact square root of a given natural number."
},
{
"code": null,
"e": 4370,
"s": 4338,
"text": "floor, ceiling, truncate, round"
},
{
"code": null,
"e": 4761,
"s": 4370,
"text": "All these functions take two arguments as a number and returns the quotient; floor returns the largest integer that is not greater than ratio, ceiling chooses the smaller integer that is larger than ratio, truncate chooses the integer of the same sign as ratio with the largest absolute value that is less than absolute value of ratio, and round chooses an integer that is closest to ratio."
},
{
"code": null,
"e": 4797,
"s": 4761,
"text": "ffloor, fceiling, ftruncate, fround"
},
{
"code": null,
"e": 4874,
"s": 4797,
"text": "Does the same as above, but returns the quotient as a floating point number."
},
{
"code": null,
"e": 4883,
"s": 4874,
"text": "mod, rem"
},
{
"code": null,
"e": 4930,
"s": 4883,
"text": "Returns the remainder in a division operation."
},
{
"code": null,
"e": 4936,
"s": 4930,
"text": "float"
},
{
"code": null,
"e": 4987,
"s": 4936,
"text": "Converts a real number to a floating point number."
},
{
"code": null,
"e": 5009,
"s": 4987,
"text": "rational, rationalize"
},
{
"code": null,
"e": 5052,
"s": 5009,
"text": "Converts a real number to rational number."
},
{
"code": null,
"e": 5075,
"s": 5052,
"text": "numerator, denominator"
},
{
"code": null,
"e": 5126,
"s": 5075,
"text": "Returns the respective parts of a rational number."
},
{
"code": null,
"e": 5145,
"s": 5126,
"text": "realpart, imagpart"
},
{
"code": null,
"e": 5202,
"s": 5145,
"text": "Returns the real and imaginary part of a complex number."
},
{
"code": null,
"e": 5283,
"s": 5202,
"text": "Create a new source code file named main.lisp and type the following code in it."
},
{
"code": null,
"e": 5804,
"s": 5283,
"text": "(write (/ 45 78))\n(terpri)\n(write (floor 45 78))\n(terpri)\n(write (/ 3456 75))\n(terpri)\n(write (floor 3456 75))\n(terpri)\n(write (ceiling 3456 75))\n(terpri)\n(write (truncate 3456 75))\n(terpri)\n(write (round 3456 75))\n(terpri)\n(write (ffloor 3456 75))\n(terpri)\n(write (fceiling 3456 75))\n(terpri)\n(write (ftruncate 3456 75))\n(terpri)\n(write (fround 3456 75))\n(terpri)\n(write (mod 3456 75))\n(terpri)\n(setq c (complex 6 7))\n(write c)\n(terpri)\n(write (complex 5 -9))\n(terpri)\n(write (realpart c))\n(terpri)\n(write (imagpart c))"
},
{
"code": null,
"e": 5865,
"s": 5804,
"text": "When you execute the code, it returns the following result −"
},
{
"code": null,
"e": 5937,
"s": 5865,
"text": "15/26\n0\n1152/25\n46\n47\n46\n46\n46.0\n47.0\n46.0\n46.0\n6\n#C(6 7)\n#C(5 -9)\n6\n7\n"
},
{
"code": null,
"e": 5970,
"s": 5937,
"text": "\n 79 Lectures \n 7 hours \n"
},
{
"code": null,
"e": 5985,
"s": 5970,
"text": " Arnold Higuit"
},
{
"code": null,
"e": 5992,
"s": 5985,
"text": " Print"
},
{
"code": null,
"e": 6003,
"s": 5992,
"text": " Add Notes"
}
] |
\text - Tex Command | \text - Used to produce text-mode material within a mathematical expression.
{ \text #1}
\text command is used to produce text-mode material (in a given font) within a mathematical expression.
|x| = x \text{ for all \(x \ge 0\)}
|x|=x for all x≥0
\text{\alpha in text mode }\alpha
\alpha in text mode α
|x| = x \text{ for all \(x \ge 0\)}
|x|=x for all x≥0
|x| = x \text{ for all \(x \ge 0\)}
\text{\alpha in text mode }\alpha
\alpha in text mode α
\text{\alpha in text mode }\alpha
14 Lectures
52 mins
Ashraf Said
11 Lectures
1 hours
Ashraf Said
9 Lectures
1 hours
Emenwa Global, Ejike IfeanyiChukwu
29 Lectures
2.5 hours
Mohammad Nauman
14 Lectures
1 hours
Daniel Stern
15 Lectures
47 mins
Nishant Kumar
Print
Add Notes
Bookmark this page | [
{
"code": null,
"e": 8063,
"s": 7986,
"text": "\\text - Used to produce text-mode material within a mathematical expression."
},
{
"code": null,
"e": 8075,
"s": 8063,
"text": "{ \\text #1}"
},
{
"code": null,
"e": 8179,
"s": 8075,
"text": "\\text command is used to produce text-mode material (in a given font) within a mathematical expression."
},
{
"code": null,
"e": 8297,
"s": 8179,
"text": "\n|x| = x \\text{ for all \\(x \\ge 0\\)}\n\n|x|=x for all x≥0\n\n\n\\text{\\alpha in text mode }\\alpha\n\n\\alpha in text mode α\n\n\n"
},
{
"code": null,
"e": 8354,
"s": 8297,
"text": "|x| = x \\text{ for all \\(x \\ge 0\\)}\n\n|x|=x for all x≥0\n\n"
},
{
"code": null,
"e": 8390,
"s": 8354,
"text": "|x| = x \\text{ for all \\(x \\ge 0\\)}"
},
{
"code": null,
"e": 8449,
"s": 8390,
"text": "\\text{\\alpha in text mode }\\alpha\n\n\\alpha in text mode α\n\n"
},
{
"code": null,
"e": 8483,
"s": 8449,
"text": "\\text{\\alpha in text mode }\\alpha"
},
{
"code": null,
"e": 8515,
"s": 8483,
"text": "\n 14 Lectures \n 52 mins\n"
},
{
"code": null,
"e": 8528,
"s": 8515,
"text": " Ashraf Said"
},
{
"code": null,
"e": 8561,
"s": 8528,
"text": "\n 11 Lectures \n 1 hours \n"
},
{
"code": null,
"e": 8574,
"s": 8561,
"text": " Ashraf Said"
},
{
"code": null,
"e": 8606,
"s": 8574,
"text": "\n 9 Lectures \n 1 hours \n"
},
{
"code": null,
"e": 8642,
"s": 8606,
"text": " Emenwa Global, Ejike IfeanyiChukwu"
},
{
"code": null,
"e": 8677,
"s": 8642,
"text": "\n 29 Lectures \n 2.5 hours \n"
},
{
"code": null,
"e": 8694,
"s": 8677,
"text": " Mohammad Nauman"
},
{
"code": null,
"e": 8727,
"s": 8694,
"text": "\n 14 Lectures \n 1 hours \n"
},
{
"code": null,
"e": 8741,
"s": 8727,
"text": " Daniel Stern"
},
{
"code": null,
"e": 8773,
"s": 8741,
"text": "\n 15 Lectures \n 47 mins\n"
},
{
"code": null,
"e": 8788,
"s": 8773,
"text": " Nishant Kumar"
},
{
"code": null,
"e": 8795,
"s": 8788,
"text": " Print"
},
{
"code": null,
"e": 8806,
"s": 8795,
"text": " Add Notes"
}
] |
What is the best way to auto scale TextView Text to Fit within Bounds on Android? | This example demonstrates how to do I auto scale TextView text to fit within the bounds on android.
Step 1 − Create a new project in Android Studio, go to File ⇒ New Project and fill all required details to create a new project.
Add the following dependencies to build.gradle: Module: App)
implementation 'com.android.support:design:28.0.0'
implementation 'me.grantland:autofittextview:0.2.1'
Step 2 − Add the following code to res/layout/activity_main.xml.
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
xmlns:autofit="http://schemas.android.com/apk/res-auto"
android:orientation="vertical"
tools:context=".MainActivity">
<me.grantland.widget.AutofitTextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:maxLines="2"
android:singleLine="true"
android:text="Android AutoFit TextView Example"
android:textSize="42sp"
autofit:minTextSize="5sp" />
<me.grantland.widget.AutofitTextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:maxLines="2"
android:layout_marginTop="10dp"
android:layout_marginBottom="10dp"
android:singleLine="true"
android:text="A TextView that automatically reSizes text to fit perfectly within the bounds"
android:textSize="42sp"
autofit:minTextSize="5sp" />
<me.grantland.widget.AutofitTextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:maxLines="2"
android:singleLine="true"
android:text="Android AutoFit TextView"
android:textSize="42sp"
autofit:minTextSize="5sp" />
<me.grantland.widget.AutofitTextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:maxLines="2"
android:layout_marginTop="10dp"
android:layout_marginBottom="10dp"
android:singleLine="true"
android:text="Automatically Resized text"
android:textSize="42sp"
autofit:minTextSize="5sp" />
<me.grantland.widget.AutofitTextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:maxLines="2"
android:singleLine="true"
android:text="Automatically Resize Text to Fit Perfectly within its Bounds"
android:textSize="42sp"
autofit:minTextSize="5sp" />
</LinearLayout>
Step 3 − Add the following code to src/MainActivity.java
import androidx.appcompat.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);
}
}
Step 4 − Add the following code to androidManifest.xml
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android" package="app.com.sample">
<application
android:allowBackup="true"
android:icon="@mipmap/ic_launcher"
android:label="@string/app_name"
android:roundIcon="@mipmap/ic_launcher_round"
android:supportsRtl="true"
android:theme="@style/AppTheme">
<activity android:name=".MainActivity">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
</manifest>
Let's try to run your application. I assume you have connected your actual Android Mobile device with your computer. To run the app from the android studio, open one of your project's activity files and click Run icon from the toolbar. Select your mobile device as an option and then check your mobile device which will display your default screen −
Click here to download the project code. | [
{
"code": null,
"e": 1162,
"s": 1062,
"text": "This example demonstrates how to do I auto scale TextView text to fit within the bounds on android."
},
{
"code": null,
"e": 1291,
"s": 1162,
"text": "Step 1 − Create a new project in Android Studio, go to File ⇒ New Project and fill all required details to create a new project."
},
{
"code": null,
"e": 1352,
"s": 1291,
"text": "Add the following dependencies to build.gradle: Module: App)"
},
{
"code": null,
"e": 1455,
"s": 1352,
"text": "implementation 'com.android.support:design:28.0.0'\nimplementation 'me.grantland:autofittextview:0.2.1'"
},
{
"code": null,
"e": 1520,
"s": 1455,
"text": "Step 2 − Add the following code to res/layout/activity_main.xml."
},
{
"code": null,
"e": 3633,
"s": 1520,
"text": "<?xml version=\"1.0\" encoding=\"utf-8\"?>\n<LinearLayout xmlns:android=\"http://schemas.android.com/apk/res/android\"\nxmlns:tools=\"http://schemas.android.com/tools\"\n android:layout_width=\"match_parent\"\n android:layout_height=\"match_parent\"\n xmlns:autofit=\"http://schemas.android.com/apk/res-auto\"\n android:orientation=\"vertical\"\n tools:context=\".MainActivity\">\n <me.grantland.widget.AutofitTextView\n android:layout_width=\"match_parent\"\n android:layout_height=\"wrap_content\"\n android:maxLines=\"2\"\n android:singleLine=\"true\"\n android:text=\"Android AutoFit TextView Example\"\n android:textSize=\"42sp\"\n autofit:minTextSize=\"5sp\" />\n <me.grantland.widget.AutofitTextView\n android:layout_width=\"match_parent\"\n android:layout_height=\"wrap_content\"\n android:maxLines=\"2\"\n android:layout_marginTop=\"10dp\"\n android:layout_marginBottom=\"10dp\"\n android:singleLine=\"true\"\n android:text=\"A TextView that automatically reSizes text to fit perfectly within the bounds\"\n android:textSize=\"42sp\"\n autofit:minTextSize=\"5sp\" />\n <me.grantland.widget.AutofitTextView\n android:layout_width=\"match_parent\"\n android:layout_height=\"wrap_content\"\n android:maxLines=\"2\"\n android:singleLine=\"true\"\n android:text=\"Android AutoFit TextView\"\n android:textSize=\"42sp\"\n autofit:minTextSize=\"5sp\" />\n <me.grantland.widget.AutofitTextView\n android:layout_width=\"match_parent\"\n android:layout_height=\"wrap_content\"\n android:maxLines=\"2\"\n android:layout_marginTop=\"10dp\"\n android:layout_marginBottom=\"10dp\"\n android:singleLine=\"true\"\n android:text=\"Automatically Resized text\"\n android:textSize=\"42sp\"\n autofit:minTextSize=\"5sp\" />\n <me.grantland.widget.AutofitTextView\n android:layout_width=\"match_parent\"\n android:layout_height=\"wrap_content\"\n android:maxLines=\"2\"\n android:singleLine=\"true\"\n android:text=\"Automatically Resize Text to Fit Perfectly within its Bounds\"\n android:textSize=\"42sp\"\n autofit:minTextSize=\"5sp\" />\n</LinearLayout>"
},
{
"code": null,
"e": 3690,
"s": 3633,
"text": "Step 3 − Add the following code to src/MainActivity.java"
},
{
"code": null,
"e": 3983,
"s": 3690,
"text": "import androidx.appcompat.app.AppCompatActivity;\nimport android.os.Bundle;\npublic class MainActivity extends AppCompatActivity {\n @Override\n protected void onCreate(Bundle savedInstanceState) {\n super.onCreate(savedInstanceState);\n setContentView(R.layout.activity_main);\n }\n}"
},
{
"code": null,
"e": 4038,
"s": 3983,
"text": "Step 4 − Add the following code to androidManifest.xml"
},
{
"code": null,
"e": 4708,
"s": 4038,
"text": "<?xml version=\"1.0\" encoding=\"utf-8\"?>\n<manifest xmlns:android=\"http://schemas.android.com/apk/res/android\" package=\"app.com.sample\">\n <application\n android:allowBackup=\"true\"\n android:icon=\"@mipmap/ic_launcher\"\n android:label=\"@string/app_name\"\n android:roundIcon=\"@mipmap/ic_launcher_round\"\n android:supportsRtl=\"true\"\n android:theme=\"@style/AppTheme\">\n <activity android:name=\".MainActivity\">\n <intent-filter>\n <action android:name=\"android.intent.action.MAIN\" />\n <category android:name=\"android.intent.category.LAUNCHER\" />\n </intent-filter>\n </activity>\n </application>\n</manifest>"
},
{
"code": null,
"e": 5059,
"s": 4708,
"text": "Let's try to run your application. I assume you have connected your actual Android Mobile device with your computer. To run the app from the android studio, open one of your project's activity files and click Run icon from the toolbar. Select your mobile device as an option and then check your mobile device which will display your default screen −"
},
{
"code": null,
"e": 5100,
"s": 5059,
"text": "Click here to download the project code."
}
] |
Android | How to add Radio Buttons in an Android Application? - GeeksforGeeks | 29 Sep, 2021
Pre-requisites:
Android App Development Fundamentals for Beginners
Guide to Install and Set up Android Studio
Android | Starting with first app/android project
Android | Running your first Android app
Android radio button is a widget which can have more than one option to choose from. The user can choose only one option at a time. Each option here refers to a radio button and all the options for the topic are together referred to as Radio Group. Hence, Radio Buttons are used inside a RadioGroup.
For Example:
This image shows 4 options of the subjects for a question. In this, each mentioned subject is a Radio Button and all the 4 subjects together are enclosed in a Radio Group.
This example will help in developing an Android App that create Radio Buttons according to the above example:
Step 1: First create a new Android Application. This will create an XML file “activity_main.xml” and a Java File “MainActivity.Java”. Please refer the pre-requisites to learn more about this step.
Step 2: Open “activity_main.xml” file and add following widgets in a Relative Layout:
A TextView to display the question message
A RadioGroup to hold the option Radio Buttons which are the possible answers
4 RadioButtons to hold an answer each.
A Submit and a Clear button to store the response.
Also, Assign the ID to each of the component along with other attributes as shown in the given image and the code below. The assigned ID on a component helps that component to be easily found and used in the Java files.
Syntax:
android:id="@+id/id_name"
Here the given IDs are as follows:
RadioGroup: groupradio
RadioButton1: radia_id1
RadioButton2: radia_id2
RadioButton3: radia_id3
RadioButton4: radia_id4
Submit Button: submit
Clear Button: clear
This will make the UI of the Application.
Step 3: Now, after the UI, this step will create the Backend of Application. For this, open the “MainActivity.java” file and instantiate the components made in the XML file (RadioGroup, TextView, Clear, and Submit Button) using findViewById() method. This method binds the created object to the UI Components with the help of the assigned ID.
General Syntax:
ComponentType object = (ComponentType)findViewById(R.id.IdOfTheComponent);
Syntax for components used:
Button submit = (Button)findViewById(R.id.submit); Button clear = (Button)findViewById(R.id.clear); RadioGroup radioGroup = (RadioGroup)findViewById(R.id.groupradio);
Step 4: This step involves setting up the operations on the RadioGroup, RadioButtons and the Submit and Clear Buttons.
These operations are as follows:
Unset all the Radio Buttons initially as the default value. This is done by the following command:
radioGroup.clearCheck();
Add the Listener on the RadioGroup. This will help to know whenever the user clicks on any Radio Button, and the further operation will be performed. The listener can be added as follows:
radioGroup.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener(){}
Define the operations to be done when a radio button is clicked. This involves getting the specific radio button that has been clicked, using its id. Then this radio button gets set and the rest of the radio button is reset.
Add the listener on Submit button and clear button. This will be used to check when the user clicks on the button. This is done as follows:
submit.setOnClickListener(new View.OnClickListener() {} clear.setOnClickListener(new View.OnClickListener() {}
In the Submit Button Listener, set the operations to be performed. This involves displaying the marked answer in the form of Toast.
In the Clear Button Listener, set the operations to be performed. This involves resetting all the radio buttons.
Step5: Now run the app and operate as follows:
When the app is opened, it displays a question with 4 answers and a clear and submit button.
When any answer is clicked, that radio button gets set.
Clicking on any other radio button sets that one and resets the others.
Clicking on Submit button displays the currently marked answer as a Toast.
Clicking on Clear button resets all the radio buttons to their default state.
Complete code of MainActivity.java and activity_main.xml of RadioButton is below.
Filename: activity_main.xml
XML
<?xml version="1.0" encoding="utf-8"?><RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:app="http://schemas.android.com/apk/res-auto" xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent" android:layout_height="match_parent" tools:context=".MainActivity"> <TextView android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="Select your Subject ?" android:textStyle="bold" android:layout_marginLeft="10dp" android:textSize="20dp"/> <!-- add RadioGroup which contain the many RadioButton--> <RadioGroup android:layout_marginTop="50dp" android:id="@+id/groupradio" android:layout_marginLeft="10dp" android:layout_width="fill_parent" android:layout_height="wrap_content"> <!-- In RadioGroup create the 1 Radio Button--> <!-- like this we will add some more Radio Button--> <RadioButton android:layout_width="fill_parent" android:layout_height="wrap_content" android:id="@+id/radia_id1" android:text="DBMS" android:textSize="20dp"/> <RadioButton android:layout_width="fill_parent" android:layout_height="wrap_content" android:id="@+id/radia_id2" android:text="C/C++ Programming" android:textSize="20dp"/> <RadioButton android:layout_width="fill_parent" android:layout_height="wrap_content" android:id="@+id/radia_id3" android:text="Data Structure" android:textSize="20dp"/> <RadioButton android:layout_width="fill_parent" android:layout_height="wrap_content" android:id="@+id/radia_id4" android:text="Algorithms" android:textSize="20dp"/> </RadioGroup> <!-- add button For Submit the Selected item--> <Button android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="Submit" android:id="@+id/submit" android:textStyle="bold" android:textSize="20dp" android:layout_marginTop="200dp" android:layout_marginLeft="180dp" /> <!-- add clear button for clear the selected item--> <Button android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="Clear" android:id="@+id/clear" android:textSize="20dp" android:textStyle="bold" android:layout_marginTop="200dp" android:layout_marginLeft="20dp" /> </RelativeLayout>
Filename: MainActivity.Java
Java
package org.geeksforgeeks.navedmalik.radiobuttons; import android.support.v7.app.AppCompatActivity;import android.os.Bundle;import android.view.View;import android.widget.Button;import android.widget.RadioButton;import android.widget.RadioGroup;import android.widget.Toast; public class MainActivity extends AppCompatActivity { // Define the object for Radio Group, // Submit and Clear buttons private RadioGroup radioGroup; Button submit, clear; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); // Bind the components to their respective objects // by assigning their IDs // with the help of findViewById() method submit = (Button)findViewById(R.id.submit); clear = (Button)findViewById(R.id.clear); radioGroup = (RadioGroup)findViewById(R.id.groupradio); // Uncheck or reset the radio buttons initially radioGroup.clearCheck(); // Add the Listener to the RadioGroup radioGroup.setOnCheckedChangeListener( new RadioGroup .OnCheckedChangeListener() { @Override // The flow will come here when // any of the radio buttons in the radioGroup // has been clicked // Check which radio button has been clicked public void onCheckedChanged(RadioGroup group, int checkedId) { // Get the selected Radio Button RadioButton radioButton = (RadioButton)group .findViewById(checkedId); } }); // Add the Listener to the Submit Button submit.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { // When submit button is clicked, // Ge the Radio Button which is set // If no Radio Button is set, -1 will be returned int selectedId = radioGroup.getCheckedRadioButtonId(); if (selectedId == -1) { Toast.makeText(MainActivity.this, "No answer has been selected", Toast.LENGTH_SHORT) .show(); } else { RadioButton radioButton = (RadioButton)radioGroup .findViewById(selectedId); // Now display the value of selected item // by the Toast message Toast.makeText(MainActivity.this, radioButton.getText(), Toast.LENGTH_SHORT) .show(); } } }); // Add the Listener to the Submit Button clear.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { // Clear RadioGroup // i.e. reset all the Radio Buttons radioGroup.clearCheck(); } }); }}
Output:
vartika02
anikakapoor
Android-Button
Android
Java
Java
Android
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Broadcast Receiver in Android With Example
How to Create and Add Data to SQLite Database in Android?
Content Providers in Android with Example
Android RecyclerView in Kotlin
Flutter - Custom Bottom Navigation Bar
Arrays in Java
Split() String method in Java with examples
For-each loop in Java
Arrays.sort() in Java with examples
Reverse a string in Java | [
{
"code": null,
"e": 24206,
"s": 24178,
"text": "\n29 Sep, 2021"
},
{
"code": null,
"e": 24223,
"s": 24206,
"text": "Pre-requisites: "
},
{
"code": null,
"e": 24274,
"s": 24223,
"text": "Android App Development Fundamentals for Beginners"
},
{
"code": null,
"e": 24317,
"s": 24274,
"text": "Guide to Install and Set up Android Studio"
},
{
"code": null,
"e": 24367,
"s": 24317,
"text": "Android | Starting with first app/android project"
},
{
"code": null,
"e": 24408,
"s": 24367,
"text": "Android | Running your first Android app"
},
{
"code": null,
"e": 24709,
"s": 24408,
"text": "Android radio button is a widget which can have more than one option to choose from. The user can choose only one option at a time. Each option here refers to a radio button and all the options for the topic are together referred to as Radio Group. Hence, Radio Buttons are used inside a RadioGroup. "
},
{
"code": null,
"e": 24723,
"s": 24709,
"text": "For Example: "
},
{
"code": null,
"e": 24896,
"s": 24723,
"text": "This image shows 4 options of the subjects for a question. In this, each mentioned subject is a Radio Button and all the 4 subjects together are enclosed in a Radio Group. "
},
{
"code": null,
"e": 25006,
"s": 24896,
"text": "This example will help in developing an Android App that create Radio Buttons according to the above example:"
},
{
"code": null,
"e": 25203,
"s": 25006,
"text": "Step 1: First create a new Android Application. This will create an XML file “activity_main.xml” and a Java File “MainActivity.Java”. Please refer the pre-requisites to learn more about this step."
},
{
"code": null,
"e": 25290,
"s": 25203,
"text": "Step 2: Open “activity_main.xml” file and add following widgets in a Relative Layout: "
},
{
"code": null,
"e": 25333,
"s": 25290,
"text": "A TextView to display the question message"
},
{
"code": null,
"e": 25410,
"s": 25333,
"text": "A RadioGroup to hold the option Radio Buttons which are the possible answers"
},
{
"code": null,
"e": 25449,
"s": 25410,
"text": "4 RadioButtons to hold an answer each."
},
{
"code": null,
"e": 25500,
"s": 25449,
"text": "A Submit and a Clear button to store the response."
},
{
"code": null,
"e": 25720,
"s": 25500,
"text": "Also, Assign the ID to each of the component along with other attributes as shown in the given image and the code below. The assigned ID on a component helps that component to be easily found and used in the Java files."
},
{
"code": null,
"e": 25728,
"s": 25720,
"text": "Syntax:"
},
{
"code": null,
"e": 25754,
"s": 25728,
"text": "android:id=\"@+id/id_name\""
},
{
"code": null,
"e": 25789,
"s": 25754,
"text": "Here the given IDs are as follows:"
},
{
"code": null,
"e": 25812,
"s": 25789,
"text": "RadioGroup: groupradio"
},
{
"code": null,
"e": 25836,
"s": 25812,
"text": "RadioButton1: radia_id1"
},
{
"code": null,
"e": 25860,
"s": 25836,
"text": "RadioButton2: radia_id2"
},
{
"code": null,
"e": 25884,
"s": 25860,
"text": "RadioButton3: radia_id3"
},
{
"code": null,
"e": 25908,
"s": 25884,
"text": "RadioButton4: radia_id4"
},
{
"code": null,
"e": 25930,
"s": 25908,
"text": "Submit Button: submit"
},
{
"code": null,
"e": 25950,
"s": 25930,
"text": "Clear Button: clear"
},
{
"code": null,
"e": 25992,
"s": 25950,
"text": "This will make the UI of the Application."
},
{
"code": null,
"e": 26335,
"s": 25992,
"text": "Step 3: Now, after the UI, this step will create the Backend of Application. For this, open the “MainActivity.java” file and instantiate the components made in the XML file (RadioGroup, TextView, Clear, and Submit Button) using findViewById() method. This method binds the created object to the UI Components with the help of the assigned ID."
},
{
"code": null,
"e": 26352,
"s": 26335,
"text": "General Syntax: "
},
{
"code": null,
"e": 26427,
"s": 26352,
"text": "ComponentType object = (ComponentType)findViewById(R.id.IdOfTheComponent);"
},
{
"code": null,
"e": 26456,
"s": 26427,
"text": "Syntax for components used: "
},
{
"code": null,
"e": 26625,
"s": 26456,
"text": "Button submit = (Button)findViewById(R.id.submit); Button clear = (Button)findViewById(R.id.clear); RadioGroup radioGroup = (RadioGroup)findViewById(R.id.groupradio); "
},
{
"code": null,
"e": 26744,
"s": 26625,
"text": "Step 4: This step involves setting up the operations on the RadioGroup, RadioButtons and the Submit and Clear Buttons."
},
{
"code": null,
"e": 26779,
"s": 26744,
"text": " These operations are as follows: "
},
{
"code": null,
"e": 26878,
"s": 26779,
"text": "Unset all the Radio Buttons initially as the default value. This is done by the following command:"
},
{
"code": null,
"e": 26903,
"s": 26878,
"text": "radioGroup.clearCheck();"
},
{
"code": null,
"e": 27091,
"s": 26903,
"text": "Add the Listener on the RadioGroup. This will help to know whenever the user clicks on any Radio Button, and the further operation will be performed. The listener can be added as follows:"
},
{
"code": null,
"e": 27172,
"s": 27091,
"text": "radioGroup.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener(){}"
},
{
"code": null,
"e": 27397,
"s": 27172,
"text": "Define the operations to be done when a radio button is clicked. This involves getting the specific radio button that has been clicked, using its id. Then this radio button gets set and the rest of the radio button is reset."
},
{
"code": null,
"e": 27537,
"s": 27397,
"text": "Add the listener on Submit button and clear button. This will be used to check when the user clicks on the button. This is done as follows:"
},
{
"code": null,
"e": 27648,
"s": 27537,
"text": "submit.setOnClickListener(new View.OnClickListener() {} clear.setOnClickListener(new View.OnClickListener() {}"
},
{
"code": null,
"e": 27780,
"s": 27648,
"text": "In the Submit Button Listener, set the operations to be performed. This involves displaying the marked answer in the form of Toast."
},
{
"code": null,
"e": 27893,
"s": 27780,
"text": "In the Clear Button Listener, set the operations to be performed. This involves resetting all the radio buttons."
},
{
"code": null,
"e": 27941,
"s": 27893,
"text": "Step5: Now run the app and operate as follows: "
},
{
"code": null,
"e": 28034,
"s": 27941,
"text": "When the app is opened, it displays a question with 4 answers and a clear and submit button."
},
{
"code": null,
"e": 28090,
"s": 28034,
"text": "When any answer is clicked, that radio button gets set."
},
{
"code": null,
"e": 28162,
"s": 28090,
"text": "Clicking on any other radio button sets that one and resets the others."
},
{
"code": null,
"e": 28237,
"s": 28162,
"text": "Clicking on Submit button displays the currently marked answer as a Toast."
},
{
"code": null,
"e": 28315,
"s": 28237,
"text": "Clicking on Clear button resets all the radio buttons to their default state."
},
{
"code": null,
"e": 28397,
"s": 28315,
"text": "Complete code of MainActivity.java and activity_main.xml of RadioButton is below."
},
{
"code": null,
"e": 28425,
"s": 28397,
"text": "Filename: activity_main.xml"
},
{
"code": null,
"e": 28429,
"s": 28425,
"text": "XML"
},
{
"code": "<?xml version=\"1.0\" encoding=\"utf-8\"?><RelativeLayout xmlns:android=\"http://schemas.android.com/apk/res/android\" xmlns:app=\"http://schemas.android.com/apk/res-auto\" xmlns:tools=\"http://schemas.android.com/tools\" android:layout_width=\"match_parent\" android:layout_height=\"match_parent\" tools:context=\".MainActivity\"> <TextView android:layout_width=\"wrap_content\" android:layout_height=\"wrap_content\" android:text=\"Select your Subject ?\" android:textStyle=\"bold\" android:layout_marginLeft=\"10dp\" android:textSize=\"20dp\"/> <!-- add RadioGroup which contain the many RadioButton--> <RadioGroup android:layout_marginTop=\"50dp\" android:id=\"@+id/groupradio\" android:layout_marginLeft=\"10dp\" android:layout_width=\"fill_parent\" android:layout_height=\"wrap_content\"> <!-- In RadioGroup create the 1 Radio Button--> <!-- like this we will add some more Radio Button--> <RadioButton android:layout_width=\"fill_parent\" android:layout_height=\"wrap_content\" android:id=\"@+id/radia_id1\" android:text=\"DBMS\" android:textSize=\"20dp\"/> <RadioButton android:layout_width=\"fill_parent\" android:layout_height=\"wrap_content\" android:id=\"@+id/radia_id2\" android:text=\"C/C++ Programming\" android:textSize=\"20dp\"/> <RadioButton android:layout_width=\"fill_parent\" android:layout_height=\"wrap_content\" android:id=\"@+id/radia_id3\" android:text=\"Data Structure\" android:textSize=\"20dp\"/> <RadioButton android:layout_width=\"fill_parent\" android:layout_height=\"wrap_content\" android:id=\"@+id/radia_id4\" android:text=\"Algorithms\" android:textSize=\"20dp\"/> </RadioGroup> <!-- add button For Submit the Selected item--> <Button android:layout_width=\"wrap_content\" android:layout_height=\"wrap_content\" android:text=\"Submit\" android:id=\"@+id/submit\" android:textStyle=\"bold\" android:textSize=\"20dp\" android:layout_marginTop=\"200dp\" android:layout_marginLeft=\"180dp\" /> <!-- add clear button for clear the selected item--> <Button android:layout_width=\"wrap_content\" android:layout_height=\"wrap_content\" android:text=\"Clear\" android:id=\"@+id/clear\" android:textSize=\"20dp\" android:textStyle=\"bold\" android:layout_marginTop=\"200dp\" android:layout_marginLeft=\"20dp\" /> </RelativeLayout>",
"e": 31093,
"s": 28429,
"text": null
},
{
"code": null,
"e": 31121,
"s": 31093,
"text": "Filename: MainActivity.Java"
},
{
"code": null,
"e": 31126,
"s": 31121,
"text": "Java"
},
{
"code": "package org.geeksforgeeks.navedmalik.radiobuttons; import android.support.v7.app.AppCompatActivity;import android.os.Bundle;import android.view.View;import android.widget.Button;import android.widget.RadioButton;import android.widget.RadioGroup;import android.widget.Toast; public class MainActivity extends AppCompatActivity { // Define the object for Radio Group, // Submit and Clear buttons private RadioGroup radioGroup; Button submit, clear; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); // Bind the components to their respective objects // by assigning their IDs // with the help of findViewById() method submit = (Button)findViewById(R.id.submit); clear = (Button)findViewById(R.id.clear); radioGroup = (RadioGroup)findViewById(R.id.groupradio); // Uncheck or reset the radio buttons initially radioGroup.clearCheck(); // Add the Listener to the RadioGroup radioGroup.setOnCheckedChangeListener( new RadioGroup .OnCheckedChangeListener() { @Override // The flow will come here when // any of the radio buttons in the radioGroup // has been clicked // Check which radio button has been clicked public void onCheckedChanged(RadioGroup group, int checkedId) { // Get the selected Radio Button RadioButton radioButton = (RadioButton)group .findViewById(checkedId); } }); // Add the Listener to the Submit Button submit.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { // When submit button is clicked, // Ge the Radio Button which is set // If no Radio Button is set, -1 will be returned int selectedId = radioGroup.getCheckedRadioButtonId(); if (selectedId == -1) { Toast.makeText(MainActivity.this, \"No answer has been selected\", Toast.LENGTH_SHORT) .show(); } else { RadioButton radioButton = (RadioButton)radioGroup .findViewById(selectedId); // Now display the value of selected item // by the Toast message Toast.makeText(MainActivity.this, radioButton.getText(), Toast.LENGTH_SHORT) .show(); } } }); // Add the Listener to the Submit Button clear.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { // Clear RadioGroup // i.e. reset all the Radio Buttons radioGroup.clearCheck(); } }); }}",
"e": 34516,
"s": 31126,
"text": null
},
{
"code": null,
"e": 34525,
"s": 34516,
"text": "Output: "
},
{
"code": null,
"e": 34537,
"s": 34527,
"text": "vartika02"
},
{
"code": null,
"e": 34549,
"s": 34537,
"text": "anikakapoor"
},
{
"code": null,
"e": 34564,
"s": 34549,
"text": "Android-Button"
},
{
"code": null,
"e": 34572,
"s": 34564,
"text": "Android"
},
{
"code": null,
"e": 34577,
"s": 34572,
"text": "Java"
},
{
"code": null,
"e": 34582,
"s": 34577,
"text": "Java"
},
{
"code": null,
"e": 34590,
"s": 34582,
"text": "Android"
},
{
"code": null,
"e": 34688,
"s": 34590,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 34697,
"s": 34688,
"text": "Comments"
},
{
"code": null,
"e": 34710,
"s": 34697,
"text": "Old Comments"
},
{
"code": null,
"e": 34753,
"s": 34710,
"text": "Broadcast Receiver in Android With Example"
},
{
"code": null,
"e": 34811,
"s": 34753,
"text": "How to Create and Add Data to SQLite Database in Android?"
},
{
"code": null,
"e": 34853,
"s": 34811,
"text": "Content Providers in Android with Example"
},
{
"code": null,
"e": 34884,
"s": 34853,
"text": "Android RecyclerView in Kotlin"
},
{
"code": null,
"e": 34923,
"s": 34884,
"text": "Flutter - Custom Bottom Navigation Bar"
},
{
"code": null,
"e": 34938,
"s": 34923,
"text": "Arrays in Java"
},
{
"code": null,
"e": 34982,
"s": 34938,
"text": "Split() String method in Java with examples"
},
{
"code": null,
"e": 35004,
"s": 34982,
"text": "For-each loop in Java"
},
{
"code": null,
"e": 35040,
"s": 35004,
"text": "Arrays.sort() in Java with examples"
}
] |
Synchronization by using Semaphore in Python - GeeksforGeeks | 11 Oct, 2020
In Lock and RLock, at a time only one Thread is allowed to execute but sometimes our requirement is to execute a particular number of Threads at a time.
Suppose we have to allow at a time 10 members to access the Database and only 4 members are allowed to access Network Connection. To handle such types of requirements we can not use Lock and RLock concept and here we should go for Semaphore. Semaphore can be used to limit the access to the shared resources with limited capacity. It is an advanced part of synchronization.
Create an object of Semaphore:
object_name = Semaphore(count)
Here ‘count’ is the number of Threads allowed to access simultaneously. The default value of count is 1.
When a Thread executes acquire() method then the value of “count” variable will be decremented by 1 and whenever a Thread executes release() method then the value of “count” variable will be incremented by 1. i.e whenever acquire() method will be called the value of count variable will be decremented and whenever release() method will be called the value of “count” variable will be incremented.
Way to create an object of Semaphore :
Case 1 :
object_name.Semaphore()
In this case, by default value of the count variable is 1 due to which only one thread is allowed to access. It is exactly the same as the Lock concept.
Case 2 :
object_name.Semaphore(n)
In this case, a Semaphore object can be accessed by n Threads at a time. The remaining Threads have to wait until releasing the semaphore.
Executable code of Semaphore :
Python3
# importing the modulesfrom threading import * import time # creating thread instance where count = 3obj = Semaphore(3) # creating instancedef display(name): # calling acquire method obj.acquire() for i in range(5): print('Hello, ', end = '') time.sleep(1) print(name) # calling release method obj.release() # creating multiple thread t1 = Thread(target = display , args = ('Thread-1',))t2 = Thread(target = display , args = ('Thread-2',))t3 = Thread(target = display , args = ('Thread-3',))t4 = Thread(target = display , args = ('Thread-4',))t5 = Thread(target = display , args = ('Thread-5',)) # calling the threads t1.start()t2.start()t3.start()t4.start()t5.start()
Output:
Here in the above example first we created an instance of Semaphore Class where the value of “count” is 3 it means that Semaphore Object can be accessed by 3 Threads at a time. Now we have created display() method which will print the Thread name 5 times. Now we created 5 threads and now whenever we call start() method at that time 3 Threads are allowed to access Semaphore objects and hence 3 Threads are allowed to execute display() method at a time but in this example whenever we will execute we will get irregular output because 3 Threads are executing display() method at a time.
python-utility
Advanced Computer Subject
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
ML | Linear Regression
Decision Tree
Copying Files to and from Docker Containers
System Design Tutorial
Python | Decision tree implementation
Read JSON file using Python
Adding new column to existing DataFrame in Pandas
Python map() function
How to get column names in Pandas dataframe | [
{
"code": null,
"e": 24686,
"s": 24658,
"text": "\n11 Oct, 2020"
},
{
"code": null,
"e": 24842,
"s": 24686,
"text": "In Lock and RLock, at a time only one Thread is allowed to execute but sometimes our requirement is to execute a particular number of Threads at a time. "
},
{
"code": null,
"e": 25216,
"s": 24842,
"text": "Suppose we have to allow at a time 10 members to access the Database and only 4 members are allowed to access Network Connection. To handle such types of requirements we can not use Lock and RLock concept and here we should go for Semaphore. Semaphore can be used to limit the access to the shared resources with limited capacity. It is an advanced part of synchronization."
},
{
"code": null,
"e": 25248,
"s": 25216,
"text": "Create an object of Semaphore: "
},
{
"code": null,
"e": 25280,
"s": 25248,
"text": "object_name = Semaphore(count)\n"
},
{
"code": null,
"e": 25385,
"s": 25280,
"text": "Here ‘count’ is the number of Threads allowed to access simultaneously. The default value of count is 1."
},
{
"code": null,
"e": 25784,
"s": 25385,
"text": "When a Thread executes acquire() method then the value of “count” variable will be decremented by 1 and whenever a Thread executes release() method then the value of “count” variable will be incremented by 1. i.e whenever acquire() method will be called the value of count variable will be decremented and whenever release() method will be called the value of “count” variable will be incremented. "
},
{
"code": null,
"e": 25825,
"s": 25784,
"text": "Way to create an object of Semaphore : "
},
{
"code": null,
"e": 26006,
"s": 25825,
"text": "Case 1 : "
},
{
"code": null,
"e": 26030,
"s": 26006,
"text": "object_name.Semaphore()"
},
{
"code": null,
"e": 26183,
"s": 26030,
"text": "In this case, by default value of the count variable is 1 due to which only one thread is allowed to access. It is exactly the same as the Lock concept."
},
{
"code": null,
"e": 26193,
"s": 26183,
"text": "Case 2 : "
},
{
"code": null,
"e": 26219,
"s": 26193,
"text": "object_name.Semaphore(n) "
},
{
"code": null,
"e": 26358,
"s": 26219,
"text": "In this case, a Semaphore object can be accessed by n Threads at a time. The remaining Threads have to wait until releasing the semaphore."
},
{
"code": null,
"e": 26390,
"s": 26358,
"text": "Executable code of Semaphore : "
},
{
"code": null,
"e": 26398,
"s": 26390,
"text": "Python3"
},
{
"code": "# importing the modulesfrom threading import * import time # creating thread instance where count = 3obj = Semaphore(3) # creating instancedef display(name): # calling acquire method obj.acquire() for i in range(5): print('Hello, ', end = '') time.sleep(1) print(name) # calling release method obj.release() # creating multiple thread t1 = Thread(target = display , args = ('Thread-1',))t2 = Thread(target = display , args = ('Thread-2',))t3 = Thread(target = display , args = ('Thread-3',))t4 = Thread(target = display , args = ('Thread-4',))t5 = Thread(target = display , args = ('Thread-5',)) # calling the threads t1.start()t2.start()t3.start()t4.start()t5.start()",
"e": 27185,
"s": 26398,
"text": null
},
{
"code": null,
"e": 27193,
"s": 27185,
"text": "Output:"
},
{
"code": null,
"e": 27806,
"s": 27197,
"text": "Here in the above example first we created an instance of Semaphore Class where the value of “count” is 3 it means that Semaphore Object can be accessed by 3 Threads at a time. Now we have created display() method which will print the Thread name 5 times. Now we created 5 threads and now whenever we call start() method at that time 3 Threads are allowed to access Semaphore objects and hence 3 Threads are allowed to execute display() method at a time but in this example whenever we will execute we will get irregular output because 3 Threads are executing display() method at a time. "
},
{
"code": null,
"e": 27821,
"s": 27806,
"text": "python-utility"
},
{
"code": null,
"e": 27847,
"s": 27821,
"text": "Advanced Computer Subject"
},
{
"code": null,
"e": 27854,
"s": 27847,
"text": "Python"
},
{
"code": null,
"e": 27952,
"s": 27854,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 27975,
"s": 27952,
"text": "ML | Linear Regression"
},
{
"code": null,
"e": 27989,
"s": 27975,
"text": "Decision Tree"
},
{
"code": null,
"e": 28033,
"s": 27989,
"text": "Copying Files to and from Docker Containers"
},
{
"code": null,
"e": 28056,
"s": 28033,
"text": "System Design Tutorial"
},
{
"code": null,
"e": 28094,
"s": 28056,
"text": "Python | Decision tree implementation"
},
{
"code": null,
"e": 28122,
"s": 28094,
"text": "Read JSON file using Python"
},
{
"code": null,
"e": 28172,
"s": 28122,
"text": "Adding new column to existing DataFrame in Pandas"
},
{
"code": null,
"e": 28194,
"s": 28172,
"text": "Python map() function"
}
] |
Python Module for easy data pre-processing for beginners | by Benjamin Lau | Towards Data Science | Features in structured data can come in many forms including continuous, categorical, datetime and more. Normally to build a predictive model, we would look at feature selection or feature engineering to gather more insights or input more relevant data into the model. However, in cases where the data has a large number of features, feature engineering can become overwhelming fast. There is a need to process these data quickly and create an initial model to better understand your dataset or the problem at hand. Creating a model before any feature engineering has the benefits of:
Knowing the relative features importance of all your featuresHaving a rough idea of the model that works and those that don'tGives the insight to help with feature engineering/ features selection
Knowing the relative features importance of all your features
Having a rough idea of the model that works and those that don't
Gives the insight to help with feature engineering/ features selection
Introduction to Machine Learning for Coders from fast.ai used this exact approach and implemented what Jeremy Howard referred to as ‘Machine Learning Driven EDA’. Exploratory data analysis was done according to what the model tells you instead of domain knowledge or pre-determine assumption of the problems.
Here I present a simple implementation of data preprocessing with a python module I wrote.
The module can be found in my GitHub at https://github.com/Benlau93/easy_processing
You can download the module and place it in the same directory as your notebook and import using
import easy_processing as ep
To test the module, I will be using it for 2 datasets from kaggle competition. One will be for a regression problem and the other for a classification task. Both use RandomForest model from the sklearn.ensemble library.
Firstly, the House Prices: Advanced Regression Techniques dataset.
import libraries and dataset
import numpy as npimport pandas as pddf = pd.read_csv("train.csv",low_memory=False)X = df.drop(["SalePrice"],axis = 1)y=df["SalePrice"]
We start with handling missing values in our data. proc_miss replace NaN in continuous variables with the median of non-missing values in the respective feature columns
X, missing_val = ep.proc_miss(X)
missing_val that was returned is a dictionary with the column that contains missing values as keys and the median replaced as values
To process categorical variables, proc_cat convert categorical columns given by the user as a list into pandas categorical object. In the event that cat_cols is not given, columns with ‘object’ dtype are converted instead. max_cardi is the maximum cardinality of the features that will be converted to dummies variables. Cardinality just refer to the number of classes in each categorical features.
X, cat_dict = ep.proc_cat(X,max_cardi=5)
cat_dict returned is a dictionary with the categorical columns as keys and the Series.cat.categories as values
With just 2 lines of code, your data is ready to enter into a model. To check if all your features are in numeric format,
Training the model,
from sklearn.ensemble import RandomForestRegressorm = RandomForestRegressor(n_jobs=-1)m.fit(X,y)m.score(X,y)
The score obtained is 0.9711 (R2)
We can now test it on our testing dataset, get an initial prediction, submit to kaggle and get an initial score.
df_test = pd.read_csv("test.csv",low_memory=False)X_test, missing_val = ep.proc_miss(df_test,missing_val)X_test, cat_dict = ep.proc_cat(X_test,cat_dict=cat_dict,max_cardi=5)y_pred = m.predict(X_test)
For test/validation set, proc_miss requires a missing_val parameter so that it replaces the same median in each column of the test set. In cases where missing values are found in a column of the test set that isn't in the training set, the missing_val variables will be updated. The same logic applies to proc_cat where cat_dict is required as a parameter to ensure the encoding is consistent.
y_pred can now be exported into csv format and submit to kaggle. The score obtained for this dataset is 0.15296, which is top 68% in the leaderboard. Now you can look at the relative feature importance, hyperparameter tuning, and feature engineering to further improve your score.
The second dataset I will be using the Prudential Life Insurance Assessment
Loading of libraries and data
import numpy as npimport pandas as pdimport easy_processing as epdf = pd.read_csv("insurance_train.csv",low_memory=False)X = df.drop(["Response"],axis = 1)y=df["Response"]
Going through the exact same steps as before but using RandomForestClassifier instead of RandomForestRegressor
X, missing_val = ep.proc_miss(X)X, cat_dict = ep.proc_cat(X,max_cardi=5)from sklearn.ensemble import RandomForestClassifierm = RandomForestClassifier(n_jobs=-1)m.fit(X,y)m.score(X,y)
The score obtained here was 0.98939054
Processing the test set,
df_test = pd.read_csv("insurance_test.csv",low_memory=False)X_test, missing_val = ep.proc_miss(df_test,missing_val)X_test, cat_dict = ep.proc_cat(X_test,cat_dict=cat_dict,max_cardi=5)y_pred = m.predict(X_test)
After submitting y_pred to kaggle, I attained a score of 0.50516 in public score and 0.51187 in private leaderboard. Not remotely good enough but it is a start.
Disclaimer: fastai has a similar, more optimized and efficient library for this. My implementation is a concise version which can help beginner to go through the whole code and understand each implementation under the hood. All documentation can also be found in the GitHub (https://github.com/Benlau93/easy_processing).
Thanks for reading. | [
{
"code": null,
"e": 757,
"s": 172,
"text": "Features in structured data can come in many forms including continuous, categorical, datetime and more. Normally to build a predictive model, we would look at feature selection or feature engineering to gather more insights or input more relevant data into the model. However, in cases where the data has a large number of features, feature engineering can become overwhelming fast. There is a need to process these data quickly and create an initial model to better understand your dataset or the problem at hand. Creating a model before any feature engineering has the benefits of:"
},
{
"code": null,
"e": 953,
"s": 757,
"text": "Knowing the relative features importance of all your featuresHaving a rough idea of the model that works and those that don'tGives the insight to help with feature engineering/ features selection"
},
{
"code": null,
"e": 1015,
"s": 953,
"text": "Knowing the relative features importance of all your features"
},
{
"code": null,
"e": 1080,
"s": 1015,
"text": "Having a rough idea of the model that works and those that don't"
},
{
"code": null,
"e": 1151,
"s": 1080,
"text": "Gives the insight to help with feature engineering/ features selection"
},
{
"code": null,
"e": 1460,
"s": 1151,
"text": "Introduction to Machine Learning for Coders from fast.ai used this exact approach and implemented what Jeremy Howard referred to as ‘Machine Learning Driven EDA’. Exploratory data analysis was done according to what the model tells you instead of domain knowledge or pre-determine assumption of the problems."
},
{
"code": null,
"e": 1551,
"s": 1460,
"text": "Here I present a simple implementation of data preprocessing with a python module I wrote."
},
{
"code": null,
"e": 1635,
"s": 1551,
"text": "The module can be found in my GitHub at https://github.com/Benlau93/easy_processing"
},
{
"code": null,
"e": 1732,
"s": 1635,
"text": "You can download the module and place it in the same directory as your notebook and import using"
},
{
"code": null,
"e": 1761,
"s": 1732,
"text": "import easy_processing as ep"
},
{
"code": null,
"e": 1981,
"s": 1761,
"text": "To test the module, I will be using it for 2 datasets from kaggle competition. One will be for a regression problem and the other for a classification task. Both use RandomForest model from the sklearn.ensemble library."
},
{
"code": null,
"e": 2048,
"s": 1981,
"text": "Firstly, the House Prices: Advanced Regression Techniques dataset."
},
{
"code": null,
"e": 2077,
"s": 2048,
"text": "import libraries and dataset"
},
{
"code": null,
"e": 2213,
"s": 2077,
"text": "import numpy as npimport pandas as pddf = pd.read_csv(\"train.csv\",low_memory=False)X = df.drop([\"SalePrice\"],axis = 1)y=df[\"SalePrice\"]"
},
{
"code": null,
"e": 2382,
"s": 2213,
"text": "We start with handling missing values in our data. proc_miss replace NaN in continuous variables with the median of non-missing values in the respective feature columns"
},
{
"code": null,
"e": 2415,
"s": 2382,
"text": "X, missing_val = ep.proc_miss(X)"
},
{
"code": null,
"e": 2548,
"s": 2415,
"text": "missing_val that was returned is a dictionary with the column that contains missing values as keys and the median replaced as values"
},
{
"code": null,
"e": 2947,
"s": 2548,
"text": "To process categorical variables, proc_cat convert categorical columns given by the user as a list into pandas categorical object. In the event that cat_cols is not given, columns with ‘object’ dtype are converted instead. max_cardi is the maximum cardinality of the features that will be converted to dummies variables. Cardinality just refer to the number of classes in each categorical features."
},
{
"code": null,
"e": 2988,
"s": 2947,
"text": "X, cat_dict = ep.proc_cat(X,max_cardi=5)"
},
{
"code": null,
"e": 3099,
"s": 2988,
"text": "cat_dict returned is a dictionary with the categorical columns as keys and the Series.cat.categories as values"
},
{
"code": null,
"e": 3221,
"s": 3099,
"text": "With just 2 lines of code, your data is ready to enter into a model. To check if all your features are in numeric format,"
},
{
"code": null,
"e": 3241,
"s": 3221,
"text": "Training the model,"
},
{
"code": null,
"e": 3350,
"s": 3241,
"text": "from sklearn.ensemble import RandomForestRegressorm = RandomForestRegressor(n_jobs=-1)m.fit(X,y)m.score(X,y)"
},
{
"code": null,
"e": 3384,
"s": 3350,
"text": "The score obtained is 0.9711 (R2)"
},
{
"code": null,
"e": 3497,
"s": 3384,
"text": "We can now test it on our testing dataset, get an initial prediction, submit to kaggle and get an initial score."
},
{
"code": null,
"e": 3697,
"s": 3497,
"text": "df_test = pd.read_csv(\"test.csv\",low_memory=False)X_test, missing_val = ep.proc_miss(df_test,missing_val)X_test, cat_dict = ep.proc_cat(X_test,cat_dict=cat_dict,max_cardi=5)y_pred = m.predict(X_test)"
},
{
"code": null,
"e": 4091,
"s": 3697,
"text": "For test/validation set, proc_miss requires a missing_val parameter so that it replaces the same median in each column of the test set. In cases where missing values are found in a column of the test set that isn't in the training set, the missing_val variables will be updated. The same logic applies to proc_cat where cat_dict is required as a parameter to ensure the encoding is consistent."
},
{
"code": null,
"e": 4372,
"s": 4091,
"text": "y_pred can now be exported into csv format and submit to kaggle. The score obtained for this dataset is 0.15296, which is top 68% in the leaderboard. Now you can look at the relative feature importance, hyperparameter tuning, and feature engineering to further improve your score."
},
{
"code": null,
"e": 4448,
"s": 4372,
"text": "The second dataset I will be using the Prudential Life Insurance Assessment"
},
{
"code": null,
"e": 4478,
"s": 4448,
"text": "Loading of libraries and data"
},
{
"code": null,
"e": 4650,
"s": 4478,
"text": "import numpy as npimport pandas as pdimport easy_processing as epdf = pd.read_csv(\"insurance_train.csv\",low_memory=False)X = df.drop([\"Response\"],axis = 1)y=df[\"Response\"]"
},
{
"code": null,
"e": 4761,
"s": 4650,
"text": "Going through the exact same steps as before but using RandomForestClassifier instead of RandomForestRegressor"
},
{
"code": null,
"e": 4944,
"s": 4761,
"text": "X, missing_val = ep.proc_miss(X)X, cat_dict = ep.proc_cat(X,max_cardi=5)from sklearn.ensemble import RandomForestClassifierm = RandomForestClassifier(n_jobs=-1)m.fit(X,y)m.score(X,y)"
},
{
"code": null,
"e": 4983,
"s": 4944,
"text": "The score obtained here was 0.98939054"
},
{
"code": null,
"e": 5008,
"s": 4983,
"text": "Processing the test set,"
},
{
"code": null,
"e": 5218,
"s": 5008,
"text": "df_test = pd.read_csv(\"insurance_test.csv\",low_memory=False)X_test, missing_val = ep.proc_miss(df_test,missing_val)X_test, cat_dict = ep.proc_cat(X_test,cat_dict=cat_dict,max_cardi=5)y_pred = m.predict(X_test)"
},
{
"code": null,
"e": 5379,
"s": 5218,
"text": "After submitting y_pred to kaggle, I attained a score of 0.50516 in public score and 0.51187 in private leaderboard. Not remotely good enough but it is a start."
},
{
"code": null,
"e": 5700,
"s": 5379,
"text": "Disclaimer: fastai has a similar, more optimized and efficient library for this. My implementation is a concise version which can help beginner to go through the whole code and understand each implementation under the hood. All documentation can also be found in the GitHub (https://github.com/Benlau93/easy_processing)."
}
] |
Convert an image into Blur using HTML/CSS - GeeksforGeeks | 16 Feb, 2019
Given an image and the task is to convert the image into blur image using CSS property. In CSS, filter property is used to convert an image into blur image. Filter property is mainly used to set the visual effect of an image.
Syntax:
filter: blur()
Example 1: This example use blur filter to convert the image into blur image.
Original Image:
<!DOCTYPE html> <html> <head> <title>Convert into blur image</title> <style> img { -webkit-filter: blur(4px); filter: blur(4px); } h1 { color:green; } </style> </head> <body> <center> <h1>GeeksforGeeks</h1> <h2>Blur Image</h2> <img src= "https://media.geeksforgeeks.org/wp-content/uploads/interview-preparation-2.png" width="500px" height="250px" alt="filter applied" /> </center> </body> </html>
Output:
Example 2: This example use blur filter to create background blur image.Original Image:
<!DOCTYPE html> <html> <head> <title> Convert into blur image </title> <style> img { -webkit-filter: blur(4px); filter: blur(4px); } h1 { color:green; } .backgr-text { position: absolute; top: 20%; left: 50%; transform: translate(-50%, -50%); text-align: center; } </style> </head> <body> <center> <img src= "https://media.geeksforgeeks.org/wp-content/uploads/geeksforgeeks-logo.png" width="500px" height="250px" alt="filter applied" /> <div class="backgr-text"> <h1>GeeksforGeeks</h1> <h2>Blurred Background Image</h2> </div> </center> </body> </html>
Output:
CSS-Misc
CSS
Web Technologies
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Top 10 Projects For Beginners To Practice HTML and CSS Skills
How to insert spaces/tabs in text using HTML/CSS?
How to create footer to stay at the bottom of a Web page?
How to update Node.js and NPM to next version ?
CSS to put icon inside an input element in a form
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
Convert a string to an integer in JavaScript | [
{
"code": null,
"e": 24846,
"s": 24818,
"text": "\n16 Feb, 2019"
},
{
"code": null,
"e": 25072,
"s": 24846,
"text": "Given an image and the task is to convert the image into blur image using CSS property. In CSS, filter property is used to convert an image into blur image. Filter property is mainly used to set the visual effect of an image."
},
{
"code": null,
"e": 25080,
"s": 25072,
"text": "Syntax:"
},
{
"code": null,
"e": 25096,
"s": 25080,
"text": "filter: blur()\n"
},
{
"code": null,
"e": 25174,
"s": 25096,
"text": "Example 1: This example use blur filter to convert the image into blur image."
},
{
"code": null,
"e": 25190,
"s": 25174,
"text": "Original Image:"
},
{
"code": "<!DOCTYPE html> <html> <head> <title>Convert into blur image</title> <style> img { -webkit-filter: blur(4px); filter: blur(4px); } h1 { color:green; } </style> </head> <body> <center> <h1>GeeksforGeeks</h1> <h2>Blur Image</h2> <img src= \"https://media.geeksforgeeks.org/wp-content/uploads/interview-preparation-2.png\" width=\"500px\" height=\"250px\" alt=\"filter applied\" /> </center> </body> </html> ",
"e": 25771,
"s": 25190,
"text": null
},
{
"code": null,
"e": 25779,
"s": 25771,
"text": "Output:"
},
{
"code": null,
"e": 25867,
"s": 25779,
"text": "Example 2: This example use blur filter to create background blur image.Original Image:"
},
{
"code": "<!DOCTYPE html> <html> <head> <title> Convert into blur image </title> <style> img { -webkit-filter: blur(4px); filter: blur(4px); } h1 { color:green; } .backgr-text { position: absolute; top: 20%; left: 50%; transform: translate(-50%, -50%); text-align: center; } </style> </head> <body> <center> <img src= \"https://media.geeksforgeeks.org/wp-content/uploads/geeksforgeeks-logo.png\" width=\"500px\" height=\"250px\" alt=\"filter applied\" /> <div class=\"backgr-text\"> <h1>GeeksforGeeks</h1> <h2>Blurred Background Image</h2> </div> </center> </body> </html> ",
"e": 26808,
"s": 25867,
"text": null
},
{
"code": null,
"e": 26816,
"s": 26808,
"text": "Output:"
},
{
"code": null,
"e": 26825,
"s": 26816,
"text": "CSS-Misc"
},
{
"code": null,
"e": 26829,
"s": 26825,
"text": "CSS"
},
{
"code": null,
"e": 26846,
"s": 26829,
"text": "Web Technologies"
},
{
"code": null,
"e": 26944,
"s": 26846,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 27006,
"s": 26944,
"text": "Top 10 Projects For Beginners To Practice HTML and CSS Skills"
},
{
"code": null,
"e": 27056,
"s": 27006,
"text": "How to insert spaces/tabs in text using HTML/CSS?"
},
{
"code": null,
"e": 27114,
"s": 27056,
"text": "How to create footer to stay at the bottom of a Web page?"
},
{
"code": null,
"e": 27162,
"s": 27114,
"text": "How to update Node.js and NPM to next version ?"
},
{
"code": null,
"e": 27212,
"s": 27162,
"text": "CSS to put icon inside an input element in a form"
},
{
"code": null,
"e": 27254,
"s": 27212,
"text": "Roadmap to Become a Web Developer in 2022"
},
{
"code": null,
"e": 27287,
"s": 27254,
"text": "Installation of Node.js on Linux"
},
{
"code": null,
"e": 27330,
"s": 27287,
"text": "How to fetch data from an API in ReactJS ?"
},
{
"code": null,
"e": 27392,
"s": 27330,
"text": "Top 10 Projects For Beginners To Practice HTML and CSS Skills"
}
] |
How to style an hr element with CSS? | To style an hr element with CSS, the code is as follows −
Live Demo
<!DOCTYPE html>
<html>
<meta name="viewport" content="width=device-width, initial-scale=1">
<head>
<style>
body{
font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif;
margin: 20px;
}
hr{
margin-bottom: 20px;
}
.solid {
border-top: 5px solid rgb(16, 2, 141);
}
.dashed {
border-top: 5px dashed rgb(190, 13, 146);
}
.double {
border-top: 5px double rgb(22, 145, 11);
}
.dotted {
border: 5px dotted rgb(200, 255, 0);
}
.round {
border: 5px solid rgb(35, 196, 142);
border-radius: 5px;
}
</style>
</head>
<body>
<h1 style="text-align: center;">HR styling example</h1>
<hr class="solid">
<hr class="dashed">
<hr class="double">
<hr class="dotted">
<hr class="round">
</body>
</html>
The above code will produce the following output − | [
{
"code": null,
"e": 1120,
"s": 1062,
"text": "To style an hr element with CSS, the code is as follows −"
},
{
"code": null,
"e": 1131,
"s": 1120,
"text": " Live Demo"
},
{
"code": null,
"e": 1913,
"s": 1131,
"text": "<!DOCTYPE html>\n<html>\n<meta name=\"viewport\" content=\"width=device-width, initial-scale=1\">\n<head>\n<style>\n body{\n font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif;\n margin: 20px;\n }\n hr{\n margin-bottom: 20px;\n }\n .solid {\n border-top: 5px solid rgb(16, 2, 141);\n }\n .dashed {\n border-top: 5px dashed rgb(190, 13, 146);\n }\n .double {\n border-top: 5px double rgb(22, 145, 11);\n }\n .dotted {\n border: 5px dotted rgb(200, 255, 0);\n }\n .round {\n border: 5px solid rgb(35, 196, 142);\n border-radius: 5px;\n }\n</style>\n</head>\n<body>\n<h1 style=\"text-align: center;\">HR styling example</h1>\n<hr class=\"solid\">\n<hr class=\"dashed\">\n<hr class=\"double\">\n<hr class=\"dotted\">\n<hr class=\"round\">\n</body>\n</html>"
},
{
"code": null,
"e": 1964,
"s": 1913,
"text": "The above code will produce the following output −"
}
] |
Generating Fractals with Blender and Animation-Nodes | by 5agado | Towards Data Science | What: this is a collection of tutorials, examples and resources for generating fractals visuals using Blender. I’ll cover topics such as recursion, n-flakes, L-systems, Mandelbrot/Julia sets and derivations.
Why: if you are fascinated by fractals patterns, interested in procedural generation in Blender and want to get a better understanding and hands-on experience of animation-nodes and shader nodes.
Who: all content here is based on Blender 2.8.2 and animation-nodes v2.1. I also relied on a few short code snippets (Python ≥ 3.6).
“beautifully intricate, yet so simple”
Fractals are shapes with fractal dimensions. This derives from the way we measure them as they scale. Theoretical fractals are infinitely self-similar across different scales.
For our setup, we are not concerned with pure theoretical fractals, as those are not achievable in Blender, unless under very specific circumstances. We mostly care about fine structure (details at different scales) and a natural appearance of self-similarity (made up of apparent smaller copies of itself).
Additional suggested resources to learn more about fractals:
[YouTube] 3Blue1Brown on Fractals
[Book] The Fractal Geometry of Nature by Benoît B. Mandelbrot
[Book] Fractals: A Very Short Introduction by Kenneth Falconer
[Book] The Algorithmic Beauty of Plants by Przemysław Prusinkiewicz
An n-flake (or polyflake) is a fractal constructed by replacing an initial shape with multiple scaled copies of itself, generally placed in correspondence to vertices and center. The process is then repeated recursively for each new shape.
This is a good starting point for our exploration of fractals, as it allows us to cover recursion and other important concepts via a simple animation-nodes setup.
Which brings us to our main issue: animation-nodes doesn’t (currently) support pure recursion. We need some workarounds. One option is always to rely on pure Python scripting, as I explained in a previous entry, but I wanted the focus of this piece to be more on animation-nodes, so what we can do is to approximate recursion via iterations and loop queues.
The idea is to rely on the Loop Input Reassign option to keep a queue of results which we can then be processed in the next iteration.
Let’s consider the n-flake case for regular polygons. Given a number of segments n(the number of sides of the polygon), a radius r and center c, we compute the points of the n-polygon centered in c with radius r. For each new computed point p we repeat this procedure (that is, finding the polygon centered in p), but resizing the radius r by some predefined factor.
All the main logic resides in the following loop, which takes care of computing the polygon points and new radius, and reassigning it such that the next iteration can process them. It is important to understand this part: during the first iteration the loop processes whatever has been given to the Invoke Subprogram node, while for all successive iterations the loop will process the values that it updated in the previous iteration. Each time these are cleaned-up, and that’s why we maintain two queues (centers_queue and all_centers), the former is the centers we haven’t yet processed, the latter is a collection of all centers computed so far, which will be used as output to create our list of splines.
The two subprograms are both Python script. These are examples where I find coding more concise and not necessary to be translated to pure nodes.
Compute the points of a regular polygon:
points = []# compute regular polygon points for each given centerfor center in centers: angle = 2*pi/segments # angle in radians for i in range(segments): x = center[0] + radius*cos(angle*i) y = center[1] + radius*sin(angle*i) z = center[2] # constant z values points.append((x, y, z)) #points.append(points[-segments]) # close the loop
Get scale factor:
from math import cos, pi# compute scale factor for any n-flake# https://en.wikipedia.org/wiki/N-flakecumulative = 0for i in range(0, segments//4): cumulative += cos(2*pi*(i+1) / segments)scale_factor = 1 / (2*(1 + cumulative))
The additional loop setup is to split points such that each polygon is converted to a separate spline.
We can easily adapt this setup to work with regular solids. This time, instead of computing the shape vertices ourselves, we just rely on an object already present in the scene, get its vertices and recursively transform them. We leverage matrix properties and the Compose Matrix node to minimize the amount of work or nodes required. Here the setup
Out matrix_queue is initialized with an identity transformation matrix (no translation, no rotation and unit scale) while our transformation list is our target/input object vertices locations composed with an arbitrary scale factor, which is equivalent to say “shift everything there, and scale by the given factor” when used to transform another matrix.Here the adapted recursive part which executes the transformation loop and reassign operations.
Sample results for platonic solids (between four and five iterations).
One can then update the original translation matrix, such that the new solids are not placed exactly on predecessor vertices, but instead on any point of the line passing through the predecessor center and new vertex, as illustrated in the side animation.
While previously the translation matrices were purely the vertices location, we are now doing some vector math to shift such points from the original location. If we subtract from them the object center, we obtain the direction vector of interest. We can then divide this by arbitrary values to place the new recursive solids accordingly.
If we instantiate only objects of the last iteration we obtain proper platonic solid fractals. Well known examples are the Sierpinski tetrahedron and the Menger Sponge.
arbitrary/random change of polyflake type across recursive steps
use of displacement maps to simulate additional recursive steps without the need of creating the finer-details additional geometry
volumetric and pure shader nodes setup
An L-system (or Lindenmayer system) is a grammar; something that specifies how to generate textual strings via a set of rules, an alphabet and initial axioms. It is accompanied by a translation mechanism to transform such strings to geometry.
We are interested in L-systems because they can be used to generate self-similar fractals and also because we kinda get them for free out-of-the-box with animation-nodes via LSystem node. Here an example setup that instantiates the results to object.
The one on the side is a fractal-plat configuration defined by axiom X (the initial state) and two rules X=F[+X][-X]FX and F=FF . The node takes care of evolving the system for the specified number of generations, which nicely enough can be fractional, allowing for smooth transitions. It also converts textual results to a mesh. For this reason you will have to follow the specified convention for axioms and alphabet usage.
Another important parameter to consider is Symbol Limit in the advanced node settings, which specifies the maximum length of the generated string. The system will throw an error if exceeding this limit.
dragon curve - axiom: FX, rules: (X=X+YF, Y=-FX-Y), angle: 90fractal plant - axiom: F, rules: (F=FF-[-F+F+F]+[+F-F-F]), angle: 22.5sierpinski triangle - axiom: F-F1-F1, rules: (X=X+YF, Y=-FX-Y), angle: 120
3D L-systems (e.g. azimuth + inclination) and stochastic L-systems. (see Python code)
Step size rule, proportional to growth such that view can be kept constant while increasing generations
As the father of fractals, it is of no surprise that the most common and frequently displayed fractals bear his name. Together with Julia sets, the Mandelbrot set provide theoretical foundation for a phenomenon that is again defined by simple rules, but able to generate an infinite picture of beauty and intricacy.
We can think of these sets as “iteration of functions expressed in coordinate form”, in which we are dealing with the plane of complex numbers. This entry by Jeremy Behreandt provides an impressively detailed introduction to complex numbers, Mandelbrot Set and much more, and all in Blender’s Python API and Open Shading Language (OSL).
We can achieve similar results purely in Blender nodes (no scripting), but as usual we are limited by the missing iterative/recursive capabilities of the setup. The basic idea is to move around the plane of complex number as dictated by the formula
coloring each point based on the speed to which it converges to infinite. Here z is our starting point, and c can be an arbitrarily chosen complex number. The formula can be rewritten in pure cartesian-plane coordinates form as
where we now have (x,y) as our point, and a and b as our control values (the real and imaginary part of our previous c).Here the translation of the formula in shader nodes setup
The iterations_count part is used to keep track of valid iterations, the ones for which the point didn’t diverge. For practical purposes, this can be approximated by checking that the vector magnitude is less than two.
We can then plug in our texture coordinate, by separating x and y as illustrated. Reusing them for a and b gives us the Mandebrot set, or we can otherwise pass custom values to explore other sets and results.Now the ugly part: we have to approximate the function iterations via a very-non-elegant copy-and-paste mess, which for me ended up looking something like this. 100 iterations is a decent estimate to provide good results, the more you add the more fine details you get, but the setup can quickly become slow.
But at least we now have something to play with
The Mandelbulb is a projection in 3D of the Mandelbrot set. Again there is already an awesome tutorial out there by Jonas Dichelle explaining how to simulate a Mandelbulb in Blender nodes and Eevee. Given that the method relies on volumetrics, it’s worth referencing also this Blender Conference talk by Gleb Alexandrov about 3D Nebulae.
I have always been captivated by phenomena that exhibit complexity out of simple rules, and the ability to visualize them makes it all even more intriguing. Blender just makes it so easy, and animation-nodes is just one more addition to an already present set of amazing tools/utils, especially from a procedural point of view.
I admit that getting a couple of steps away from pure coding feels a bit frightening to me, like a visceral feeling I’m not doing the right thing, but there is no doubt about the efficiency one can achieve my using nodes, from an iterative and experimental point of view. I still believe some parts are better suited as separate scripts, and also that people should always build/understand basics first with code, as it provides a better framework for complexity breakdown and organizations as well as problem-solving generalization.
I am planning to explore more of similar topics, refining both a theoretical understanding and practical capabilities to reproduce them in a compelling way.
In particular these are the current top entries:
beyond 3 dimensions
cellular automata
morphogenesis
reaction diffusion
strange attractors
tessellation
epicycles
I welcome any suggestions, critiques and feedback.
You can see more of my “polished” graphics results on Instagram, read more technical/breakdown explanations on Twitter and try out my code on Github. | [
{
"code": null,
"e": 379,
"s": 171,
"text": "What: this is a collection of tutorials, examples and resources for generating fractals visuals using Blender. I’ll cover topics such as recursion, n-flakes, L-systems, Mandelbrot/Julia sets and derivations."
},
{
"code": null,
"e": 575,
"s": 379,
"text": "Why: if you are fascinated by fractals patterns, interested in procedural generation in Blender and want to get a better understanding and hands-on experience of animation-nodes and shader nodes."
},
{
"code": null,
"e": 708,
"s": 575,
"text": "Who: all content here is based on Blender 2.8.2 and animation-nodes v2.1. I also relied on a few short code snippets (Python ≥ 3.6)."
},
{
"code": null,
"e": 747,
"s": 708,
"text": "“beautifully intricate, yet so simple”"
},
{
"code": null,
"e": 923,
"s": 747,
"text": "Fractals are shapes with fractal dimensions. This derives from the way we measure them as they scale. Theoretical fractals are infinitely self-similar across different scales."
},
{
"code": null,
"e": 1231,
"s": 923,
"text": "For our setup, we are not concerned with pure theoretical fractals, as those are not achievable in Blender, unless under very specific circumstances. We mostly care about fine structure (details at different scales) and a natural appearance of self-similarity (made up of apparent smaller copies of itself)."
},
{
"code": null,
"e": 1292,
"s": 1231,
"text": "Additional suggested resources to learn more about fractals:"
},
{
"code": null,
"e": 1326,
"s": 1292,
"text": "[YouTube] 3Blue1Brown on Fractals"
},
{
"code": null,
"e": 1389,
"s": 1326,
"text": "[Book] The Fractal Geometry of Nature by Benoît B. Mandelbrot"
},
{
"code": null,
"e": 1452,
"s": 1389,
"text": "[Book] Fractals: A Very Short Introduction by Kenneth Falconer"
},
{
"code": null,
"e": 1520,
"s": 1452,
"text": "[Book] The Algorithmic Beauty of Plants by Przemysław Prusinkiewicz"
},
{
"code": null,
"e": 1760,
"s": 1520,
"text": "An n-flake (or polyflake) is a fractal constructed by replacing an initial shape with multiple scaled copies of itself, generally placed in correspondence to vertices and center. The process is then repeated recursively for each new shape."
},
{
"code": null,
"e": 1923,
"s": 1760,
"text": "This is a good starting point for our exploration of fractals, as it allows us to cover recursion and other important concepts via a simple animation-nodes setup."
},
{
"code": null,
"e": 2281,
"s": 1923,
"text": "Which brings us to our main issue: animation-nodes doesn’t (currently) support pure recursion. We need some workarounds. One option is always to rely on pure Python scripting, as I explained in a previous entry, but I wanted the focus of this piece to be more on animation-nodes, so what we can do is to approximate recursion via iterations and loop queues."
},
{
"code": null,
"e": 2416,
"s": 2281,
"text": "The idea is to rely on the Loop Input Reassign option to keep a queue of results which we can then be processed in the next iteration."
},
{
"code": null,
"e": 2783,
"s": 2416,
"text": "Let’s consider the n-flake case for regular polygons. Given a number of segments n(the number of sides of the polygon), a radius r and center c, we compute the points of the n-polygon centered in c with radius r. For each new computed point p we repeat this procedure (that is, finding the polygon centered in p), but resizing the radius r by some predefined factor."
},
{
"code": null,
"e": 3492,
"s": 2783,
"text": "All the main logic resides in the following loop, which takes care of computing the polygon points and new radius, and reassigning it such that the next iteration can process them. It is important to understand this part: during the first iteration the loop processes whatever has been given to the Invoke Subprogram node, while for all successive iterations the loop will process the values that it updated in the previous iteration. Each time these are cleaned-up, and that’s why we maintain two queues (centers_queue and all_centers), the former is the centers we haven’t yet processed, the latter is a collection of all centers computed so far, which will be used as output to create our list of splines."
},
{
"code": null,
"e": 3638,
"s": 3492,
"text": "The two subprograms are both Python script. These are examples where I find coding more concise and not necessary to be translated to pure nodes."
},
{
"code": null,
"e": 3679,
"s": 3638,
"text": "Compute the points of a regular polygon:"
},
{
"code": null,
"e": 4057,
"s": 3679,
"text": "points = []# compute regular polygon points for each given centerfor center in centers: angle = 2*pi/segments # angle in radians for i in range(segments): x = center[0] + radius*cos(angle*i) y = center[1] + radius*sin(angle*i) z = center[2] # constant z values points.append((x, y, z)) #points.append(points[-segments]) # close the loop"
},
{
"code": null,
"e": 4075,
"s": 4057,
"text": "Get scale factor:"
},
{
"code": null,
"e": 4305,
"s": 4075,
"text": "from math import cos, pi# compute scale factor for any n-flake# https://en.wikipedia.org/wiki/N-flakecumulative = 0for i in range(0, segments//4): cumulative += cos(2*pi*(i+1) / segments)scale_factor = 1 / (2*(1 + cumulative))"
},
{
"code": null,
"e": 4408,
"s": 4305,
"text": "The additional loop setup is to split points such that each polygon is converted to a separate spline."
},
{
"code": null,
"e": 4758,
"s": 4408,
"text": "We can easily adapt this setup to work with regular solids. This time, instead of computing the shape vertices ourselves, we just rely on an object already present in the scene, get its vertices and recursively transform them. We leverage matrix properties and the Compose Matrix node to minimize the amount of work or nodes required. Here the setup"
},
{
"code": null,
"e": 5208,
"s": 4758,
"text": "Out matrix_queue is initialized with an identity transformation matrix (no translation, no rotation and unit scale) while our transformation list is our target/input object vertices locations composed with an arbitrary scale factor, which is equivalent to say “shift everything there, and scale by the given factor” when used to transform another matrix.Here the adapted recursive part which executes the transformation loop and reassign operations."
},
{
"code": null,
"e": 5279,
"s": 5208,
"text": "Sample results for platonic solids (between four and five iterations)."
},
{
"code": null,
"e": 5535,
"s": 5279,
"text": "One can then update the original translation matrix, such that the new solids are not placed exactly on predecessor vertices, but instead on any point of the line passing through the predecessor center and new vertex, as illustrated in the side animation."
},
{
"code": null,
"e": 5874,
"s": 5535,
"text": "While previously the translation matrices were purely the vertices location, we are now doing some vector math to shift such points from the original location. If we subtract from them the object center, we obtain the direction vector of interest. We can then divide this by arbitrary values to place the new recursive solids accordingly."
},
{
"code": null,
"e": 6043,
"s": 5874,
"text": "If we instantiate only objects of the last iteration we obtain proper platonic solid fractals. Well known examples are the Sierpinski tetrahedron and the Menger Sponge."
},
{
"code": null,
"e": 6108,
"s": 6043,
"text": "arbitrary/random change of polyflake type across recursive steps"
},
{
"code": null,
"e": 6239,
"s": 6108,
"text": "use of displacement maps to simulate additional recursive steps without the need of creating the finer-details additional geometry"
},
{
"code": null,
"e": 6278,
"s": 6239,
"text": "volumetric and pure shader nodes setup"
},
{
"code": null,
"e": 6521,
"s": 6278,
"text": "An L-system (or Lindenmayer system) is a grammar; something that specifies how to generate textual strings via a set of rules, an alphabet and initial axioms. It is accompanied by a translation mechanism to transform such strings to geometry."
},
{
"code": null,
"e": 6772,
"s": 6521,
"text": "We are interested in L-systems because they can be used to generate self-similar fractals and also because we kinda get them for free out-of-the-box with animation-nodes via LSystem node. Here an example setup that instantiates the results to object."
},
{
"code": null,
"e": 7198,
"s": 6772,
"text": "The one on the side is a fractal-plat configuration defined by axiom X (the initial state) and two rules X=F[+X][-X]FX and F=FF . The node takes care of evolving the system for the specified number of generations, which nicely enough can be fractional, allowing for smooth transitions. It also converts textual results to a mesh. For this reason you will have to follow the specified convention for axioms and alphabet usage."
},
{
"code": null,
"e": 7401,
"s": 7198,
"text": "Another important parameter to consider is Symbol Limit in the advanced node settings, which specifies the maximum length of the generated string. The system will throw an error if exceeding this limit."
},
{
"code": null,
"e": 7607,
"s": 7401,
"text": "dragon curve - axiom: FX, rules: (X=X+YF, Y=-FX-Y), angle: 90fractal plant - axiom: F, rules: (F=FF-[-F+F+F]+[+F-F-F]), angle: 22.5sierpinski triangle - axiom: F-F1-F1, rules: (X=X+YF, Y=-FX-Y), angle: 120"
},
{
"code": null,
"e": 7693,
"s": 7607,
"text": "3D L-systems (e.g. azimuth + inclination) and stochastic L-systems. (see Python code)"
},
{
"code": null,
"e": 7797,
"s": 7693,
"text": "Step size rule, proportional to growth such that view can be kept constant while increasing generations"
},
{
"code": null,
"e": 8113,
"s": 7797,
"text": "As the father of fractals, it is of no surprise that the most common and frequently displayed fractals bear his name. Together with Julia sets, the Mandelbrot set provide theoretical foundation for a phenomenon that is again defined by simple rules, but able to generate an infinite picture of beauty and intricacy."
},
{
"code": null,
"e": 8450,
"s": 8113,
"text": "We can think of these sets as “iteration of functions expressed in coordinate form”, in which we are dealing with the plane of complex numbers. This entry by Jeremy Behreandt provides an impressively detailed introduction to complex numbers, Mandelbrot Set and much more, and all in Blender’s Python API and Open Shading Language (OSL)."
},
{
"code": null,
"e": 8699,
"s": 8450,
"text": "We can achieve similar results purely in Blender nodes (no scripting), but as usual we are limited by the missing iterative/recursive capabilities of the setup. The basic idea is to move around the plane of complex number as dictated by the formula"
},
{
"code": null,
"e": 8927,
"s": 8699,
"text": "coloring each point based on the speed to which it converges to infinite. Here z is our starting point, and c can be an arbitrarily chosen complex number. The formula can be rewritten in pure cartesian-plane coordinates form as"
},
{
"code": null,
"e": 9105,
"s": 8927,
"text": "where we now have (x,y) as our point, and a and b as our control values (the real and imaginary part of our previous c).Here the translation of the formula in shader nodes setup"
},
{
"code": null,
"e": 9324,
"s": 9105,
"text": "The iterations_count part is used to keep track of valid iterations, the ones for which the point didn’t diverge. For practical purposes, this can be approximated by checking that the vector magnitude is less than two."
},
{
"code": null,
"e": 9841,
"s": 9324,
"text": "We can then plug in our texture coordinate, by separating x and y as illustrated. Reusing them for a and b gives us the Mandebrot set, or we can otherwise pass custom values to explore other sets and results.Now the ugly part: we have to approximate the function iterations via a very-non-elegant copy-and-paste mess, which for me ended up looking something like this. 100 iterations is a decent estimate to provide good results, the more you add the more fine details you get, but the setup can quickly become slow."
},
{
"code": null,
"e": 9889,
"s": 9841,
"text": "But at least we now have something to play with"
},
{
"code": null,
"e": 10227,
"s": 9889,
"text": "The Mandelbulb is a projection in 3D of the Mandelbrot set. Again there is already an awesome tutorial out there by Jonas Dichelle explaining how to simulate a Mandelbulb in Blender nodes and Eevee. Given that the method relies on volumetrics, it’s worth referencing also this Blender Conference talk by Gleb Alexandrov about 3D Nebulae."
},
{
"code": null,
"e": 10555,
"s": 10227,
"text": "I have always been captivated by phenomena that exhibit complexity out of simple rules, and the ability to visualize them makes it all even more intriguing. Blender just makes it so easy, and animation-nodes is just one more addition to an already present set of amazing tools/utils, especially from a procedural point of view."
},
{
"code": null,
"e": 11089,
"s": 10555,
"text": "I admit that getting a couple of steps away from pure coding feels a bit frightening to me, like a visceral feeling I’m not doing the right thing, but there is no doubt about the efficiency one can achieve my using nodes, from an iterative and experimental point of view. I still believe some parts are better suited as separate scripts, and also that people should always build/understand basics first with code, as it provides a better framework for complexity breakdown and organizations as well as problem-solving generalization."
},
{
"code": null,
"e": 11246,
"s": 11089,
"text": "I am planning to explore more of similar topics, refining both a theoretical understanding and practical capabilities to reproduce them in a compelling way."
},
{
"code": null,
"e": 11295,
"s": 11246,
"text": "In particular these are the current top entries:"
},
{
"code": null,
"e": 11315,
"s": 11295,
"text": "beyond 3 dimensions"
},
{
"code": null,
"e": 11333,
"s": 11315,
"text": "cellular automata"
},
{
"code": null,
"e": 11347,
"s": 11333,
"text": "morphogenesis"
},
{
"code": null,
"e": 11366,
"s": 11347,
"text": "reaction diffusion"
},
{
"code": null,
"e": 11385,
"s": 11366,
"text": "strange attractors"
},
{
"code": null,
"e": 11398,
"s": 11385,
"text": "tessellation"
},
{
"code": null,
"e": 11408,
"s": 11398,
"text": "epicycles"
},
{
"code": null,
"e": 11459,
"s": 11408,
"text": "I welcome any suggestions, critiques and feedback."
}
] |
Cubic Bezier Curve Implementation in C - GeeksforGeeks | 04 Jan, 2022
What is a bezier curve? So a Bezier curve is a mathematically defined curve used in two-dimensional graphic applications like adobe Illustrator, Inkscape etc. The curve is defined by four points: the initial position and the terminating position i.e P0 and P3 respectively (which are called “anchors”) and two separate middle points i.e P1 and P2(which are called “handles”) in our example. Bezier curves are frequently used in computer graphics, animation, modelling etc.How do we Represent Bezier Curves Mathematically? Bezier curves can be generated under the control of other points. Approximate tangents by using control points are used to generate curve. The Bezier curve can be represented mathematically as – Where is the set of points and represents the Bernstein polynomials i.e. Blending Function which are given by – Where n is the polynomial order, i is the index, and u/t is the variable which has from 0 to 1.Let us define our cubic bezier curve mathematically. So a bezier curve id defined by a set of control points to where n is called its order(n = 1 for linear, n = 2 for quadratic, etc.). The first and last control points are always the endpoints of the curve; however, the intermediate control points (if any) generally do not lie on the curve. For cubic bezier curve order(n) of polynomial is 3 , index(i) vary from i = 0 to i = n i.e. 3 and u will vary from .
Cubic Bezier Curve function is defined as :
Cubic Bezier Curve blending function are defined as :
So and Now,So we will calculate curve x and y pixel by incrementing value of u by 0.0001.
Construction of a cubic Bézier curve
Properties of bezier curves
1. They always pass through the first and last control points.2. They are contained in the convex hull of their defining control points.3. The degree of the polynomial defining the curve segment is one less than the number of defining polygon point. Therefore, for 4 control points, the degree of the polynomial is 3, i.e. cubic polynomial.4. A Bezier curve generally follows the shape of the defining polygon5. The direction of the tangent vector at the endpoints is the same as that of the vector determined by the first and last segments.6. Bezier curves exhibit global control means moving a control point alters the shape of the whole curveNOTE: The following implementation uses the SDL library to draw pixels on the screen. If you are on Debian system like ubuntu just runs following command to install SDL library.
Ex: We are given with four control points B0[1,0], B1[2,2], B2[6,3], B3[8,2], so determine the five points that lie on the curve also draw the curve on the graph.
Ans: Given curve has four control points hence it is a cubic bezier curve, So, the parametric equation of cubic bezier curve is
now, substitute the control points into the above equation so we’ll get,
Let’s assume five different values of t are {0, 0.2, 0.5, 0.7, 1}.
So, for t=0 the coordinate will be,
So, for t=0.2 the coordinate will be,
So, for t=0.5 the coordinate will be,
So, for t=0.7 the coordinate will be,
So, for t=1.0 the coordinate will be,
Fig.1
Drawbacks of Bezier curve:
a) The degree of Bezier curve depends upon the number of control points associated with the corresponding curve, as the number of control points increases the polynomial degree of the curve equation also increases that make the curve equation very complex and harder to deal with.
Degree of curve = no. of control points - 1
b) One major disadvantage of using the Bezier curve is that they impart global control to the curve. Which means if the relative position of the curve changes the whole curve shape get changes. This makes it less convenient to use.
On changing any one of the control points relative position the whole curve shape get changes:
c) One more problem with Bezier is that its blending function never gets zero for any parameter irrespective of the degree of the curve.
sudo apt-get install libsdl2-dev
To build use
gcc fileName.c -lSDL2 -lm
C
// C program to implement// Cubic Bezier Curve /* install SDL library for running thing code*//* install by using this commamnd line : sudo apt-get install libsdl2-dev *//* run this code using command : gcc fileName.c -lSDL2 -lm*/ #include<stdio.h>#include<stdlib.h>#include<math.h>#include<SDL2/SDL.h> SDL_Window* window = NULL;SDL_Renderer* renderer = NULL;int mousePosX , mousePosY ;int xnew , ynew ; /*Function to draw all other 7 pixels present at symmetric position*/void drawCircle(int xc, int yc, int x, int y){ SDL_RenderDrawPoint(renderer,xc+x,yc+y) ; SDL_RenderDrawPoint(renderer,xc-x,yc+y); SDL_RenderDrawPoint(renderer,xc+x,yc-y); SDL_RenderDrawPoint(renderer,xc-x,yc-y); SDL_RenderDrawPoint(renderer,xc+y,yc+x); SDL_RenderDrawPoint(renderer,xc-y,yc+x); SDL_RenderDrawPoint(renderer,xc+y,yc-x); SDL_RenderDrawPoint(renderer,xc-y,yc-x);} /*Function for circle-generation using Bresenham's algorithm */void circleBres(int xc, int yc, int r){ int x = 0, y = r; int d = 3 - 2 * r; while (y >= x) { /*for each pixel we will draw all eight pixels */ drawCircle(xc, yc, x, y); x++; /*check for decision parameter and correspondingly update d, x, y*/ if (d > 0) { y--; d = d + 4 * (x - y) + 10; } else d = d + 4 * x + 6; drawCircle(xc, yc, x, y); }} /* Function that take input as Control Point x_coordinates andControl Point y_coordinates and draw bezier curve */void bezierCurve(int x[] , int y[]){ double xu = 0.0 , yu = 0.0 , u = 0.0 ; int i = 0 ; for(u = 0.0 ; u <= 1.0 ; u += 0.0001) { xu = pow(1-u,3)*x[0]+3*u*pow(1-u,2)*x[1]+3*pow(u,2)*(1-u)*x[2] +pow(u,3)*x[3]; yu = pow(1-u,3)*y[0]+3*u*pow(1-u,2)*y[1]+3*pow(u,2)*(1-u)*y[2] +pow(u,3)*y[3]; SDL_RenderDrawPoint(renderer , (int)xu , (int)yu) ; }}int main(int argc, char* argv[]){ /*initialize sdl*/ if (SDL_Init(SDL_INIT_EVERYTHING) == 0) { /* This function is used to create a window and default renderer. int SDL_CreateWindowAndRenderer(int width ,int height ,Uint32 window_flags ,SDL_Window** window ,SDL_Renderer** renderer) return 0 on success and -1 on error */ if(SDL_CreateWindowAndRenderer(640, 480, 0, &window, &renderer) == 0) { SDL_bool done = SDL_FALSE; int i = 0 ; int x[4] , y[4] , flagDrawn = 0 ; while (!done) { SDL_Event event; /*set background color to black*/ SDL_SetRenderDrawColor(renderer, 0, 0, 0, SDL_ALPHA_OPAQUE); SDL_RenderClear(renderer); /*set draw color to white*/ SDL_SetRenderDrawColor(renderer, 255, 255, 255, SDL_ALPHA_OPAQUE); /* We are drawing cubic bezier curve which has four control points */ if(i==4) { bezierCurve(x , y) ; flagDrawn = 1 ; } /*grey color circle to encircle control Point P0*/ SDL_SetRenderDrawColor(renderer, 128, 128, 128, SDL_ALPHA_OPAQUE); circleBres(x[0] , y[0] , 8) ; /*Red Line between control Point P0 & P1*/ SDL_SetRenderDrawColor(renderer, 255, 0, 0, SDL_ALPHA_OPAQUE); SDL_RenderDrawLine(renderer , x[0] , y[0] , x[1] , y[1]) ; /*grey color circle to encircle control Point P1*/ SDL_SetRenderDrawColor(renderer, 128, 128, 128, SDL_ALPHA_OPAQUE); circleBres(x[1] , y[1] , 8) ; /*Red Line between control Point P1 & P2*/ SDL_SetRenderDrawColor(renderer, 255, 0, 0, SDL_ALPHA_OPAQUE); SDL_RenderDrawLine(renderer , x[1] , y[1] , x[2] , y[2]) ; /*grey color circle to encircle control Point P2*/ SDL_SetRenderDrawColor(renderer, 128, 128, 128, SDL_ALPHA_OPAQUE); circleBres(x[2] , y[2] , 8) ; /*Red Line between control Point P2 & P3*/ SDL_SetRenderDrawColor(renderer, 255, 0, 0, SDL_ALPHA_OPAQUE); SDL_RenderDrawLine(renderer , x[2] , y[2] , x[3] , y[3]) ; /*grey color circle to encircle control Point P3*/ SDL_SetRenderDrawColor(renderer, 128, 128, 128, SDL_ALPHA_OPAQUE); circleBres(x[3] , y[3] , 8) ; /*We are Polling SDL events*/ if (SDL_PollEvent(&event)) { /* if window cross button clicked then quit from window */ if (event.type == SDL_QUIT) { done = SDL_TRUE; } /*Mouse Button is Down */ if(event.type == SDL_MOUSEBUTTONDOWN) { /*If left mouse button down then store that point as control point*/ if(event.button.button == SDL_BUTTON_LEFT) { /*store only four points because of cubic bezier curve*/ if(i < 4) { printf("Control Point(P%d):(%d,%d)\n" ,i,mousePosX,mousePosY) ; /*Storing Mouse x and y positions in our x and y coordinate array */ x[i] = mousePosX ; y[i] = mousePosY ; i++ ; } } } /*Mouse is in motion*/ if(event.type == SDL_MOUSEMOTION) { /*get x and y positions from motion of mouse*/ xnew = event.motion.x ; ynew = event.motion.y ; int j ; /* change coordinates of control point after bezier curve has been drawn */ if(flagDrawn == 1) { for(j = 0 ; j < i ; j++) { /*Check mouse position if in b/w circle then change position of that control point to mouse new position which are coming from mouse motion*/ if((float)sqrt(abs(xnew-x[j]) * abs(xnew-x[j]) + abs(ynew-y[j]) * abs(ynew-y[j])) < 8.0) { /*change coordinate of jth control point*/ x[j] = xnew ; y[j] = ynew ; printf("Changed Control Point(P%d):(%d,%d)\n" ,j,xnew,ynew) ; } } } /*updating mouse positions to positions coming from motion*/ mousePosX = xnew ; mousePosY = ynew ; } } /*show the window*/ SDL_RenderPresent(renderer); } } /*Destroy the renderer and window*/ if (renderer) { SDL_DestroyRenderer(renderer); } if (window) { SDL_DestroyWindow(window); } } /*clean up SDL*/ SDL_Quit(); return 0;}
Output
Move mouse when mouse position is b/w circle then only curve shape will be changed
References: https://en.wikipedia.org/wiki/B%C3%A9zier_curve https://www.tutorialspoint.com/computer_graphics/computer_graphics_curves.htm http://www.math.ucla.edu/~baker/149.1.02w/handouts/bb_bezier.pdfThis article is contributed by Palkansh Khandelwal
ManasChhabra2
madhav_mohan
clintra
computer-graphics
Mathematical
Mathematical
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Merge two sorted arrays
Modulo Operator (%) in C/C++ with Examples
Program to find GCD or HCF of two numbers
Prime Numbers
Program to find sum of elements in a given array
Program for Decimal to Binary Conversion
Program for factorial of a number
Sieve of Eratosthenes
Operators in C / C++
Euclidean algorithms (Basic and Extended) | [
{
"code": null,
"e": 24506,
"s": 24478,
"text": "\n04 Jan, 2022"
},
{
"code": null,
"e": 25892,
"s": 24506,
"text": "What is a bezier curve? So a Bezier curve is a mathematically defined curve used in two-dimensional graphic applications like adobe Illustrator, Inkscape etc. The curve is defined by four points: the initial position and the terminating position i.e P0 and P3 respectively (which are called “anchors”) and two separate middle points i.e P1 and P2(which are called “handles”) in our example. Bezier curves are frequently used in computer graphics, animation, modelling etc.How do we Represent Bezier Curves Mathematically? Bezier curves can be generated under the control of other points. Approximate tangents by using control points are used to generate curve. The Bezier curve can be represented mathematically as – Where is the set of points and represents the Bernstein polynomials i.e. Blending Function which are given by – Where n is the polynomial order, i is the index, and u/t is the variable which has from 0 to 1.Let us define our cubic bezier curve mathematically. So a bezier curve id defined by a set of control points to where n is called its order(n = 1 for linear, n = 2 for quadratic, etc.). The first and last control points are always the endpoints of the curve; however, the intermediate control points (if any) generally do not lie on the curve. For cubic bezier curve order(n) of polynomial is 3 , index(i) vary from i = 0 to i = n i.e. 3 and u will vary from . "
},
{
"code": null,
"e": 25936,
"s": 25892,
"text": "Cubic Bezier Curve function is defined as :"
},
{
"code": null,
"e": 25992,
"s": 25938,
"text": "Cubic Bezier Curve blending function are defined as :"
},
{
"code": null,
"e": 26083,
"s": 25992,
"text": "So and Now,So we will calculate curve x and y pixel by incrementing value of u by 0.0001. "
},
{
"code": null,
"e": 26121,
"s": 26083,
"text": "Construction of a cubic Bézier curve"
},
{
"code": null,
"e": 26151,
"s": 26123,
"text": "Properties of bezier curves"
},
{
"code": null,
"e": 26975,
"s": 26151,
"text": "1. They always pass through the first and last control points.2. They are contained in the convex hull of their defining control points.3. The degree of the polynomial defining the curve segment is one less than the number of defining polygon point. Therefore, for 4 control points, the degree of the polynomial is 3, i.e. cubic polynomial.4. A Bezier curve generally follows the shape of the defining polygon5. The direction of the tangent vector at the endpoints is the same as that of the vector determined by the first and last segments.6. Bezier curves exhibit global control means moving a control point alters the shape of the whole curveNOTE: The following implementation uses the SDL library to draw pixels on the screen. If you are on Debian system like ubuntu just runs following command to install SDL library. "
},
{
"code": null,
"e": 27138,
"s": 26975,
"text": "Ex: We are given with four control points B0[1,0], B1[2,2], B2[6,3], B3[8,2], so determine the five points that lie on the curve also draw the curve on the graph."
},
{
"code": null,
"e": 27266,
"s": 27138,
"text": "Ans: Given curve has four control points hence it is a cubic bezier curve, So, the parametric equation of cubic bezier curve is"
},
{
"code": null,
"e": 27339,
"s": 27266,
"text": "now, substitute the control points into the above equation so we’ll get,"
},
{
"code": null,
"e": 27407,
"s": 27339,
"text": "Let’s assume five different values of t are {0, 0.2, 0.5, 0.7, 1}. "
},
{
"code": null,
"e": 27443,
"s": 27407,
"text": "So, for t=0 the coordinate will be,"
},
{
"code": null,
"e": 27481,
"s": 27443,
"text": "So, for t=0.2 the coordinate will be,"
},
{
"code": null,
"e": 27519,
"s": 27481,
"text": "So, for t=0.5 the coordinate will be,"
},
{
"code": null,
"e": 27557,
"s": 27519,
"text": "So, for t=0.7 the coordinate will be,"
},
{
"code": null,
"e": 27595,
"s": 27557,
"text": "So, for t=1.0 the coordinate will be,"
},
{
"code": null,
"e": 27601,
"s": 27595,
"text": "Fig.1"
},
{
"code": null,
"e": 27628,
"s": 27601,
"text": "Drawbacks of Bezier curve:"
},
{
"code": null,
"e": 27909,
"s": 27628,
"text": "a) The degree of Bezier curve depends upon the number of control points associated with the corresponding curve, as the number of control points increases the polynomial degree of the curve equation also increases that make the curve equation very complex and harder to deal with."
},
{
"code": null,
"e": 27955,
"s": 27909,
"text": " Degree of curve = no. of control points - 1"
},
{
"code": null,
"e": 28187,
"s": 27955,
"text": "b) One major disadvantage of using the Bezier curve is that they impart global control to the curve. Which means if the relative position of the curve changes the whole curve shape get changes. This makes it less convenient to use."
},
{
"code": null,
"e": 28282,
"s": 28187,
"text": "On changing any one of the control points relative position the whole curve shape get changes:"
},
{
"code": null,
"e": 28419,
"s": 28282,
"text": "c) One more problem with Bezier is that its blending function never gets zero for any parameter irrespective of the degree of the curve."
},
{
"code": null,
"e": 28452,
"s": 28419,
"text": "sudo apt-get install libsdl2-dev"
},
{
"code": null,
"e": 28467,
"s": 28452,
"text": "To build use "
},
{
"code": null,
"e": 28493,
"s": 28467,
"text": "gcc fileName.c -lSDL2 -lm"
},
{
"code": null,
"e": 28497,
"s": 28495,
"text": "C"
},
{
"code": "// C program to implement// Cubic Bezier Curve /* install SDL library for running thing code*//* install by using this commamnd line : sudo apt-get install libsdl2-dev *//* run this code using command : gcc fileName.c -lSDL2 -lm*/ #include<stdio.h>#include<stdlib.h>#include<math.h>#include<SDL2/SDL.h> SDL_Window* window = NULL;SDL_Renderer* renderer = NULL;int mousePosX , mousePosY ;int xnew , ynew ; /*Function to draw all other 7 pixels present at symmetric position*/void drawCircle(int xc, int yc, int x, int y){ SDL_RenderDrawPoint(renderer,xc+x,yc+y) ; SDL_RenderDrawPoint(renderer,xc-x,yc+y); SDL_RenderDrawPoint(renderer,xc+x,yc-y); SDL_RenderDrawPoint(renderer,xc-x,yc-y); SDL_RenderDrawPoint(renderer,xc+y,yc+x); SDL_RenderDrawPoint(renderer,xc-y,yc+x); SDL_RenderDrawPoint(renderer,xc+y,yc-x); SDL_RenderDrawPoint(renderer,xc-y,yc-x);} /*Function for circle-generation using Bresenham's algorithm */void circleBres(int xc, int yc, int r){ int x = 0, y = r; int d = 3 - 2 * r; while (y >= x) { /*for each pixel we will draw all eight pixels */ drawCircle(xc, yc, x, y); x++; /*check for decision parameter and correspondingly update d, x, y*/ if (d > 0) { y--; d = d + 4 * (x - y) + 10; } else d = d + 4 * x + 6; drawCircle(xc, yc, x, y); }} /* Function that take input as Control Point x_coordinates andControl Point y_coordinates and draw bezier curve */void bezierCurve(int x[] , int y[]){ double xu = 0.0 , yu = 0.0 , u = 0.0 ; int i = 0 ; for(u = 0.0 ; u <= 1.0 ; u += 0.0001) { xu = pow(1-u,3)*x[0]+3*u*pow(1-u,2)*x[1]+3*pow(u,2)*(1-u)*x[2] +pow(u,3)*x[3]; yu = pow(1-u,3)*y[0]+3*u*pow(1-u,2)*y[1]+3*pow(u,2)*(1-u)*y[2] +pow(u,3)*y[3]; SDL_RenderDrawPoint(renderer , (int)xu , (int)yu) ; }}int main(int argc, char* argv[]){ /*initialize sdl*/ if (SDL_Init(SDL_INIT_EVERYTHING) == 0) { /* This function is used to create a window and default renderer. int SDL_CreateWindowAndRenderer(int width ,int height ,Uint32 window_flags ,SDL_Window** window ,SDL_Renderer** renderer) return 0 on success and -1 on error */ if(SDL_CreateWindowAndRenderer(640, 480, 0, &window, &renderer) == 0) { SDL_bool done = SDL_FALSE; int i = 0 ; int x[4] , y[4] , flagDrawn = 0 ; while (!done) { SDL_Event event; /*set background color to black*/ SDL_SetRenderDrawColor(renderer, 0, 0, 0, SDL_ALPHA_OPAQUE); SDL_RenderClear(renderer); /*set draw color to white*/ SDL_SetRenderDrawColor(renderer, 255, 255, 255, SDL_ALPHA_OPAQUE); /* We are drawing cubic bezier curve which has four control points */ if(i==4) { bezierCurve(x , y) ; flagDrawn = 1 ; } /*grey color circle to encircle control Point P0*/ SDL_SetRenderDrawColor(renderer, 128, 128, 128, SDL_ALPHA_OPAQUE); circleBres(x[0] , y[0] , 8) ; /*Red Line between control Point P0 & P1*/ SDL_SetRenderDrawColor(renderer, 255, 0, 0, SDL_ALPHA_OPAQUE); SDL_RenderDrawLine(renderer , x[0] , y[0] , x[1] , y[1]) ; /*grey color circle to encircle control Point P1*/ SDL_SetRenderDrawColor(renderer, 128, 128, 128, SDL_ALPHA_OPAQUE); circleBres(x[1] , y[1] , 8) ; /*Red Line between control Point P1 & P2*/ SDL_SetRenderDrawColor(renderer, 255, 0, 0, SDL_ALPHA_OPAQUE); SDL_RenderDrawLine(renderer , x[1] , y[1] , x[2] , y[2]) ; /*grey color circle to encircle control Point P2*/ SDL_SetRenderDrawColor(renderer, 128, 128, 128, SDL_ALPHA_OPAQUE); circleBres(x[2] , y[2] , 8) ; /*Red Line between control Point P2 & P3*/ SDL_SetRenderDrawColor(renderer, 255, 0, 0, SDL_ALPHA_OPAQUE); SDL_RenderDrawLine(renderer , x[2] , y[2] , x[3] , y[3]) ; /*grey color circle to encircle control Point P3*/ SDL_SetRenderDrawColor(renderer, 128, 128, 128, SDL_ALPHA_OPAQUE); circleBres(x[3] , y[3] , 8) ; /*We are Polling SDL events*/ if (SDL_PollEvent(&event)) { /* if window cross button clicked then quit from window */ if (event.type == SDL_QUIT) { done = SDL_TRUE; } /*Mouse Button is Down */ if(event.type == SDL_MOUSEBUTTONDOWN) { /*If left mouse button down then store that point as control point*/ if(event.button.button == SDL_BUTTON_LEFT) { /*store only four points because of cubic bezier curve*/ if(i < 4) { printf(\"Control Point(P%d):(%d,%d)\\n\" ,i,mousePosX,mousePosY) ; /*Storing Mouse x and y positions in our x and y coordinate array */ x[i] = mousePosX ; y[i] = mousePosY ; i++ ; } } } /*Mouse is in motion*/ if(event.type == SDL_MOUSEMOTION) { /*get x and y positions from motion of mouse*/ xnew = event.motion.x ; ynew = event.motion.y ; int j ; /* change coordinates of control point after bezier curve has been drawn */ if(flagDrawn == 1) { for(j = 0 ; j < i ; j++) { /*Check mouse position if in b/w circle then change position of that control point to mouse new position which are coming from mouse motion*/ if((float)sqrt(abs(xnew-x[j]) * abs(xnew-x[j]) + abs(ynew-y[j]) * abs(ynew-y[j])) < 8.0) { /*change coordinate of jth control point*/ x[j] = xnew ; y[j] = ynew ; printf(\"Changed Control Point(P%d):(%d,%d)\\n\" ,j,xnew,ynew) ; } } } /*updating mouse positions to positions coming from motion*/ mousePosX = xnew ; mousePosY = ynew ; } } /*show the window*/ SDL_RenderPresent(renderer); } } /*Destroy the renderer and window*/ if (renderer) { SDL_DestroyRenderer(renderer); } if (window) { SDL_DestroyWindow(window); } } /*clean up SDL*/ SDL_Quit(); return 0;}",
"e": 36421,
"s": 28497,
"text": null
},
{
"code": null,
"e": 36428,
"s": 36421,
"text": "Output"
},
{
"code": null,
"e": 36513,
"s": 36428,
"text": "Move mouse when mouse position is b/w circle then only curve shape will be changed "
},
{
"code": null,
"e": 36771,
"s": 36517,
"text": "References: https://en.wikipedia.org/wiki/B%C3%A9zier_curve https://www.tutorialspoint.com/computer_graphics/computer_graphics_curves.htm http://www.math.ucla.edu/~baker/149.1.02w/handouts/bb_bezier.pdfThis article is contributed by Palkansh Khandelwal "
},
{
"code": null,
"e": 36785,
"s": 36771,
"text": "ManasChhabra2"
},
{
"code": null,
"e": 36798,
"s": 36785,
"text": "madhav_mohan"
},
{
"code": null,
"e": 36806,
"s": 36798,
"text": "clintra"
},
{
"code": null,
"e": 36824,
"s": 36806,
"text": "computer-graphics"
},
{
"code": null,
"e": 36837,
"s": 36824,
"text": "Mathematical"
},
{
"code": null,
"e": 36850,
"s": 36837,
"text": "Mathematical"
},
{
"code": null,
"e": 36948,
"s": 36850,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 36972,
"s": 36948,
"text": "Merge two sorted arrays"
},
{
"code": null,
"e": 37015,
"s": 36972,
"text": "Modulo Operator (%) in C/C++ with Examples"
},
{
"code": null,
"e": 37057,
"s": 37015,
"text": "Program to find GCD or HCF of two numbers"
},
{
"code": null,
"e": 37071,
"s": 37057,
"text": "Prime Numbers"
},
{
"code": null,
"e": 37120,
"s": 37071,
"text": "Program to find sum of elements in a given array"
},
{
"code": null,
"e": 37161,
"s": 37120,
"text": "Program for Decimal to Binary Conversion"
},
{
"code": null,
"e": 37195,
"s": 37161,
"text": "Program for factorial of a number"
},
{
"code": null,
"e": 37217,
"s": 37195,
"text": "Sieve of Eratosthenes"
},
{
"code": null,
"e": 37238,
"s": 37217,
"text": "Operators in C / C++"
}
] |
How to import a single function from a Python module? | You can use the "from module import function" statement to import a specific function from a Python module. For example, if you want to import the sin function from the math library without importing any other function, you can do it as follows:
>>> from math import sin
>>> sin(0)
0.0
Note that you don't have to prefix sin with "math." as only sin has been imported and not math. Also you can alias imported functions. For example,
>>> from math import cos as cosine
>>> cosine(0)
1.0 | [
{
"code": null,
"e": 1308,
"s": 1062,
"text": "You can use the \"from module import function\" statement to import a specific function from a Python module. For example, if you want to import the sin function from the math library without importing any other function, you can do it as follows:"
},
{
"code": null,
"e": 1348,
"s": 1308,
"text": ">>> from math import sin\n>>> sin(0)\n0.0"
},
{
"code": null,
"e": 1496,
"s": 1348,
"text": "Note that you don't have to prefix sin with \"math.\" as only sin has been imported and not math. Also you can alias imported functions. For example,"
},
{
"code": null,
"e": 1549,
"s": 1496,
"text": ">>> from math import cos as cosine\n>>> cosine(0)\n1.0"
}
] |
Maximum value of difference of a pair of elements and their Index | Practice | GeeksforGeeks | Given an array arr[] of N positive integers. Find maximum value of |arr[i] – arr[j]| + |i – j|, (0 <= i, j <= N – 1)
Example 1:
Input:
N = 4
arr[] = {1, 2, 3, 1}
Output:
4
Explanation:
Choosing i=0 and j=2, will result in
|1-3|+|0-2| = 4, which is the maximum
possible value.
Example 2:
Input:
N = 3
A[] = {1, 1, 1}
Output:
2
Explanation:
Choosing i=0 and j=2, will result in
|1-1|+|0-2| = 2, which is the maximum
possible value.
Your Task:
You don't need to read input or print anything. Your task is to complete the function maxValue() which takes an Integer N and an array arr of size N as input and returns the maximum possoble value of |arr[i] – arr[j]| + |i – j|.
Expected Time Complexity: O(N)
Expected Auxiliary Space: O(N)
Constraints:
1 <= N <= 105
0 <= arr[i] <= 105
+1
diyer1711001 month ago
Here is a python code for reference -
def maxValue(self, arr, N):
a=[]
b=[]
for i in range(N):
a.append(arr[i]+i)
b.append(-arr[i]+i)
mx=max(a)
mn=min(a)
mx1=max(b)
mn1=min(b)
return max(mx-mn,mx1-mn1)
+3
msf_venom0031 month ago
self note
property of mod will be used
after opening mode we have two cases
|x| = x , x >0
|x| = -x , x <0
as two mod values are used so it will be four cases
when the first value is > 0 , and second is > 0
|A[i]-A[j]| = A[i]-A[j]
and
|i-j| = i- j
which can be rewritten as (A[i]+i) - (A[j]+j)
similarly for second case (-A[i]+i)- (-A[j]+j) (when first is <0 and and other is greater than 0. other two cases will match with it after rearranging , so in conclusion we need to
maximize the A[i]+i and -A[i]+i and also find it minimum value so differnce will be largest at end we will have two max and 2 min and ans will be
max( max1-min2,max2-min2)
int maxValue(int arr[], int N) {
int max1 = INT_MIN,min1=INT_MAX;
int max2 = INT_MIN,min2=INT_MAX;
for(int i=0;i<N;++i){
max1 = max(arr[i]+i,max1);
min1 = min(arr[i]+i,min1);
max2 = max(-arr[i]+i,max2);
min2 = min(-arr[i]+i,min2);
}
return max((max1-min1),(max2-min2));
}
+1
akshatshubhra2 months ago
C++ | 0ms| Easy Approach|
O(N)
O(N)
‘’'
class Solution { public: int maxValue(int arr[], int N) { // code here int brr[N]; for(int i=0;i<N;i++){ brr[i]=arr[i]-i; arr[i]+=i; } int a=*max_element(arr,arr+N); int b=*min_element(arr,arr+N); int c=*max_element(brr,brr+N); int d=*min_element(brr,brr+N); return max(a-b,c-d); }};
‘’'
+7
badgujarsachin835 months ago
int maxValue(int arr[], int N) {
// code here
int min1=INT_MAX, min2=INT_MAX,max1=INT_MIN,max2=INT_MIN;
for(int i=0;i<N;i++){
min1=min(min1,i+arr[i]);
max1=max(max1,i+arr[i]);
min2=min(min2,i-arr[i]);
max2=max(max2,i-arr[i]);
}
return max(max1-min1,max2-min2);
}
+1
punitkumarojha6 months ago
Simple O(n) time approach with O(1) space
class Solution {
public:
int maxValue(int a[], int n) {
int mn=a[0],mx=a[0];
int ans=0;
for(int i=1;i<n;i++){
ans=max({ans,i+a[i]-mn,i-a[i]+mx});
mn=min(mn,a[i]+i);
mx=max(mx,a[i]-i);
}
return ans;
}
};
-3
abhishekpanwar6976 months ago
int maxValue(int a[], int n) { int p[n],q[n]; for(int i=0;i<n;i++) { p[i]=a[i]+i; q[i]=a[i]-i; } sort(p,p+n); sort(q,q+n); int x=p[n-1]-p[0]; int y=q[n-1]-q[0]; return max(x,y); }
0
rakeshthala6 months ago
NO extra space reqd.
class Solution { public: int maxValue(int arr[], int N) { // code here int min1=INT_MAX,max1=INT_MIN,min2=INT_MAX,max2=INT_MIN; for(int i=0; i<N;i++) { min1 = min(min1,i+arr[i]); max1 = max(max1,i+arr[i]); min2 = min(min2,i-arr[i]); max2 = max(max2,i-arr[i]); } return max(max1-min1,max2-min2); }};
0
Satyam8 months ago
Satyam
JAVA SOLUTION//class Solution { static int maxValue(int[] arr, int N) { int min1=Integer.MAX_VALUE; int max1=Integer.MIN_VALUE; int min2=Integer.MAX_VALUE; int max2=Integer.MIN_VALUE;
for(int i=0;i<n;i++){ if(arr[i]+i<min1)="" min1="arr[i]+i;" if(arr[i]+i="">max1) max1=arr[i]+i; if(arr[i]-i<min2) min2="arr[i]-i;" if(arr[i]-i="">max2) max2=arr[i]-i; } return Math.max(Math.abs(max1-min1),Math.abs(max2-min2)); }};
-2
Gourav Modi10 months ago
Gourav Modi
https://ide.geeksforgeeks.o...
0
Gourav Modi
This comment was deleted.
We strongly recommend solving this problem on your own before viewing its editorial. Do you still
want to view the editorial?
Login to access your submissions.
Problem
Contest
Reset the IDE using the second button on the top right corner.
Avoid using static/global variables in your code as your code is tested against multiple test cases and these tend to retain their previous values.
Passing the Sample/Custom Test cases does not guarantee the correctness of code. On submission, your code is tested against multiple test cases consisting of all possible corner cases and stress constraints.
You can access the hints to get an idea about what is expected of you as well as the final solution code.
You can view the solutions submitted by other users from the submission tab. | [
{
"code": null,
"e": 355,
"s": 238,
"text": "Given an array arr[] of N positive integers. Find maximum value of |arr[i] – arr[j]| + |i – j|, (0 <= i, j <= N – 1)"
},
{
"code": null,
"e": 368,
"s": 357,
"text": "Example 1:"
},
{
"code": null,
"e": 518,
"s": 368,
"text": "Input:\nN = 4 \narr[] = {1, 2, 3, 1}\nOutput:\n4\nExplanation:\nChoosing i=0 and j=2, will result in\n|1-3|+|0-2| = 4, which is the maximum\npossible value.\n"
},
{
"code": null,
"e": 529,
"s": 518,
"text": "Example 2:"
},
{
"code": null,
"e": 673,
"s": 529,
"text": "Input:\nN = 3 \nA[] = {1, 1, 1}\nOutput:\n2\nExplanation:\nChoosing i=0 and j=2, will result in\n|1-1|+|0-2| = 2, which is the maximum\npossible value."
},
{
"code": null,
"e": 915,
"s": 675,
"text": "Your Task:\nYou don't need to read input or print anything. Your task is to complete the function maxValue() which takes an Integer N and an array arr of size N as input and returns the maximum possoble value of |arr[i] – arr[j]| + |i – j|."
},
{
"code": null,
"e": 979,
"s": 917,
"text": "Expected Time Complexity: O(N)\nExpected Auxiliary Space: O(N)"
},
{
"code": null,
"e": 1027,
"s": 981,
"text": "Constraints:\n1 <= N <= 105\n0 <= arr[i] <= 105"
},
{
"code": null,
"e": 1030,
"s": 1027,
"text": "+1"
},
{
"code": null,
"e": 1053,
"s": 1030,
"text": "diyer1711001 month ago"
},
{
"code": null,
"e": 1093,
"s": 1055,
"text": "Here is a python code for reference -"
},
{
"code": null,
"e": 1350,
"s": 1093,
"text": " def maxValue(self, arr, N):\n a=[]\n b=[]\n for i in range(N):\n a.append(arr[i]+i)\n b.append(-arr[i]+i)\n\n mx=max(a)\n mn=min(a)\n mx1=max(b)\n mn1=min(b)\n return max(mx-mn,mx1-mn1)"
},
{
"code": null,
"e": 1353,
"s": 1350,
"text": "+3"
},
{
"code": null,
"e": 1377,
"s": 1353,
"text": "msf_venom0031 month ago"
},
{
"code": null,
"e": 1387,
"s": 1377,
"text": "self note"
},
{
"code": null,
"e": 1416,
"s": 1387,
"text": "property of mod will be used"
},
{
"code": null,
"e": 1453,
"s": 1416,
"text": "after opening mode we have two cases"
},
{
"code": null,
"e": 1468,
"s": 1453,
"text": "|x| = x , x >0"
},
{
"code": null,
"e": 1484,
"s": 1468,
"text": "|x| = -x , x <0"
},
{
"code": null,
"e": 1539,
"s": 1486,
"text": "as two mod values are used so it will be four cases "
},
{
"code": null,
"e": 1589,
"s": 1541,
"text": "when the first value is > 0 , and second is > 0"
},
{
"code": null,
"e": 1615,
"s": 1591,
"text": "|A[i]-A[j]| = A[i]-A[j]"
},
{
"code": null,
"e": 1619,
"s": 1615,
"text": "and"
},
{
"code": null,
"e": 1633,
"s": 1619,
"text": "|i-j| = i- j "
},
{
"code": null,
"e": 1681,
"s": 1635,
"text": "which can be rewritten as (A[i]+i) - (A[j]+j)"
},
{
"code": null,
"e": 1864,
"s": 1681,
"text": "similarly for second case (-A[i]+i)- (-A[j]+j) (when first is <0 and and other is greater than 0. other two cases will match with it after rearranging , so in conclusion we need to "
},
{
"code": null,
"e": 2011,
"s": 1864,
"text": "maximize the A[i]+i and -A[i]+i and also find it minimum value so differnce will be largest at end we will have two max and 2 min and ans will be "
},
{
"code": null,
"e": 2039,
"s": 2013,
"text": "max( max1-min2,max2-min2)"
},
{
"code": null,
"e": 2425,
"s": 2039,
"text": "int maxValue(int arr[], int N) {\n int max1 = INT_MIN,min1=INT_MAX;\n int max2 = INT_MIN,min2=INT_MAX;\n \n for(int i=0;i<N;++i){\n max1 = max(arr[i]+i,max1);\n min1 = min(arr[i]+i,min1);\n max2 = max(-arr[i]+i,max2);\n min2 = min(-arr[i]+i,min2);\n \n }\n return max((max1-min1),(max2-min2));\n }"
},
{
"code": null,
"e": 2434,
"s": 2431,
"text": "+1"
},
{
"code": null,
"e": 2460,
"s": 2434,
"text": "akshatshubhra2 months ago"
},
{
"code": null,
"e": 2486,
"s": 2460,
"text": "C++ | 0ms| Easy Approach|"
},
{
"code": null,
"e": 2491,
"s": 2486,
"text": "O(N)"
},
{
"code": null,
"e": 2496,
"s": 2491,
"text": "O(N)"
},
{
"code": null,
"e": 2500,
"s": 2496,
"text": "‘’'"
},
{
"code": null,
"e": 2862,
"s": 2500,
"text": "class Solution { public: int maxValue(int arr[], int N) { // code here int brr[N]; for(int i=0;i<N;i++){ brr[i]=arr[i]-i; arr[i]+=i; } int a=*max_element(arr,arr+N); int b=*min_element(arr,arr+N); int c=*max_element(brr,brr+N); int d=*min_element(brr,brr+N); return max(a-b,c-d); }};"
},
{
"code": null,
"e": 2866,
"s": 2862,
"text": "‘’'"
},
{
"code": null,
"e": 2869,
"s": 2866,
"text": "+7"
},
{
"code": null,
"e": 2898,
"s": 2869,
"text": "badgujarsachin835 months ago"
},
{
"code": null,
"e": 3237,
"s": 2898,
"text": "int maxValue(int arr[], int N) {\n // code here\n int min1=INT_MAX, min2=INT_MAX,max1=INT_MIN,max2=INT_MIN;\n for(int i=0;i<N;i++){\n min1=min(min1,i+arr[i]);\n max1=max(max1,i+arr[i]);\n min2=min(min2,i-arr[i]);\n max2=max(max2,i-arr[i]);\n }\n return max(max1-min1,max2-min2);\n }"
},
{
"code": null,
"e": 3240,
"s": 3237,
"text": "+1"
},
{
"code": null,
"e": 3267,
"s": 3240,
"text": "punitkumarojha6 months ago"
},
{
"code": null,
"e": 3309,
"s": 3267,
"text": "Simple O(n) time approach with O(1) space"
},
{
"code": null,
"e": 3600,
"s": 3311,
"text": "class Solution {\n public:\n int maxValue(int a[], int n) {\n int mn=a[0],mx=a[0];\n int ans=0;\n for(int i=1;i<n;i++){\n ans=max({ans,i+a[i]-mn,i-a[i]+mx});\n mn=min(mn,a[i]+i);\n mx=max(mx,a[i]-i);\n }\n return ans;\n }\n};"
},
{
"code": null,
"e": 3603,
"s": 3600,
"text": "-3"
},
{
"code": null,
"e": 3633,
"s": 3603,
"text": "abhishekpanwar6976 months ago"
},
{
"code": null,
"e": 3856,
"s": 3633,
"text": "int maxValue(int a[], int n) { int p[n],q[n]; for(int i=0;i<n;i++) { p[i]=a[i]+i; q[i]=a[i]-i; } sort(p,p+n); sort(q,q+n); int x=p[n-1]-p[0]; int y=q[n-1]-q[0]; return max(x,y); }"
},
{
"code": null,
"e": 3858,
"s": 3856,
"text": "0"
},
{
"code": null,
"e": 3882,
"s": 3858,
"text": "rakeshthala6 months ago"
},
{
"code": null,
"e": 3903,
"s": 3882,
"text": "NO extra space reqd."
},
{
"code": null,
"e": 4282,
"s": 3903,
"text": "class Solution { public: int maxValue(int arr[], int N) { // code here int min1=INT_MAX,max1=INT_MIN,min2=INT_MAX,max2=INT_MIN; for(int i=0; i<N;i++) { min1 = min(min1,i+arr[i]); max1 = max(max1,i+arr[i]); min2 = min(min2,i-arr[i]); max2 = max(max2,i-arr[i]); } return max(max1-min1,max2-min2); }};"
},
{
"code": null,
"e": 4284,
"s": 4282,
"text": "0"
},
{
"code": null,
"e": 4303,
"s": 4284,
"text": "Satyam8 months ago"
},
{
"code": null,
"e": 4310,
"s": 4303,
"text": "Satyam"
},
{
"code": null,
"e": 4517,
"s": 4310,
"text": "JAVA SOLUTION//class Solution { static int maxValue(int[] arr, int N) { int min1=Integer.MAX_VALUE; int max1=Integer.MIN_VALUE; int min2=Integer.MAX_VALUE; int max2=Integer.MIN_VALUE;"
},
{
"code": null,
"e": 4794,
"s": 4517,
"text": " for(int i=0;i<n;i++){ if(arr[i]+i<min1)=\"\" min1=\"arr[i]+i;\" if(arr[i]+i=\"\">max1) max1=arr[i]+i; if(arr[i]-i<min2) min2=\"arr[i]-i;\" if(arr[i]-i=\"\">max2) max2=arr[i]-i; } return Math.max(Math.abs(max1-min1),Math.abs(max2-min2)); }};"
},
{
"code": null,
"e": 4797,
"s": 4794,
"text": "-2"
},
{
"code": null,
"e": 4822,
"s": 4797,
"text": "Gourav Modi10 months ago"
},
{
"code": null,
"e": 4834,
"s": 4822,
"text": "Gourav Modi"
},
{
"code": null,
"e": 4865,
"s": 4834,
"text": "https://ide.geeksforgeeks.o..."
},
{
"code": null,
"e": 4867,
"s": 4865,
"text": "0"
},
{
"code": null,
"e": 4879,
"s": 4867,
"text": "Gourav Modi"
},
{
"code": null,
"e": 4905,
"s": 4879,
"text": "This comment was deleted."
},
{
"code": null,
"e": 5051,
"s": 4905,
"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": 5087,
"s": 5051,
"text": " Login to access your submissions. "
},
{
"code": null,
"e": 5097,
"s": 5087,
"text": "\nProblem\n"
},
{
"code": null,
"e": 5107,
"s": 5097,
"text": "\nContest\n"
},
{
"code": null,
"e": 5170,
"s": 5107,
"text": "Reset the IDE using the second button on the top right corner."
},
{
"code": null,
"e": 5318,
"s": 5170,
"text": "Avoid using static/global variables in your code as your code is tested against multiple test cases and these tend to retain their previous values."
},
{
"code": null,
"e": 5526,
"s": 5318,
"text": "Passing the Sample/Custom Test cases does not guarantee the correctness of code. On submission, your code is tested against multiple test cases consisting of all possible corner cases and stress constraints."
},
{
"code": null,
"e": 5632,
"s": 5526,
"text": "You can access the hints to get an idea about what is expected of you as well as the final solution code."
}
] |
Scrape Data from PDF Files Using Python and tabula-py | by Aaron Zhu | Towards Data Science | Data science professionals are dealing with data in all shapes and forms. Data could be stored in popular SQL databases, such as PostgreSQL, MySQL, or an old-fashioned excel spreadsheet. Sometimes, data might also be saved in an unconventional format, such as PDF. In this article, I am going to talk about how to scrape data from PDF using Python library: tabula-py.
tabula-py: to scrape text from PDF files
re: to extract data using regular expression
pandas: to construct and manipulate our panel data
pip install tabula-pypip install pandas
import tabula as tbimport pandas as pdimport re
First, let’s talk about scraping PDF data in a structured format. In the following example, we want to scrape the table on the bottom left corner. It is nicely-structured tabular data, in which rows and columns are well defined.
Scraping PDF data in structured form is straightforward using tabula-py. We just need to input the location of the tabular data in the PDF page by specifying the (top, left, bottom, right) coordinates of the area. In practice, you will learn what values to use by trial and error. If the PDF page only includes the target table, then we don’t even need to specify the area. tabula-py should be able to detect the rows and columns automatically.
file = 'state_population.pdf'data = tb.read_pdf(file, area = (300, 0, 600, 800), pages = '1')
Next, we will explore something more interesting — PFD data in an unstructured format.
To implement statistical analysis, data visualization and machine learning model, we need the data in tabular form (panel data). However, many data are only available in an unstructured format. For example, HR staff are likely to keep historical payroll data, which might not be created in tabular form. In the following picture, we have an example of payroll data, which has mixed data structures. On the left section, it has data in long format, including employee name, net amount, pay date and pay period. On the right section, it has pay category, pay rate, hours and pay amount.
There are a few steps we need to take to transform the data into panel format.
Step 1: Import PDF data as a DataFrame
Like data in a structured format, we also use tb.read_pdf to import the unstructured data. This time, we need to specify extra options to properly import the data.
file = 'payroll_sample.pdf'df= tb.read_pdf(file, pages = '1', area = (0, 0, 300, 400), columns = [200, 265, 300, 320], pandas_options={'header': None}, stream=True)[0]
Area and Columns: I’ve talked about area above. Here we will also need to use columns to identify the locations of all relevant columns. Like area, the values of columns would be determined by trial and error.
Stream and Lattice: If there are grid lines to separate each cell, we can use lattice = True to automatically identify each cell, If not, we can use stream = True and columns to manually specify each cell. Stream-mode would look for whitespace between columns. These options might make a huge impact, so we can experiment with either lattice or stream and see if they improve overall scraping.
Step 2: Create a Row Identifier
Now we have some data to work with, we will use Python library Pandas to manipulate the dataframe.
First, we will need to create a new column that can identify unique rows. We notice that employee names (Superman and Batman) seem to be useful to identify the border between different records. Each employee name contains a unique pattern, which starts with a capital letter and ends with a lower-case letter. We can use regular expression '^[A-Z].*[a-z]$' to identify employee name, then use Pandas function cumsum (cumulative sum) to create a row identifier.
df['border'] = df.apply(lambda x: 1 if re.findall('^[A-Z].*[a-z]$', str(x[0])) else 0, axis = 1)df['row'] = df['border'].transform('cumsum')
Step 3: Reshape the data (convert data from long-form to wide form)
Next, we will reshape data on both the left section and right section. For the left section, we create a new dataframe, employee that includes employee_name, net_amount, pay_date and pay_period. For the right section, we create another dataframe, payment that includes OT_Rate, Regular_Rate, OT_Hours, Regular_Hours, OT_Amt and Regular_Amt. To convert the data in a wide form, we can use the Pandas function, pivot.
# reshape left sectionemployee = df[[0, 'row']]employee = employee[employee[0].notnull()]employee['index'] = employee.groupby('row').cumcount()+1employee = employee.pivot(index = ['row'], columns = ['index'], values = 0).reset_index()employee = employee.rename(columns = {1: 'employee_name', 2: 'net_amount', 3: 'pay_date', 4: 'pay_period'})employee['net_amount'] = employee.apply(lambda x: x['net_amount'].replace('Net', '').strip(), axis = 1)# reshape right sectionpayment = df[[1, 2, 3, 4, 'row']]payment = payment[payment[1].notnull()]payment = payment[payment['row']!=0]payment = payment.pivot(index = ['row'], columns = 1, values = [2, 3, 4]).reset_index()payment.columns = [str(col[0])+col[1] for col in payment.columns.values]for i in ['Regular', 'OT']: payment = payment.rename(columns = {f'2{i}': f'{i}_Rate', f'3{i}': f'{i}_Hours', f'4{i}': f'{i}_Amt'})
Step 4: Join the data in the left section with the data in the right section
Lastly, we use the function, merge to join both employee and payment dataframes based on the row identifier.
df_clean = employee.merge(payment, on = ['row'], how = 'inner')
As of today, companies still manually process PDF data. With the help of python libraries, we can save time and money by automating this process of scraping data from PDF files and converting unstructured data into panel data.
Please keep in mind that when scraping data from PDF files, you should always carefully read the terms and conditions posted by the author and make sure you have permission to do so.
If you would like to continue exploring PDF scraping, please check out my other articles:
Scrape Data from PDF Files Using Python and PDFQuery
Extract PDF Text While Preserving Whitespaces Using Python and Pytesseract
How to Convert Scanned Files to Searchable PDF Using Python and Pytesseract
You can sign up for a membership to unlock full access to my articles, and have unlimited access to everything on Medium. Please subscribe if you’d like to get an email notification whenever I post a new article. | [
{
"code": null,
"e": 540,
"s": 172,
"text": "Data science professionals are dealing with data in all shapes and forms. Data could be stored in popular SQL databases, such as PostgreSQL, MySQL, or an old-fashioned excel spreadsheet. Sometimes, data might also be saved in an unconventional format, such as PDF. In this article, I am going to talk about how to scrape data from PDF using Python library: tabula-py."
},
{
"code": null,
"e": 581,
"s": 540,
"text": "tabula-py: to scrape text from PDF files"
},
{
"code": null,
"e": 626,
"s": 581,
"text": "re: to extract data using regular expression"
},
{
"code": null,
"e": 677,
"s": 626,
"text": "pandas: to construct and manipulate our panel data"
},
{
"code": null,
"e": 717,
"s": 677,
"text": "pip install tabula-pypip install pandas"
},
{
"code": null,
"e": 765,
"s": 717,
"text": "import tabula as tbimport pandas as pdimport re"
},
{
"code": null,
"e": 994,
"s": 765,
"text": "First, let’s talk about scraping PDF data in a structured format. In the following example, we want to scrape the table on the bottom left corner. It is nicely-structured tabular data, in which rows and columns are well defined."
},
{
"code": null,
"e": 1439,
"s": 994,
"text": "Scraping PDF data in structured form is straightforward using tabula-py. We just need to input the location of the tabular data in the PDF page by specifying the (top, left, bottom, right) coordinates of the area. In practice, you will learn what values to use by trial and error. If the PDF page only includes the target table, then we don’t even need to specify the area. tabula-py should be able to detect the rows and columns automatically."
},
{
"code": null,
"e": 1533,
"s": 1439,
"text": "file = 'state_population.pdf'data = tb.read_pdf(file, area = (300, 0, 600, 800), pages = '1')"
},
{
"code": null,
"e": 1620,
"s": 1533,
"text": "Next, we will explore something more interesting — PFD data in an unstructured format."
},
{
"code": null,
"e": 2205,
"s": 1620,
"text": "To implement statistical analysis, data visualization and machine learning model, we need the data in tabular form (panel data). However, many data are only available in an unstructured format. For example, HR staff are likely to keep historical payroll data, which might not be created in tabular form. In the following picture, we have an example of payroll data, which has mixed data structures. On the left section, it has data in long format, including employee name, net amount, pay date and pay period. On the right section, it has pay category, pay rate, hours and pay amount."
},
{
"code": null,
"e": 2284,
"s": 2205,
"text": "There are a few steps we need to take to transform the data into panel format."
},
{
"code": null,
"e": 2323,
"s": 2284,
"text": "Step 1: Import PDF data as a DataFrame"
},
{
"code": null,
"e": 2487,
"s": 2323,
"text": "Like data in a structured format, we also use tb.read_pdf to import the unstructured data. This time, we need to specify extra options to properly import the data."
},
{
"code": null,
"e": 2655,
"s": 2487,
"text": "file = 'payroll_sample.pdf'df= tb.read_pdf(file, pages = '1', area = (0, 0, 300, 400), columns = [200, 265, 300, 320], pandas_options={'header': None}, stream=True)[0]"
},
{
"code": null,
"e": 2865,
"s": 2655,
"text": "Area and Columns: I’ve talked about area above. Here we will also need to use columns to identify the locations of all relevant columns. Like area, the values of columns would be determined by trial and error."
},
{
"code": null,
"e": 3259,
"s": 2865,
"text": "Stream and Lattice: If there are grid lines to separate each cell, we can use lattice = True to automatically identify each cell, If not, we can use stream = True and columns to manually specify each cell. Stream-mode would look for whitespace between columns. These options might make a huge impact, so we can experiment with either lattice or stream and see if they improve overall scraping."
},
{
"code": null,
"e": 3291,
"s": 3259,
"text": "Step 2: Create a Row Identifier"
},
{
"code": null,
"e": 3390,
"s": 3291,
"text": "Now we have some data to work with, we will use Python library Pandas to manipulate the dataframe."
},
{
"code": null,
"e": 3851,
"s": 3390,
"text": "First, we will need to create a new column that can identify unique rows. We notice that employee names (Superman and Batman) seem to be useful to identify the border between different records. Each employee name contains a unique pattern, which starts with a capital letter and ends with a lower-case letter. We can use regular expression '^[A-Z].*[a-z]$' to identify employee name, then use Pandas function cumsum (cumulative sum) to create a row identifier."
},
{
"code": null,
"e": 3992,
"s": 3851,
"text": "df['border'] = df.apply(lambda x: 1 if re.findall('^[A-Z].*[a-z]$', str(x[0])) else 0, axis = 1)df['row'] = df['border'].transform('cumsum')"
},
{
"code": null,
"e": 4060,
"s": 3992,
"text": "Step 3: Reshape the data (convert data from long-form to wide form)"
},
{
"code": null,
"e": 4476,
"s": 4060,
"text": "Next, we will reshape data on both the left section and right section. For the left section, we create a new dataframe, employee that includes employee_name, net_amount, pay_date and pay_period. For the right section, we create another dataframe, payment that includes OT_Rate, Regular_Rate, OT_Hours, Regular_Hours, OT_Amt and Regular_Amt. To convert the data in a wide form, we can use the Pandas function, pivot."
},
{
"code": null,
"e": 5344,
"s": 4476,
"text": "# reshape left sectionemployee = df[[0, 'row']]employee = employee[employee[0].notnull()]employee['index'] = employee.groupby('row').cumcount()+1employee = employee.pivot(index = ['row'], columns = ['index'], values = 0).reset_index()employee = employee.rename(columns = {1: 'employee_name', 2: 'net_amount', 3: 'pay_date', 4: 'pay_period'})employee['net_amount'] = employee.apply(lambda x: x['net_amount'].replace('Net', '').strip(), axis = 1)# reshape right sectionpayment = df[[1, 2, 3, 4, 'row']]payment = payment[payment[1].notnull()]payment = payment[payment['row']!=0]payment = payment.pivot(index = ['row'], columns = 1, values = [2, 3, 4]).reset_index()payment.columns = [str(col[0])+col[1] for col in payment.columns.values]for i in ['Regular', 'OT']: payment = payment.rename(columns = {f'2{i}': f'{i}_Rate', f'3{i}': f'{i}_Hours', f'4{i}': f'{i}_Amt'})"
},
{
"code": null,
"e": 5421,
"s": 5344,
"text": "Step 4: Join the data in the left section with the data in the right section"
},
{
"code": null,
"e": 5530,
"s": 5421,
"text": "Lastly, we use the function, merge to join both employee and payment dataframes based on the row identifier."
},
{
"code": null,
"e": 5594,
"s": 5530,
"text": "df_clean = employee.merge(payment, on = ['row'], how = 'inner')"
},
{
"code": null,
"e": 5821,
"s": 5594,
"text": "As of today, companies still manually process PDF data. With the help of python libraries, we can save time and money by automating this process of scraping data from PDF files and converting unstructured data into panel data."
},
{
"code": null,
"e": 6004,
"s": 5821,
"text": "Please keep in mind that when scraping data from PDF files, you should always carefully read the terms and conditions posted by the author and make sure you have permission to do so."
},
{
"code": null,
"e": 6094,
"s": 6004,
"text": "If you would like to continue exploring PDF scraping, please check out my other articles:"
},
{
"code": null,
"e": 6147,
"s": 6094,
"text": "Scrape Data from PDF Files Using Python and PDFQuery"
},
{
"code": null,
"e": 6222,
"s": 6147,
"text": "Extract PDF Text While Preserving Whitespaces Using Python and Pytesseract"
},
{
"code": null,
"e": 6298,
"s": 6222,
"text": "How to Convert Scanned Files to Searchable PDF Using Python and Pytesseract"
}
] |
All Pandas groupby() You Should Know for Grouping Data and Performing Operations | by B. Chen | Towards Data Science | In exploratory data analysis, we often would like to analyze data by some categories. In SQL, the GROUP BY statement groups row that has the same category values into summary rows. In Pandas, SQL’s GROUP BY operation is performed using the similarly named groupby() method. Pandas’ groupby() allows us to split data into separate groups to perform computations for better analysis.
In this article, you’ll learn the “group by” process (split-apply-combine) and how to use Pandas’s groupby() function to group data and perform operations. This article is structured as follows:
What is Pandas groupby() and how to access groups information?The “group by” process: split-apply-combineAggregationTransformationFiltrationGrouping by multiple categoriesResetting index with as_indexHandling missing values
What is Pandas groupby() and how to access groups information?
The “group by” process: split-apply-combine
Aggregation
Transformation
Filtration
Grouping by multiple categories
Resetting index with as_index
Handling missing values
For demonstration, we will use the Titanic dataset available on Kaggle.
df = pd.read_csv('data/titanic/train.csv')df.head()
Please check out Notebook for the source code.
The role of groupby() is anytime we want to analyze data by some categories. The simplest call must have a column name. In our example, let’s use the Sex column.
df_groupby_sex = df.groupby('Sex')
The statement literally means we would like to analyze our data by different Sex values. By calling the type() function on the result, we can see that it returns a DataFrameGroupBy object.
>>> type(df_groupby_sex)pandas.core.groupby.generic.DataFrameGroupBy
The groupby() function returns a DataFrameGroupBy object but essentially describes how the rows of the original dataset have been split. There are some attributes and methods available for us to access groups information
We can use ngroups attribute to get the number of groups
>>> df_groupby_sex.ngroups2
Use groups attribute to get groups object. Those integer numbers in the list are the row number.
>>> df_groupby_sex.groups{'female': [1, 2, 5, 8, 10, 21, 22, 25, 26, 27, 36, 41, 44, 47, 51, 58, 60, 65, 70, 71, 72, 76, 77, 78, 80, 87, 88, 93, 94, 95, 100, 102, 104, 105, 109, 113, 116, 119, 120, 121, 123, 129, 134, 138, 144, 146, 147, ...], 'male': [0, 3, 4, ...]}
We can use size() method to compute and display group sizes.
>>> df_groupby_sex.size()Sexfemale 256male 456dtype: int64
To preview groups, we can call first() or last() to preview the result with the first or last entry.
df_groupby_sex.first()df_groupby_sex.last()
We can use get_group() method to retrieve one of the created groups
df_female = df_groupby_sex.get_group('female')df_female.head()
Generally speaking, “group by” is referring to a process involving one or more of the following steps:
(1) Splitting the data into groups. (2). Applying a function to each group independently, (3) Combining the results into a data structure.
Out of these, Pandas groupby() is widely used for the split step and it’s the most straightforward. In fact, in many situations, we may wish to do something with those groups. In the apply step, we might wish to do one of the following:
Aggregation: compute a summary statistic for each group. for example, sum, mean, or count.
Transformation: perform some group-specific computations and return a like-indexed object. For example, standardize data within a group or replacing missing values within groups.
Filtration: discard some groups, according to a group-wise computation that evaluates True or False. For example, discard data that belongs to groups with only a few members or filter out data based on the group sum or mean.
By Pandas Official Tutorial: groupby: split-apply-combine [1]
In the following article, we will explore the real use cases of the “group by” process.
Once DataFrameGroupBy has been created, several methods are available to perform a computation on the grouped data. An obvious one is to perform aggregation - compute a summary statistic for each group.
To perform aggregation on a specific column
>>> df.groupby('Sex').Age.max()Sexfemale 63.0male 80.0Name: Age, dtype: float64
There is a method called agg() and it allows us to specify multiple aggregation functions at once.
df.groupby('Sex').Age.agg(['max', 'min', 'count', 'median', 'mean'])
Sometimes, you may prefer to use a custom column name:
df.groupby('Sex').Age.agg( sex_max=('max'), sex_min=('min'),)
If you would like to use a custom aggregation function:
def categorize(x): m = x.mean() return True if m > 29 else Falsedf.groupby('Sex').Age.agg(['max', 'mean', categorize])
We can also use a lambda expression
df.groupby('Sex').Age.agg( ['max', 'mean', lambda x: True if x.mean() > 50 else False])
Turns out when writing a groupby() we don’t actually have to specify a column like Age. Without a column, it will perform the aggregation across all of the numeric columns
df.groupby('Sex').mean()
Similarly, we can call agg() without a column.
df.groupby('Sex').agg(['mean', 'median'])
Transformation is a process in which we perform some group-specific computations and return a like-indexed (same length) object. When looking for transforming data, transform() and apply() are the most commonly used functions.
Let’s create a lambda expression for Standardization.
standardization = lambda x: (x - x.mean()) / x.std()
To perform the standardization on Age column with transform()
df.groupby('Sex').Age.transform(standardization)0 1.6306571 1.5167512 0.574994 ... 707 -0.294321708 NaN709 0.956720710 0.282784711 NaNName: Age, Length: 712, dtype: float64
To perform the standardization on Age column using apply()
df.groupby('Sex').Age.apply(standardization)0 1.6306571 1.5167512 0.574994 ... 707 -0.294321708 NaN709 0.956720710 0.282784711 NaNName: Age, Length: 712, dtype: float64
If you would like to learn more transform() and apply(), please check out:
towardsdatascience.com
towardsdatascience.com
Filtration is a process in which we discard some groups, according to a group-wise computation that evaluates True or False.
Let’s take a look at how to discard data that belongs to groups with only a few members.
First, we group the data by Cabin and take a quick look at the size for each group.
df.groupby('Cabin').size()CabinA10 1A14 1A16 1A19 1..F2 2F33 3F4 1G6 2T 1Length: 128, dtype: int64
Now let’s filter data to return all passengers that lived in a cabin has ≥ 4 people. To do that, we use filter() method with a lambda expression.
df.groupby('Cabin').filter(lambda x: len(x) >= 4)
So far, we have been passing a single label to groupby() to group data by one column. Instead of a label, we can also pass a list of labels to work with multiple grouping.
# Creating a subsetdf_subset = df.loc[:, ['Sex', 'Pclass', 'Age', 'Fare']]# Group by multiple categoriesdf_subset.groupby(['Sex', 'Pclass']).mean()
Grouping by multiple categories will result in a MultiIndex DataFrame. However, it is not practical to have Sex and Pclass columns as the index (See image above) when we need to perform some data analysis.
We can call the reset_index() method on the DataFrame to reset them and use the default 0-based integer index instead.
df_groupby_multi = subset.groupby(['Sex', 'Pclass']).mean()# Resetting indexdf_groupby_multi.reset_index()
But there is a more effective way using the as_index argument. The argument is to configure whether the index is group labels or not. If it is set to False, the group labels are represented as columns instead of index.
subset.groupby(['Sex', 'Pclass'], as_index=False).mean()
The groupby() function ignores the missing values by default. Let’s first create some missing values in the Sex column.
# Creating missing value in the Sex columnsubset.iloc[80:100, 0] = np.nan# Validating the missing valuessubset.isna().sum()Sex 20Pclass 0Age 146Fare 0dtype: int64
When calculating the mean value for each category in the Sex column, we won’t get any information about the missing values.
# The groupby function ignores the missing values by default.subset.groupby(['Sex', 'Pclass']).mean()
In some cases, we also need to get an overview of the missing values. We can set the dropna argument to False to include missing values.
subset.groupby(['Sex', 'Pclass'], dropna=False).mean()
Pandas groupby() function is one of the most widely used functions in data analysis. It is really important because of its ability to aggregate, transform and filter data in each group.
I hope this article will help you to save time in learning Pandas. I recommend you to check out the documentation for the groupby() API and to know about other things you can do.
Thanks for reading. Please check out the notebook for the source code and stay tuned if you are interested in the practical aspect of machine learning.
All Pandas json_normalize() you should know for flattening JSON
Using Pandas method chaining to improve code readability
How to do a Custom Sort on Pandas DataFrame
All the Pandas shift() you should know for data analysis
When to use Pandas transform() function
Pandas concat() tricks you should know
Difference between apply() and transform() in Pandas
All the Pandas merge() you should know
Working with datetime in Pandas DataFrame
Pandas read_csv() tricks you should know
4 tricks you should know to parse date columns with Pandas read_csv()
More tutorials can be found on my Github
[1] Pandas Official Tutorial: Group by: split-apply-combine | [
{
"code": null,
"e": 554,
"s": 172,
"text": "In exploratory data analysis, we often would like to analyze data by some categories. In SQL, the GROUP BY statement groups row that has the same category values into summary rows. In Pandas, SQL’s GROUP BY operation is performed using the similarly named groupby() method. Pandas’ groupby() allows us to split data into separate groups to perform computations for better analysis."
},
{
"code": null,
"e": 749,
"s": 554,
"text": "In this article, you’ll learn the “group by” process (split-apply-combine) and how to use Pandas’s groupby() function to group data and perform operations. This article is structured as follows:"
},
{
"code": null,
"e": 973,
"s": 749,
"text": "What is Pandas groupby() and how to access groups information?The “group by” process: split-apply-combineAggregationTransformationFiltrationGrouping by multiple categoriesResetting index with as_indexHandling missing values"
},
{
"code": null,
"e": 1036,
"s": 973,
"text": "What is Pandas groupby() and how to access groups information?"
},
{
"code": null,
"e": 1080,
"s": 1036,
"text": "The “group by” process: split-apply-combine"
},
{
"code": null,
"e": 1092,
"s": 1080,
"text": "Aggregation"
},
{
"code": null,
"e": 1107,
"s": 1092,
"text": "Transformation"
},
{
"code": null,
"e": 1118,
"s": 1107,
"text": "Filtration"
},
{
"code": null,
"e": 1150,
"s": 1118,
"text": "Grouping by multiple categories"
},
{
"code": null,
"e": 1180,
"s": 1150,
"text": "Resetting index with as_index"
},
{
"code": null,
"e": 1204,
"s": 1180,
"text": "Handling missing values"
},
{
"code": null,
"e": 1276,
"s": 1204,
"text": "For demonstration, we will use the Titanic dataset available on Kaggle."
},
{
"code": null,
"e": 1328,
"s": 1276,
"text": "df = pd.read_csv('data/titanic/train.csv')df.head()"
},
{
"code": null,
"e": 1375,
"s": 1328,
"text": "Please check out Notebook for the source code."
},
{
"code": null,
"e": 1537,
"s": 1375,
"text": "The role of groupby() is anytime we want to analyze data by some categories. The simplest call must have a column name. In our example, let’s use the Sex column."
},
{
"code": null,
"e": 1572,
"s": 1537,
"text": "df_groupby_sex = df.groupby('Sex')"
},
{
"code": null,
"e": 1761,
"s": 1572,
"text": "The statement literally means we would like to analyze our data by different Sex values. By calling the type() function on the result, we can see that it returns a DataFrameGroupBy object."
},
{
"code": null,
"e": 1830,
"s": 1761,
"text": ">>> type(df_groupby_sex)pandas.core.groupby.generic.DataFrameGroupBy"
},
{
"code": null,
"e": 2051,
"s": 1830,
"text": "The groupby() function returns a DataFrameGroupBy object but essentially describes how the rows of the original dataset have been split. There are some attributes and methods available for us to access groups information"
},
{
"code": null,
"e": 2108,
"s": 2051,
"text": "We can use ngroups attribute to get the number of groups"
},
{
"code": null,
"e": 2136,
"s": 2108,
"text": ">>> df_groupby_sex.ngroups2"
},
{
"code": null,
"e": 2233,
"s": 2136,
"text": "Use groups attribute to get groups object. Those integer numbers in the list are the row number."
},
{
"code": null,
"e": 2501,
"s": 2233,
"text": ">>> df_groupby_sex.groups{'female': [1, 2, 5, 8, 10, 21, 22, 25, 26, 27, 36, 41, 44, 47, 51, 58, 60, 65, 70, 71, 72, 76, 77, 78, 80, 87, 88, 93, 94, 95, 100, 102, 104, 105, 109, 113, 116, 119, 120, 121, 123, 129, 134, 138, 144, 146, 147, ...], 'male': [0, 3, 4, ...]}"
},
{
"code": null,
"e": 2562,
"s": 2501,
"text": "We can use size() method to compute and display group sizes."
},
{
"code": null,
"e": 2629,
"s": 2562,
"text": ">>> df_groupby_sex.size()Sexfemale 256male 456dtype: int64"
},
{
"code": null,
"e": 2730,
"s": 2629,
"text": "To preview groups, we can call first() or last() to preview the result with the first or last entry."
},
{
"code": null,
"e": 2774,
"s": 2730,
"text": "df_groupby_sex.first()df_groupby_sex.last()"
},
{
"code": null,
"e": 2842,
"s": 2774,
"text": "We can use get_group() method to retrieve one of the created groups"
},
{
"code": null,
"e": 2905,
"s": 2842,
"text": "df_female = df_groupby_sex.get_group('female')df_female.head()"
},
{
"code": null,
"e": 3008,
"s": 2905,
"text": "Generally speaking, “group by” is referring to a process involving one or more of the following steps:"
},
{
"code": null,
"e": 3147,
"s": 3008,
"text": "(1) Splitting the data into groups. (2). Applying a function to each group independently, (3) Combining the results into a data structure."
},
{
"code": null,
"e": 3384,
"s": 3147,
"text": "Out of these, Pandas groupby() is widely used for the split step and it’s the most straightforward. In fact, in many situations, we may wish to do something with those groups. In the apply step, we might wish to do one of the following:"
},
{
"code": null,
"e": 3475,
"s": 3384,
"text": "Aggregation: compute a summary statistic for each group. for example, sum, mean, or count."
},
{
"code": null,
"e": 3654,
"s": 3475,
"text": "Transformation: perform some group-specific computations and return a like-indexed object. For example, standardize data within a group or replacing missing values within groups."
},
{
"code": null,
"e": 3879,
"s": 3654,
"text": "Filtration: discard some groups, according to a group-wise computation that evaluates True or False. For example, discard data that belongs to groups with only a few members or filter out data based on the group sum or mean."
},
{
"code": null,
"e": 3941,
"s": 3879,
"text": "By Pandas Official Tutorial: groupby: split-apply-combine [1]"
},
{
"code": null,
"e": 4029,
"s": 3941,
"text": "In the following article, we will explore the real use cases of the “group by” process."
},
{
"code": null,
"e": 4232,
"s": 4029,
"text": "Once DataFrameGroupBy has been created, several methods are available to perform a computation on the grouped data. An obvious one is to perform aggregation - compute a summary statistic for each group."
},
{
"code": null,
"e": 4276,
"s": 4232,
"text": "To perform aggregation on a specific column"
},
{
"code": null,
"e": 4364,
"s": 4276,
"text": ">>> df.groupby('Sex').Age.max()Sexfemale 63.0male 80.0Name: Age, dtype: float64"
},
{
"code": null,
"e": 4463,
"s": 4364,
"text": "There is a method called agg() and it allows us to specify multiple aggregation functions at once."
},
{
"code": null,
"e": 4532,
"s": 4463,
"text": "df.groupby('Sex').Age.agg(['max', 'min', 'count', 'median', 'mean'])"
},
{
"code": null,
"e": 4587,
"s": 4532,
"text": "Sometimes, you may prefer to use a custom column name:"
},
{
"code": null,
"e": 4655,
"s": 4587,
"text": "df.groupby('Sex').Age.agg( sex_max=('max'), sex_min=('min'),)"
},
{
"code": null,
"e": 4711,
"s": 4655,
"text": "If you would like to use a custom aggregation function:"
},
{
"code": null,
"e": 4836,
"s": 4711,
"text": "def categorize(x): m = x.mean() return True if m > 29 else Falsedf.groupby('Sex').Age.agg(['max', 'mean', categorize])"
},
{
"code": null,
"e": 4872,
"s": 4836,
"text": "We can also use a lambda expression"
},
{
"code": null,
"e": 4963,
"s": 4872,
"text": "df.groupby('Sex').Age.agg( ['max', 'mean', lambda x: True if x.mean() > 50 else False])"
},
{
"code": null,
"e": 5135,
"s": 4963,
"text": "Turns out when writing a groupby() we don’t actually have to specify a column like Age. Without a column, it will perform the aggregation across all of the numeric columns"
},
{
"code": null,
"e": 5160,
"s": 5135,
"text": "df.groupby('Sex').mean()"
},
{
"code": null,
"e": 5207,
"s": 5160,
"text": "Similarly, we can call agg() without a column."
},
{
"code": null,
"e": 5249,
"s": 5207,
"text": "df.groupby('Sex').agg(['mean', 'median'])"
},
{
"code": null,
"e": 5476,
"s": 5249,
"text": "Transformation is a process in which we perform some group-specific computations and return a like-indexed (same length) object. When looking for transforming data, transform() and apply() are the most commonly used functions."
},
{
"code": null,
"e": 5530,
"s": 5476,
"text": "Let’s create a lambda expression for Standardization."
},
{
"code": null,
"e": 5583,
"s": 5530,
"text": "standardization = lambda x: (x - x.mean()) / x.std()"
},
{
"code": null,
"e": 5645,
"s": 5583,
"text": "To perform the standardization on Age column with transform()"
},
{
"code": null,
"e": 5866,
"s": 5645,
"text": "df.groupby('Sex').Age.transform(standardization)0 1.6306571 1.5167512 0.574994 ... 707 -0.294321708 NaN709 0.956720710 0.282784711 NaNName: Age, Length: 712, dtype: float64"
},
{
"code": null,
"e": 5925,
"s": 5866,
"text": "To perform the standardization on Age column using apply()"
},
{
"code": null,
"e": 6142,
"s": 5925,
"text": "df.groupby('Sex').Age.apply(standardization)0 1.6306571 1.5167512 0.574994 ... 707 -0.294321708 NaN709 0.956720710 0.282784711 NaNName: Age, Length: 712, dtype: float64"
},
{
"code": null,
"e": 6217,
"s": 6142,
"text": "If you would like to learn more transform() and apply(), please check out:"
},
{
"code": null,
"e": 6240,
"s": 6217,
"text": "towardsdatascience.com"
},
{
"code": null,
"e": 6263,
"s": 6240,
"text": "towardsdatascience.com"
},
{
"code": null,
"e": 6388,
"s": 6263,
"text": "Filtration is a process in which we discard some groups, according to a group-wise computation that evaluates True or False."
},
{
"code": null,
"e": 6477,
"s": 6388,
"text": "Let’s take a look at how to discard data that belongs to groups with only a few members."
},
{
"code": null,
"e": 6561,
"s": 6477,
"text": "First, we group the data by Cabin and take a quick look at the size for each group."
},
{
"code": null,
"e": 6692,
"s": 6561,
"text": "df.groupby('Cabin').size()CabinA10 1A14 1A16 1A19 1..F2 2F33 3F4 1G6 2T 1Length: 128, dtype: int64"
},
{
"code": null,
"e": 6838,
"s": 6692,
"text": "Now let’s filter data to return all passengers that lived in a cabin has ≥ 4 people. To do that, we use filter() method with a lambda expression."
},
{
"code": null,
"e": 6888,
"s": 6838,
"text": "df.groupby('Cabin').filter(lambda x: len(x) >= 4)"
},
{
"code": null,
"e": 7060,
"s": 6888,
"text": "So far, we have been passing a single label to groupby() to group data by one column. Instead of a label, we can also pass a list of labels to work with multiple grouping."
},
{
"code": null,
"e": 7208,
"s": 7060,
"text": "# Creating a subsetdf_subset = df.loc[:, ['Sex', 'Pclass', 'Age', 'Fare']]# Group by multiple categoriesdf_subset.groupby(['Sex', 'Pclass']).mean()"
},
{
"code": null,
"e": 7414,
"s": 7208,
"text": "Grouping by multiple categories will result in a MultiIndex DataFrame. However, it is not practical to have Sex and Pclass columns as the index (See image above) when we need to perform some data analysis."
},
{
"code": null,
"e": 7533,
"s": 7414,
"text": "We can call the reset_index() method on the DataFrame to reset them and use the default 0-based integer index instead."
},
{
"code": null,
"e": 7640,
"s": 7533,
"text": "df_groupby_multi = subset.groupby(['Sex', 'Pclass']).mean()# Resetting indexdf_groupby_multi.reset_index()"
},
{
"code": null,
"e": 7859,
"s": 7640,
"text": "But there is a more effective way using the as_index argument. The argument is to configure whether the index is group labels or not. If it is set to False, the group labels are represented as columns instead of index."
},
{
"code": null,
"e": 7916,
"s": 7859,
"text": "subset.groupby(['Sex', 'Pclass'], as_index=False).mean()"
},
{
"code": null,
"e": 8036,
"s": 7916,
"text": "The groupby() function ignores the missing values by default. Let’s first create some missing values in the Sex column."
},
{
"code": null,
"e": 8224,
"s": 8036,
"text": "# Creating missing value in the Sex columnsubset.iloc[80:100, 0] = np.nan# Validating the missing valuessubset.isna().sum()Sex 20Pclass 0Age 146Fare 0dtype: int64"
},
{
"code": null,
"e": 8348,
"s": 8224,
"text": "When calculating the mean value for each category in the Sex column, we won’t get any information about the missing values."
},
{
"code": null,
"e": 8450,
"s": 8348,
"text": "# The groupby function ignores the missing values by default.subset.groupby(['Sex', 'Pclass']).mean()"
},
{
"code": null,
"e": 8587,
"s": 8450,
"text": "In some cases, we also need to get an overview of the missing values. We can set the dropna argument to False to include missing values."
},
{
"code": null,
"e": 8642,
"s": 8587,
"text": "subset.groupby(['Sex', 'Pclass'], dropna=False).mean()"
},
{
"code": null,
"e": 8828,
"s": 8642,
"text": "Pandas groupby() function is one of the most widely used functions in data analysis. It is really important because of its ability to aggregate, transform and filter data in each group."
},
{
"code": null,
"e": 9007,
"s": 8828,
"text": "I hope this article will help you to save time in learning Pandas. I recommend you to check out the documentation for the groupby() API and to know about other things you can do."
},
{
"code": null,
"e": 9159,
"s": 9007,
"text": "Thanks for reading. Please check out the notebook for the source code and stay tuned if you are interested in the practical aspect of machine learning."
},
{
"code": null,
"e": 9223,
"s": 9159,
"text": "All Pandas json_normalize() you should know for flattening JSON"
},
{
"code": null,
"e": 9280,
"s": 9223,
"text": "Using Pandas method chaining to improve code readability"
},
{
"code": null,
"e": 9324,
"s": 9280,
"text": "How to do a Custom Sort on Pandas DataFrame"
},
{
"code": null,
"e": 9381,
"s": 9324,
"text": "All the Pandas shift() you should know for data analysis"
},
{
"code": null,
"e": 9421,
"s": 9381,
"text": "When to use Pandas transform() function"
},
{
"code": null,
"e": 9460,
"s": 9421,
"text": "Pandas concat() tricks you should know"
},
{
"code": null,
"e": 9513,
"s": 9460,
"text": "Difference between apply() and transform() in Pandas"
},
{
"code": null,
"e": 9552,
"s": 9513,
"text": "All the Pandas merge() you should know"
},
{
"code": null,
"e": 9594,
"s": 9552,
"text": "Working with datetime in Pandas DataFrame"
},
{
"code": null,
"e": 9635,
"s": 9594,
"text": "Pandas read_csv() tricks you should know"
},
{
"code": null,
"e": 9705,
"s": 9635,
"text": "4 tricks you should know to parse date columns with Pandas read_csv()"
},
{
"code": null,
"e": 9746,
"s": 9705,
"text": "More tutorials can be found on my Github"
}
] |
Tryit Editor v3.7 | Tryit: The flex-basis property | [] |
C# | Gets or Sets the element at the specified index in the List - GeeksforGeeks | 01 Feb, 2019
List<T>.Item[Int32] Property is used to gets or sets the element at the specified index.
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 T this[int index] { get; set; }
Parameter:
index: It is the zero-based index of the element to get or set of type System.Int32.
Return Value: This property returns the element at the specified index.
Exception: This method will give ArgumentOutOfRangeException if the index is less than 0 or index is equal to or greater than Count.
Below are the examples to illustrate the use of List<T>.Item[Int32] Property:
Example 1:
// C# program to illustrate the// List.Item[32] propertyusing System;using System.Collections.Generic; class Geeks { // Main Method public static void Main(String[] args) { // Creating a List of Strings List<String> firstlist = new List<String>(); // adding elements in firstlist firstlist.Add("A"); firstlist.Add("B"); firstlist.Add("C"); firstlist.Add("D"); firstlist.Add("E"); firstlist.Add("F"); // getting the element of // firstlist using Item property Console.WriteLine("Element at index 2: " + firstlist[2]); }}
Output:
Element at index 2: C
Example 2:
// C# program to illustrate the// List.Item[32] propertyusing System;using System.Collections.Generic; class Geeks { // Main Method public static void Main(String[] args) { // Creating a List of String List<String> firstlist = new List<String>(); // adding elements in firstlist firstlist.Add("A"); firstlist.Add("B"); firstlist.Add("C"); firstlist.Add("D"); firstlist.Add("E"); firstlist.Add("F"); // Before setting the another // value of index 2 we will get // the element of firstlist // using Item property Console.WriteLine("Element at index 2: " + firstlist[2]); // setting the value of Element firstlist[2] = "Z"; // displaying the updated value Console.WriteLine("After Setting the new value at 2: " + firstlist[2]); }}
Output:
Element at index 2: C
After Setting the new value at 2: Z
Reference:
https://docs.microsoft.com/en-us/dotnet/api/system.collections.generic.list-1.item?view=netframework-4.7.2
CSharp-Collections-Namespace
CSharp-Generic-List
CSharp-Generic-Namespace
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
C# | Constructors
Introduction to .NET Framework
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": 24127,
"s": 24099,
"text": "\n01 Feb, 2019"
},
{
"code": null,
"e": 24216,
"s": 24127,
"text": "List<T>.Item[Int32] Property is used to gets or sets the element at the specified index."
},
{
"code": null,
"e": 24236,
"s": 24216,
"text": "Properties of List:"
},
{
"code": null,
"e": 24322,
"s": 24236,
"text": "It is different from the arrays. A list can be resized dynamically but arrays cannot."
},
{
"code": null,
"e": 24425,
"s": 24322,
"text": "List class can accept null as a valid value for reference types and it also allows duplicate elements."
},
{
"code": null,
"e": 24649,
"s": 24425,
"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": 24657,
"s": 24649,
"text": "Syntax:"
},
{
"code": null,
"e": 24696,
"s": 24657,
"text": "public T this[int index] { get; set; }"
},
{
"code": null,
"e": 24707,
"s": 24696,
"text": "Parameter:"
},
{
"code": null,
"e": 24792,
"s": 24707,
"text": "index: It is the zero-based index of the element to get or set of type System.Int32."
},
{
"code": null,
"e": 24864,
"s": 24792,
"text": "Return Value: This property returns the element at the specified index."
},
{
"code": null,
"e": 24997,
"s": 24864,
"text": "Exception: This method will give ArgumentOutOfRangeException if the index is less than 0 or index is equal to or greater than Count."
},
{
"code": null,
"e": 25075,
"s": 24997,
"text": "Below are the examples to illustrate the use of List<T>.Item[Int32] Property:"
},
{
"code": null,
"e": 25086,
"s": 25075,
"text": "Example 1:"
},
{
"code": "// C# program to illustrate the// List.Item[32] propertyusing System;using System.Collections.Generic; class Geeks { // Main Method public static void Main(String[] args) { // Creating a List of Strings List<String> firstlist = new List<String>(); // adding elements in firstlist firstlist.Add(\"A\"); firstlist.Add(\"B\"); firstlist.Add(\"C\"); firstlist.Add(\"D\"); firstlist.Add(\"E\"); firstlist.Add(\"F\"); // getting the element of // firstlist using Item property Console.WriteLine(\"Element at index 2: \" + firstlist[2]); }}",
"e": 25711,
"s": 25086,
"text": null
},
{
"code": null,
"e": 25719,
"s": 25711,
"text": "Output:"
},
{
"code": null,
"e": 25742,
"s": 25719,
"text": "Element at index 2: C\n"
},
{
"code": null,
"e": 25753,
"s": 25742,
"text": "Example 2:"
},
{
"code": "// C# program to illustrate the// List.Item[32] propertyusing System;using System.Collections.Generic; class Geeks { // Main Method public static void Main(String[] args) { // Creating a List of String List<String> firstlist = new List<String>(); // adding elements in firstlist firstlist.Add(\"A\"); firstlist.Add(\"B\"); firstlist.Add(\"C\"); firstlist.Add(\"D\"); firstlist.Add(\"E\"); firstlist.Add(\"F\"); // Before setting the another // value of index 2 we will get // the element of firstlist // using Item property Console.WriteLine(\"Element at index 2: \" + firstlist[2]); // setting the value of Element firstlist[2] = \"Z\"; // displaying the updated value Console.WriteLine(\"After Setting the new value at 2: \" + firstlist[2]); }}",
"e": 26633,
"s": 25753,
"text": null
},
{
"code": null,
"e": 26641,
"s": 26633,
"text": "Output:"
},
{
"code": null,
"e": 26700,
"s": 26641,
"text": "Element at index 2: C\nAfter Setting the new value at 2: Z\n"
},
{
"code": null,
"e": 26711,
"s": 26700,
"text": "Reference:"
},
{
"code": null,
"e": 26818,
"s": 26711,
"text": "https://docs.microsoft.com/en-us/dotnet/api/system.collections.generic.list-1.item?view=netframework-4.7.2"
},
{
"code": null,
"e": 26847,
"s": 26818,
"text": "CSharp-Collections-Namespace"
},
{
"code": null,
"e": 26867,
"s": 26847,
"text": "CSharp-Generic-List"
},
{
"code": null,
"e": 26892,
"s": 26867,
"text": "CSharp-Generic-Namespace"
},
{
"code": null,
"e": 26895,
"s": 26892,
"text": "C#"
},
{
"code": null,
"e": 26993,
"s": 26895,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 27002,
"s": 26993,
"text": "Comments"
},
{
"code": null,
"e": 27015,
"s": 27002,
"text": "Old Comments"
},
{
"code": null,
"e": 27030,
"s": 27015,
"text": "C# | Delegates"
},
{
"code": null,
"e": 27070,
"s": 27030,
"text": "Top 50 C# Interview Questions & Answers"
},
{
"code": null,
"e": 27088,
"s": 27070,
"text": "C# | Constructors"
},
{
"code": null,
"e": 27119,
"s": 27088,
"text": "Introduction to .NET Framework"
},
{
"code": null,
"e": 27142,
"s": 27119,
"text": "Extension Method in C#"
},
{
"code": null,
"e": 27164,
"s": 27142,
"text": "C# | Class and Object"
},
{
"code": null,
"e": 27186,
"s": 27164,
"text": "C# | Abstract Classes"
},
{
"code": null,
"e": 27222,
"s": 27186,
"text": "Common Language Runtime (CLR) in C#"
},
{
"code": null,
"e": 27241,
"s": 27222,
"text": "C# | Encapsulation"
}
] |
ASP.NET MVC - Routing | Routing is the process of directing an HTTP request to a controller and the functionality of this processing is implemented in System.Web.Routing. This assembly is not part of ASP.NET MVC. It is actually part of the ASP.NET runtime, and it was officially released with the ASP.NET as a .NET 3.5 SP1.
System.Web.Routing is used by the MVC framework, but it's also used by ASP.NET Dynamic Data. The MVC framework leverages routing to direct a request to a controller. The Global.asax file is that part of your application, where you will define the route for your application.
This is the code from the application start event in Global.asax from the MVC App which we created in the previous chapter.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using System.Web.Routing;
namespace MVCFirstApp {
public class MvcApplication : System.Web.HttpApplication {
protected void Application_Start(){
AreaRegistration.RegisterAllAreas();
RouteConfig.RegisterRoutes(RouteTable.Routes);
}
}
}
Following is the implementation of RouteConfig class, which contains one method RegisterRoutes.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using System.Web.Routing;
namespace MVCFirstApp {
public class RouteConfig {
public static void RegisterRoutes(RouteCollection routes){
routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
routes.MapRoute(
name: "Default",
url: "{controller}/{action}/{id}",
defaults: new{ controller = "Home", action = "Index", id = UrlParameter.Optional});
}
}
}
You will define the routes and those routes will map URLs to a specific controller action. An action is just a method on the controller. It can also pick parameters out of that URL and pass them as parameters into the method.
So this route that is defined in the application is the default route. As seen in the above code, when you see a URL arrive in the form of (something)/(something)/(something), then the first piece is the controller name, second piece is the action name, and the third piece is an ID parameter.
MVC applications use the ASP.NET routing system, which decides how URLs map to controllers and actions.
When Visual Studio creates the MVC project, it adds some default routes to get us started. When you run your application, you will see that Visual Studio has directed the browser to port 63664. You will almost certainly see a different port number in the URL that your browser requests because Visual Studio allocates a random port when the project is created.
In the last example, we have added a HomeController, so you can also request any of the following URLs, and they will be directed to the Index action on the HomeController.
http://localhost:63664/Home/
http://localhost:63664/Home/Index
When a browser requests http://mysite/ or http://mysite/Home, it gets back the output from HomeController’s Index method.
You can try this as well by changing the URL in the browser. In this example, it is http://localhost:63664/, except that the port might be different.
If you append /Home or /Home/Index to the URL and press ‘Enter’ button, you will see the same result from the MVC application.
As you can see in this case, the convention is that we have a controller called HomeController and this HomeController will be the starting point for our MVC application.
The default routes that Visual Studio creates for a new project assumes that you will follow this convention. But if you want to follow your own convention then you would need to modify the routes.
You can certainly add your own routes. If you don't like these action names, if you have different ID parameters or if you just in general have a different URL structure for your site, then you can add your own route entries.
Let’s take a look at a simple example. Consider we have a page that contains the list of processes. Following is the code, which will route to the process page.
routes.MapRoute(
"Process",
"Process/{action}/{id}",
defaults: new{
controller = "Process", action = "List ", id = UrlParameter.Optional}
);
When someone comes in and looks for a URL with Process/Action/Id, they will go to the Process Controller. We can make the action a little bit different, the default action, we can make that a List instead of Index.
Now a request that arrives looks like localhosts/process. The routing engine will use this routing configuration to pass that along, so it's going to use a default action of List.
Following is the complete class implementation.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using System.Web.Routing;
namespace MVCFirstApp{
public class RouteConfig{
public static void RegisterRoutes(RouteCollection routes){
routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
routes.MapRoute(
"Process", "Process/{action}/{id}",
defaults: new{
controller = " Process", action = "List ", id =
UrlParameter.Optional});
routes.MapRoute(
name: "Default", url: "{controller}/{action}/{id}",
defaults: new{
controller = "Home", action = "Index", id =
UrlParameter.Optional});
}
}
}
Step 1 − Run this and request for a process page with the following URL http://localhost:63664/Process
You will see an HTTP 404, because the routing engine is looking for ProcessController, which is not available.
Step 2 − Create ProcessController by right-clicking on Controllers folder in the solution explorer and select Add → Controller.
It will display the Add Scaffold dialog.
Step 3 − Select the MVC 5 Controller – Empty option and click ‘Add’ button.
The Add Controller dialog will appear.
Step 4 − Set the name to ProcessController and click ‘Add’ button.
Now you will see a new C# file ProcessController.cs in the Controllers folder, which is open for editing in Visual Studio as well.
Now our default action is going to be List, so we want to have a List action here instead of Index.
Step 5 − Change the return type from ActionResult to string and also return some string from this action method using the following code.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
namespace MVCFirstApp.Controllers{
public class ProcessController : Controller{
// GET: Process
public string List(){
return "This is Process page";
}
}
}
Step 6 − When you run this application, again you will see the result from the default route. When you specify the following URL, http://localhost:63664/Process/List, then you will see the result from the ProcessController.
51 Lectures
5.5 hours
Anadi Sharma
44 Lectures
4.5 hours
Kaushik Roy Chowdhury
42 Lectures
18 hours
SHIVPRASAD KOIRALA
57 Lectures
3.5 hours
University Code
40 Lectures
2.5 hours
University Code
138 Lectures
9 hours
Bhrugen Patel
Print
Add Notes
Bookmark this page | [
{
"code": null,
"e": 2569,
"s": 2269,
"text": "Routing is the process of directing an HTTP request to a controller and the functionality of this processing is implemented in System.Web.Routing. This assembly is not part of ASP.NET MVC. It is actually part of the ASP.NET runtime, and it was officially released with the ASP.NET as a .NET 3.5 SP1."
},
{
"code": null,
"e": 2844,
"s": 2569,
"text": "System.Web.Routing is used by the MVC framework, but it's also used by ASP.NET Dynamic Data. The MVC framework leverages routing to direct a request to a controller. The Global.asax file is that part of your application, where you will define the route for your application."
},
{
"code": null,
"e": 2968,
"s": 2844,
"text": "This is the code from the application start event in Global.asax from the MVC App which we created in the previous chapter."
},
{
"code": null,
"e": 3348,
"s": 2968,
"text": "using System;\nusing System.Collections.Generic;\nusing System.Linq;\n\nusing System.Web;\nusing System.Web.Mvc;\nusing System.Web.Routing;\n\nnamespace MVCFirstApp {\n public class MvcApplication : System.Web.HttpApplication {\n protected void Application_Start(){\n AreaRegistration.RegisterAllAreas();\n RouteConfig.RegisterRoutes(RouteTable.Routes);\n }\n }\n}"
},
{
"code": null,
"e": 3444,
"s": 3348,
"text": "Following is the implementation of RouteConfig class, which contains one method RegisterRoutes."
},
{
"code": null,
"e": 3970,
"s": 3444,
"text": "using System;\nusing System.Collections.Generic;\nusing System.Linq;\n\nusing System.Web;\nusing System.Web.Mvc;\nusing System.Web.Routing;\n\nnamespace MVCFirstApp {\n public class RouteConfig {\n public static void RegisterRoutes(RouteCollection routes){\n routes.IgnoreRoute(\"{resource}.axd/{*pathInfo}\");\n routes.MapRoute(\n name: \"Default\",\n url: \"{controller}/{action}/{id}\",\n defaults: new{ controller = \"Home\", action = \"Index\", id = UrlParameter.Optional});\n }\n }\n}"
},
{
"code": null,
"e": 4196,
"s": 3970,
"text": "You will define the routes and those routes will map URLs to a specific controller action. An action is just a method on the controller. It can also pick parameters out of that URL and pass them as parameters into the method."
},
{
"code": null,
"e": 4490,
"s": 4196,
"text": "So this route that is defined in the application is the default route. As seen in the above code, when you see a URL arrive in the form of (something)/(something)/(something), then the first piece is the controller name, second piece is the action name, and the third piece is an ID parameter."
},
{
"code": null,
"e": 4594,
"s": 4490,
"text": "MVC applications use the ASP.NET routing system, which decides how URLs map to controllers and actions."
},
{
"code": null,
"e": 4955,
"s": 4594,
"text": "When Visual Studio creates the MVC project, it adds some default routes to get us started. When you run your application, you will see that Visual Studio has directed the browser to port 63664. You will almost certainly see a different port number in the URL that your browser requests because Visual Studio allocates a random port when the project is created."
},
{
"code": null,
"e": 5128,
"s": 4955,
"text": "In the last example, we have added a HomeController, so you can also request any of the following URLs, and they will be directed to the Index action on the HomeController."
},
{
"code": null,
"e": 5157,
"s": 5128,
"text": "http://localhost:63664/Home/"
},
{
"code": null,
"e": 5191,
"s": 5157,
"text": "http://localhost:63664/Home/Index"
},
{
"code": null,
"e": 5313,
"s": 5191,
"text": "When a browser requests http://mysite/ or http://mysite/Home, it gets back the output from HomeController’s Index method."
},
{
"code": null,
"e": 5463,
"s": 5313,
"text": "You can try this as well by changing the URL in the browser. In this example, it is http://localhost:63664/, except that the port might be different."
},
{
"code": null,
"e": 5590,
"s": 5463,
"text": "If you append /Home or /Home/Index to the URL and press ‘Enter’ button, you will see the same result from the MVC application."
},
{
"code": null,
"e": 5761,
"s": 5590,
"text": "As you can see in this case, the convention is that we have a controller called HomeController and this HomeController will be the starting point for our MVC application."
},
{
"code": null,
"e": 5959,
"s": 5761,
"text": "The default routes that Visual Studio creates for a new project assumes that you will follow this convention. But if you want to follow your own convention then you would need to modify the routes."
},
{
"code": null,
"e": 6185,
"s": 5959,
"text": "You can certainly add your own routes. If you don't like these action names, if you have different ID parameters or if you just in general have a different URL structure for your site, then you can add your own route entries."
},
{
"code": null,
"e": 6346,
"s": 6185,
"text": "Let’s take a look at a simple example. Consider we have a page that contains the list of processes. Following is the code, which will route to the process page."
},
{
"code": null,
"e": 6502,
"s": 6346,
"text": "routes.MapRoute(\n \"Process\",\n \"Process/{action}/{id}\",\n defaults: new{\n controller = \"Process\", action = \"List \", id = UrlParameter.Optional}\n);"
},
{
"code": null,
"e": 6717,
"s": 6502,
"text": "When someone comes in and looks for a URL with Process/Action/Id, they will go to the Process Controller. We can make the action a little bit different, the default action, we can make that a List instead of Index."
},
{
"code": null,
"e": 6897,
"s": 6717,
"text": "Now a request that arrives looks like localhosts/process. The routing engine will use this routing configuration to pass that along, so it's going to use a default action of List."
},
{
"code": null,
"e": 6945,
"s": 6897,
"text": "Following is the complete class implementation."
},
{
"code": null,
"e": 7701,
"s": 6945,
"text": "using System;\nusing System.Collections.Generic;\nusing System.Linq;\n\nusing System.Web;\nusing System.Web.Mvc;\nusing System.Web.Routing;\n\nnamespace MVCFirstApp{\n public class RouteConfig{\n public static void RegisterRoutes(RouteCollection routes){\n routes.IgnoreRoute(\"{resource}.axd/{*pathInfo}\");\n\t\t\t\n routes.MapRoute(\n \"Process\", \"Process/{action}/{id}\",\n defaults: new{\n controller = \" Process\", action = \"List \", id =\n UrlParameter.Optional});\n\t\t\t\t\t\n routes.MapRoute(\n name: \"Default\", url: \"{controller}/{action}/{id}\",\n defaults: new{\n controller = \"Home\", action = \"Index\", id =\n UrlParameter.Optional});\n }\n }\n}"
},
{
"code": null,
"e": 7804,
"s": 7701,
"text": "Step 1 − Run this and request for a process page with the following URL http://localhost:63664/Process"
},
{
"code": null,
"e": 7915,
"s": 7804,
"text": "You will see an HTTP 404, because the routing engine is looking for ProcessController, which is not available."
},
{
"code": null,
"e": 8043,
"s": 7915,
"text": "Step 2 − Create ProcessController by right-clicking on Controllers folder in the solution explorer and select Add → Controller."
},
{
"code": null,
"e": 8084,
"s": 8043,
"text": "It will display the Add Scaffold dialog."
},
{
"code": null,
"e": 8160,
"s": 8084,
"text": "Step 3 − Select the MVC 5 Controller – Empty option and click ‘Add’ button."
},
{
"code": null,
"e": 8199,
"s": 8160,
"text": "The Add Controller dialog will appear."
},
{
"code": null,
"e": 8266,
"s": 8199,
"text": "Step 4 − Set the name to ProcessController and click ‘Add’ button."
},
{
"code": null,
"e": 8397,
"s": 8266,
"text": "Now you will see a new C# file ProcessController.cs in the Controllers folder, which is open for editing in Visual Studio as well."
},
{
"code": null,
"e": 8497,
"s": 8397,
"text": "Now our default action is going to be List, so we want to have a List action here instead of Index."
},
{
"code": null,
"e": 8635,
"s": 8497,
"text": "Step 5 − Change the return type from ActionResult to string and also return some string from this action method using the following code."
},
{
"code": null,
"e": 8932,
"s": 8635,
"text": "using System;\nusing System.Collections.Generic;\nusing System.Linq;\n\nusing System.Web;\nusing System.Web.Mvc;\n\nnamespace MVCFirstApp.Controllers{\n public class ProcessController : Controller{\n // GET: Process\n public string List(){\n return \"This is Process page\";\n }\n }\n}"
},
{
"code": null,
"e": 9156,
"s": 8932,
"text": "Step 6 − When you run this application, again you will see the result from the default route. When you specify the following URL, http://localhost:63664/Process/List, then you will see the result from the ProcessController."
},
{
"code": null,
"e": 9191,
"s": 9156,
"text": "\n 51 Lectures \n 5.5 hours \n"
},
{
"code": null,
"e": 9205,
"s": 9191,
"text": " Anadi Sharma"
},
{
"code": null,
"e": 9240,
"s": 9205,
"text": "\n 44 Lectures \n 4.5 hours \n"
},
{
"code": null,
"e": 9263,
"s": 9240,
"text": " Kaushik Roy Chowdhury"
},
{
"code": null,
"e": 9297,
"s": 9263,
"text": "\n 42 Lectures \n 18 hours \n"
},
{
"code": null,
"e": 9317,
"s": 9297,
"text": " SHIVPRASAD KOIRALA"
},
{
"code": null,
"e": 9352,
"s": 9317,
"text": "\n 57 Lectures \n 3.5 hours \n"
},
{
"code": null,
"e": 9369,
"s": 9352,
"text": " University Code"
},
{
"code": null,
"e": 9404,
"s": 9369,
"text": "\n 40 Lectures \n 2.5 hours \n"
},
{
"code": null,
"e": 9421,
"s": 9404,
"text": " University Code"
},
{
"code": null,
"e": 9455,
"s": 9421,
"text": "\n 138 Lectures \n 9 hours \n"
},
{
"code": null,
"e": 9470,
"s": 9455,
"text": " Bhrugen Patel"
},
{
"code": null,
"e": 9477,
"s": 9470,
"text": " Print"
},
{
"code": null,
"e": 9488,
"s": 9477,
"text": " Add Notes"
}
] |
Capsule Neural Networks – Part 2: What is a Capsule? | by Tomer Eldor | Towards Data Science | This is the second part of a Capsule Networks explanation series. Post #1 is here, check it out if you haven’t yet.
In classic CNNs, each neuron in the first layer represents a pixel. Then, it feeds this information forward to next layers. The next convolutional layers group a bunch of neurons together, so that a single neuron there can represent a whole frame (bunch) of neurons. Thus, it can learn to represent a group of pixels that look something like a snout, especially if we have many examples of those in our dataset, and the neural net will learn to increase the weight (importance) of that snout neuron feature when identifying if that image is of a dog.
However, this method solely cares about the existence of the object in the picture around a specific location; but it is insensitive to the spatial relations and direction of the object. But fear not! Capsules are here to the rescue! Capsules are a new concept which can contains more information about each “object”. Capsules are a vector (an element with size and direction) specifying the features of the object and its likelihood. These features can be any of the instantiation parameters like “pose” (position, size, orientation), deformation, velocity, albedo (light reflection), hue, texture, etc.
So, for example, a neural network can learn to have one capsule representing “eye”, which will contain information about all the eye variations it has seen, rather than different neurons for different eye variations. For example, beyond the information about an “eye” looking group of pixel, a capsule can also specify its attributes like angle and size, so that it can represent with the same generic eye information various eyes if we play around with those angle or size parameters.
Now, just like a neural network has layers of neurons, a capsule network can have layers of capsules. So there could be higher capsules representing the group of objects (capsules) below them. For example, in layer 3 you might have capsules which represent “eye”, “snout”, “mouth”, and in layer 4 you might have a capsule representing “dog face”. So the capsule is more flexible and robust in identifying those features across a range of variations.
But wait... there’s more!
Our smart capsule can utilize that information for better identification. Intuitively, the capsule network can ask: are all of these features similarly rotated and sized? If not, this image in question is less likely to be a dog face (this label will get a lower probability score). If yes, that increases our confidence, which has a big meaning: we just created a network which can identify objects even if they are transformed from its original input. Let’s talk about these two points in more details. (1) CapsNets can classify better based on inconsistencies in orientation and size for identification. If the sub-elements (nose, eyes, and mouth) are inconsistent in their orientation and size with one another (such as our Picasso!), then the higher capsules will notice and will be less certain that it is a (conventional) dog face . We couldn’t do that with normal neurons in CNNs; we only had the likelihood of having a group of pixel look like something without information about its directions. By comparing the compatibility of each feature of the capsule we can detect that they are inconsistent, and (sadly) rule out Picasso from being our regular Pitbull-mix. (2) Viewpoint invariance. A classic CNN can only recognize a dog face based on a similar dog face detector stored with similar orientation and size. This is because the features of the dog face are stored in locations inside pixel frame. For example, it might have a representation of a dog face where the snout is around pixels [50,50], the mouth around [50,20], and the eyes around [20,70] and [70,70]. Then, it would only recognize images that have similar features in similar locations in the picture. Therefore, it must have a separate representation for a “dog face rotated by 30o” , or “small dog face”. Those representations would eventually map to the same class, but it still means the CNN must previously see enough examples of each type of transformation to create an internal representation of it and recognize it in the future. In contrast, a capsule network can have a general representation of a “dog face”, and check what is the transformation (rotation, size, etc) of each of its features (snout, mouth, etc). It checks if all the features are rotated or transformed at the same amount and direction and thus be more confident that it is indeed a dog face. The neural net can directly detect that this collection of substructures is really equivalent to the higher-structure transformed by that same amount. This means that CapsNets generalize the class rather than memorizing every viewpoint variant of the class, so it is invariant to the viewpoint.
This is great news! Why? Because being viewpoint invariant means that: (a) It is more robust to changes in the orientation and size of the input (b) It would need much less data (which is often hard to get) and internal representations, thus more efficient, to classify correctly. This means that (c) CapsNets can identify new, unseen variations of the class without ever being trained on them!
Conceptually, this is such great news because this is much more like what we humans do in our vision, and thus an important improvement. Rather then memorizing a face to be when the nose is at 1.70m and mouth at 1.67m, we store the relations between mouth and nose and can thus detect them in any variation. Hinton calls this equivariance of capsules. Equivariance is the detection of a class of objects which can transform to each other (i.e., by rotation, shift, or whatever transformation). Beyond recognizing just the object itself and its transformation, CapsNet equivariance means that they also detect in what state of transformation is the object in right now. We force the model to learn feature variants into one capsule, so that we may extrapolate possible variants more effectively with less training data. So when the object is moved, tilted, or differently sized, but IS the same underlying object, the Capsule will still detect this object with high probability. This is possible because the capsule contains information about an object in a vector with the length as the probability, so the length will not change if the object is transformed, but its direction towards the dimensions of transformation it represents will change. This more robust representation of objects may make it also more robust against adversarial attacks. Briefly, Adversarial Attacks are a method to “fool” a neural network to determine that an object [dog] is actually another thing [Trump] by tweaking the pixels in the image in an almost undetectable manner to the human eye, but just enough in the directions which represent another object by the neural net, until the network thinks it is that other object. Having a more generalized, wholesome and robust representation of that object, specifically with viewpoint invariance and resilience to modifications of the object - can help the network keep recognizing it is the same object and thus mitigates these attacks.
This is important for the when neural networks image recognition determines real-life events: like self-driving cars detecting [STOP] signs. A (well educated) criminal could tape an almost invisible sticker on that sign and “hack” the car to recognize this sign as a [“Speed = 60”] sign and keep driving. But a system based on CapsNets rather than CNN would be more much more resilient against such adversarial attacks. I tested the model against a common adversarial attack “FGSM”, and it degraded down to 73% accuracy at the level of noise = 50. It is then not resistant but performed better than normal CNNs.
You got the general idea.
Now let’s get down to the details.
A capsule is an abstract idea of having a group of neurons with an activity vector that contains more information about the object. There are many ways to implement this. Hinton et al chose one particular way to implement this, which allows using “dynamic routing”. We will discuss this implementation here. Sabour, Frosst & Hinton (2017) open their paper with this definition and overview:
“A capsule is a group of neurons whose activity vector represents the instantiation parameters of a specific type of entity such as an object or an object part. We use the length of the activity vector to represent the probability that the entity exists and its orientation to represent the instantiation parameters. Active capsules at one level make predictions, via transformation matrices, for the instantiation parameters of higher-level capsules. When multiple predictions agree, a higher level capsule becomes active.”
In their paper and all available implementations, Capsule networks were used on the MNIST hand-written 0–9 digits dataset — the classic ML classification task. Let’s move to that example now.
Each capsule is a group of neurons.
In the DigitCaps layer, each neuron represents a dimension in which the digit could be different: Scale and thickness, Stroke thickness, Skew, Width, Translation, etc. The authors used 16 neurons in each capsule to represent 16 dimensions in which one digit can be different.
The thing that we most care to get from the Capsule is its output.The output of a capsule is a vector. The length of the vector itself expresses the “existence of the entity” — meaning the probability of this object being [5]. The direction of the vector is forced to represent the properties themselves (width, thickness, skew...). Its size is forced to be under 1 (being size it's always positive, so between 0-1) and represent the probability of being that class. It points to a point that represents how big it is and what is its angle. Let's sketch out a simple example. Before, we had a neuron receive a single scalar representing a subobject and outputting a single scalar. Let's say that we have some “5” digit neurons close to the end of a CNN, receiving a scalar that came from a particular kind of 5:
Now, we can encode some more information if instead of one neuron we have a single capsule with 2 neurons, indicating also the angle of the digit. The length of the vector itself represents how likely this input is to be this 5 the capsule is representing; the same probability information as the single neuron outputted.
The length is calculated as the size of the vector. If the first vector is v=(0,0.9), its length is = sqrt√(0^2 + 0.9^2) = 0.9. Now we could add more neurons to a capsule to capture more dimensions: Scale and thickness, Width, Stroke thickness, Skew, etc. Hinton et al (2017) show the results of various dimensions in their DigitCaps layer capsules trained on MNIST dataset in their paper, which contained these dimensions:
The capsule learns the right transformations and to optimize its outputs. How does that work? First, let’s recall what a trattditional neuron does in a CNN:
Receives Scalars as inputs (X1, X2, X3), with additional constant (1) to represent a bias weightPerforms a weighted sum of the input scalars (by weights w1, w2, w3, and b which are scalars)Applies a nonlinearity activation function f(•)Outputs a scalar h (depending on its learned parameters of weights w,b.
Receives Scalars as inputs (X1, X2, X3), with additional constant (1) to represent a bias weight
Performs a weighted sum of the input scalars (by weights w1, w2, w3, and b which are scalars)
Applies a nonlinearity activation function f(•)
Outputs a scalar h (depending on its learned parameters of weights w,b.
Out very own capsule operates in a similar manner but with important differences.
1. INPUTTED a VECTOR (u_i). Whereas traditional neurons receive a single scalar as input and output a single scalar, capsules recieve an input vector and they output a vector. These input vectors u1, u2, u3 came out from capsules in the layer before. Let’s say they represent eyes, nose/snout and dog_mouth. Their lengths represent the probability of them correctly recognizing what they received. Their directions represent the variation / state of the underlying object in the dimension space of the capsule.
Notice that the first layer of capsules will not have the same input since it was not produced by other capsules. This will be discussed later.
Notice also that there is no bias as input. The bias may be contained in the next phase “affine transformation” with the transformation matrix Wij, which can contain this bias and more complex operations.
2. AFFINE TRANSFORMATION.
This step is unique to capsules. It applies a transformation matrix Wij to the vectors u1/u2/u3 of the pervious layer. For example, assuming we start with a matrix of size m×k and an input vector ui of size (k, D), we transform that vector to a new matrix û ji with size (m,D). ((m×k) × (k×1) ⟹ m×1).
This transformation matrix is important; it could represent the missing spatial relationships and other relationships between the inputted sub-objects (dog’s nose, dog’s right eye) and the outputted higher-level object (dog face). For example, one of the matrices W1j could represent the information that the right eye is in the right top part of the dog face, the dog face should be about 20 times bigger, and the angle of the face should be the same as the angle of the eye. This matrix aims to transform the input vector into the position of the predicted output vector representing the next level — the face (higher level feature). After this matrix multiplication, we get a predicted position of the face. This happens from each vector. So u1 represented the predicted position of the dog face according to the eye, u2 represented the predicted position of the dog face according to the snout, u1 represented the predicted position of the dog face according to the mouth. This way, we could overlay these predictions and see if they correlate or interfere. If they all predict there should be a dog in the same spot, we have more certainty in our prediction for dog_face. Example of what overlaying the predictions for a dog_face based on each input:
3. WEIGHTED SUM (Sums C_ij) OF INPUT VECTORS U^j|i
C_ij are “coupling coefficients” which we find using the dynamic routing algorithm (which will be explained next). Their weighted sum ∑cij are designed to sum to one. A short intuition for the dynamic routing, for now, is that it is a way for a capsule to “decide” where to send its output. It does so by projecting where out its transformation would land in space if it were to go with this capsule. We do with from all capsules to all capsules, so for each next capsule, we have a space full of hypothetical points from the previous layer’s capsules. This capsule will go where its projection lands closer to a cluster of other points from other capsules.
So the [snout capsule] (lower level) can project which higher level capsule would have more agreement with its projections — (between the face capsule, torso capsule, legs capsule; the projections of the snout would be closer to the projections onto the face capsule). Thus, it will optimize its C_ij weights based on this fit, maximizing for fit with face_capsule and minimizing fit with legs_capsule.
4. “SQUASHING FUNCTION”: An new Nonlinear Activation Function for vectors
Traditionally, layers of neurons map into different layers of a nonlinearity “activation” function, which is most commonly ReLU (as simple as f(x)=max(0,x), which only eliminates all the negative values into 0).Capsule Networks need to convert from vectors to vector, and Hinton’s design necessitates the output vector’s length to be between 0–1 (or more precisely, 0 — unit length) to still represent probability. However, it must preserve its direction. How can it ensure that? They created a new kind of activation function called “squashing” function. It shrinks vectors to 1 or below while preserving their direction. Specifically, it shrinks long vectors above ~3–4 to around 1 (unit vector size), and vectors smaller than 1 are drastically downsized (by the left part of the equation, where they are squared and divided by themselves + 1. Note that this vector’s size represents the probability of the object to belong to this capsule.(For example, for ||Sj||=1 this part would be 1/2=0.5 but for a vector sized ||0.1||, 0.1/1.1 = 0.09091The squashing function can be computed as (from gram-ai’s PyTorch implementation which we will go through later):
Traditionally, layers of neurons map into different layers of a nonlinearity “activation” function, which is most commonly ReLU (as simple as f(x)=max(0,x), which only eliminates all the negative values into 0).
Capsule Networks need to convert from vectors to vector, and Hinton’s design necessitates the output vector’s length to be between 0–1 (or more precisely, 0 — unit length) to still represent probability. However, it must preserve its direction. How can it ensure that? They created a new kind of activation function called “squashing” function. It shrinks vectors to 1 or below while preserving their direction. Specifically, it shrinks long vectors above ~3–4 to around 1 (unit vector size), and vectors smaller than 1 are drastically downsized (by the left part of the equation, where they are squared and divided by themselves + 1. Note that this vector’s size represents the probability of the object to belong to this capsule.
(For example, for ||Sj||=1 this part would be 1/2=0.5 but for a vector sized ||0.1||, 0.1/1.1 = 0.09091
The squashing function can be computed as (from gram-ai’s PyTorch implementation which we will go through later):
# squashing function as we’ve seen beforedef squash(self, tensor, dim=-1): squared_norm = (tensor ** 2).sum(dim=dim, keepdim=True) scale = squared_norm / (1 + squared_norm) return scale * tensor / torch.sqrt(squared_norm)
OUTPUT: The resulting Vector. The finished product.
OUTPUT: The resulting Vector. The finished product.
In summary, the inner working of a capsule was:
Receiving an input vector (representing eye)Applying “affine transformation” or transformation matrix encoding spatial relationships (between eye and dog_face, projecting where should the face be)applying weighted sum by the C weights, learned by the routing algorithm“squashing” it to 0–1 with the nonlinear “squashing” activation functionGot our new vector, ready to be sent onwards.
Receiving an input vector (representing eye)
Applying “affine transformation” or transformation matrix encoding spatial relationships (between eye and dog_face, projecting where should the face be)
applying weighted sum by the C weights, learned by the routing algorithm
“squashing” it to 0–1 with the nonlinear “squashing” activation function
Got our new vector, ready to be sent onwards.
A summary of key differences between a normal ‘neuron’ and a capsule is well presented in this table from Naturomics:
Congratulations. If you made it all the way here (even if skimming some of the technical parts), you know pretty much all you need to know about “capsules”!
But still we need to know: what do you do with these capsules? how do you connect them into a neural network? Next post will explain the algorithm and architecture that routes information between capsules dynamically.
If you’d like to see the next post and more coming out in the future, clap!
Until next time, | [
{
"code": null,
"e": 287,
"s": 171,
"text": "This is the second part of a Capsule Networks explanation series. Post #1 is here, check it out if you haven’t yet."
},
{
"code": null,
"e": 838,
"s": 287,
"text": "In classic CNNs, each neuron in the first layer represents a pixel. Then, it feeds this information forward to next layers. The next convolutional layers group a bunch of neurons together, so that a single neuron there can represent a whole frame (bunch) of neurons. Thus, it can learn to represent a group of pixels that look something like a snout, especially if we have many examples of those in our dataset, and the neural net will learn to increase the weight (importance) of that snout neuron feature when identifying if that image is of a dog."
},
{
"code": null,
"e": 1444,
"s": 838,
"text": "However, this method solely cares about the existence of the object in the picture around a specific location; but it is insensitive to the spatial relations and direction of the object. But fear not! Capsules are here to the rescue! Capsules are a new concept which can contains more information about each “object”. Capsules are a vector (an element with size and direction) specifying the features of the object and its likelihood. These features can be any of the instantiation parameters like “pose” (position, size, orientation), deformation, velocity, albedo (light reflection), hue, texture, etc."
},
{
"code": null,
"e": 1930,
"s": 1444,
"text": "So, for example, a neural network can learn to have one capsule representing “eye”, which will contain information about all the eye variations it has seen, rather than different neurons for different eye variations. For example, beyond the information about an “eye” looking group of pixel, a capsule can also specify its attributes like angle and size, so that it can represent with the same generic eye information various eyes if we play around with those angle or size parameters."
},
{
"code": null,
"e": 2380,
"s": 1930,
"text": "Now, just like a neural network has layers of neurons, a capsule network can have layers of capsules. So there could be higher capsules representing the group of objects (capsules) below them. For example, in layer 3 you might have capsules which represent “eye”, “snout”, “mouth”, and in layer 4 you might have a capsule representing “dog face”. So the capsule is more flexible and robust in identifying those features across a range of variations."
},
{
"code": null,
"e": 2406,
"s": 2380,
"text": "But wait... there’s more!"
},
{
"code": null,
"e": 5052,
"s": 2406,
"text": "Our smart capsule can utilize that information for better identification. Intuitively, the capsule network can ask: are all of these features similarly rotated and sized? If not, this image in question is less likely to be a dog face (this label will get a lower probability score). If yes, that increases our confidence, which has a big meaning: we just created a network which can identify objects even if they are transformed from its original input. Let’s talk about these two points in more details. (1) CapsNets can classify better based on inconsistencies in orientation and size for identification. If the sub-elements (nose, eyes, and mouth) are inconsistent in their orientation and size with one another (such as our Picasso!), then the higher capsules will notice and will be less certain that it is a (conventional) dog face . We couldn’t do that with normal neurons in CNNs; we only had the likelihood of having a group of pixel look like something without information about its directions. By comparing the compatibility of each feature of the capsule we can detect that they are inconsistent, and (sadly) rule out Picasso from being our regular Pitbull-mix. (2) Viewpoint invariance. A classic CNN can only recognize a dog face based on a similar dog face detector stored with similar orientation and size. This is because the features of the dog face are stored in locations inside pixel frame. For example, it might have a representation of a dog face where the snout is around pixels [50,50], the mouth around [50,20], and the eyes around [20,70] and [70,70]. Then, it would only recognize images that have similar features in similar locations in the picture. Therefore, it must have a separate representation for a “dog face rotated by 30o” , or “small dog face”. Those representations would eventually map to the same class, but it still means the CNN must previously see enough examples of each type of transformation to create an internal representation of it and recognize it in the future. In contrast, a capsule network can have a general representation of a “dog face”, and check what is the transformation (rotation, size, etc) of each of its features (snout, mouth, etc). It checks if all the features are rotated or transformed at the same amount and direction and thus be more confident that it is indeed a dog face. The neural net can directly detect that this collection of substructures is really equivalent to the higher-structure transformed by that same amount. This means that CapsNets generalize the class rather than memorizing every viewpoint variant of the class, so it is invariant to the viewpoint."
},
{
"code": null,
"e": 5447,
"s": 5052,
"text": "This is great news! Why? Because being viewpoint invariant means that: (a) It is more robust to changes in the orientation and size of the input (b) It would need much less data (which is often hard to get) and internal representations, thus more efficient, to classify correctly. This means that (c) CapsNets can identify new, unseen variations of the class without ever being trained on them!"
},
{
"code": null,
"e": 7414,
"s": 5447,
"text": "Conceptually, this is such great news because this is much more like what we humans do in our vision, and thus an important improvement. Rather then memorizing a face to be when the nose is at 1.70m and mouth at 1.67m, we store the relations between mouth and nose and can thus detect them in any variation. Hinton calls this equivariance of capsules. Equivariance is the detection of a class of objects which can transform to each other (i.e., by rotation, shift, or whatever transformation). Beyond recognizing just the object itself and its transformation, CapsNet equivariance means that they also detect in what state of transformation is the object in right now. We force the model to learn feature variants into one capsule, so that we may extrapolate possible variants more effectively with less training data. So when the object is moved, tilted, or differently sized, but IS the same underlying object, the Capsule will still detect this object with high probability. This is possible because the capsule contains information about an object in a vector with the length as the probability, so the length will not change if the object is transformed, but its direction towards the dimensions of transformation it represents will change. This more robust representation of objects may make it also more robust against adversarial attacks. Briefly, Adversarial Attacks are a method to “fool” a neural network to determine that an object [dog] is actually another thing [Trump] by tweaking the pixels in the image in an almost undetectable manner to the human eye, but just enough in the directions which represent another object by the neural net, until the network thinks it is that other object. Having a more generalized, wholesome and robust representation of that object, specifically with viewpoint invariance and resilience to modifications of the object - can help the network keep recognizing it is the same object and thus mitigates these attacks."
},
{
"code": null,
"e": 8027,
"s": 7414,
"text": "This is important for the when neural networks image recognition determines real-life events: like self-driving cars detecting [STOP] signs. A (well educated) criminal could tape an almost invisible sticker on that sign and “hack” the car to recognize this sign as a [“Speed = 60”] sign and keep driving. But a system based on CapsNets rather than CNN would be more much more resilient against such adversarial attacks. I tested the model against a common adversarial attack “FGSM”, and it degraded down to 73% accuracy at the level of noise = 50. It is then not resistant but performed better than normal CNNs."
},
{
"code": null,
"e": 8053,
"s": 8027,
"text": "You got the general idea."
},
{
"code": null,
"e": 8088,
"s": 8053,
"text": "Now let’s get down to the details."
},
{
"code": null,
"e": 8479,
"s": 8088,
"text": "A capsule is an abstract idea of having a group of neurons with an activity vector that contains more information about the object. There are many ways to implement this. Hinton et al chose one particular way to implement this, which allows using “dynamic routing”. We will discuss this implementation here. Sabour, Frosst & Hinton (2017) open their paper with this definition and overview:"
},
{
"code": null,
"e": 9004,
"s": 8479,
"text": "“A capsule is a group of neurons whose activity vector represents the instantiation parameters of a specific type of entity such as an object or an object part. We use the length of the activity vector to represent the probability that the entity exists and its orientation to represent the instantiation parameters. Active capsules at one level make predictions, via transformation matrices, for the instantiation parameters of higher-level capsules. When multiple predictions agree, a higher level capsule becomes active.”"
},
{
"code": null,
"e": 9196,
"s": 9004,
"text": "In their paper and all available implementations, Capsule networks were used on the MNIST hand-written 0–9 digits dataset — the classic ML classification task. Let’s move to that example now."
},
{
"code": null,
"e": 9232,
"s": 9196,
"text": "Each capsule is a group of neurons."
},
{
"code": null,
"e": 9508,
"s": 9232,
"text": "In the DigitCaps layer, each neuron represents a dimension in which the digit could be different: Scale and thickness, Stroke thickness, Skew, Width, Translation, etc. The authors used 16 neurons in each capsule to represent 16 dimensions in which one digit can be different."
},
{
"code": null,
"e": 10322,
"s": 9508,
"text": "The thing that we most care to get from the Capsule is its output.The output of a capsule is a vector. The length of the vector itself expresses the “existence of the entity” — meaning the probability of this object being [5]. The direction of the vector is forced to represent the properties themselves (width, thickness, skew...). Its size is forced to be under 1 (being size it's always positive, so between 0-1) and represent the probability of being that class. It points to a point that represents how big it is and what is its angle. Let's sketch out a simple example. Before, we had a neuron receive a single scalar representing a subobject and outputting a single scalar. Let's say that we have some “5” digit neurons close to the end of a CNN, receiving a scalar that came from a particular kind of 5:"
},
{
"code": null,
"e": 10644,
"s": 10322,
"text": "Now, we can encode some more information if instead of one neuron we have a single capsule with 2 neurons, indicating also the angle of the digit. The length of the vector itself represents how likely this input is to be this 5 the capsule is representing; the same probability information as the single neuron outputted."
},
{
"code": null,
"e": 11069,
"s": 10644,
"text": "The length is calculated as the size of the vector. If the first vector is v=(0,0.9), its length is = sqrt√(0^2 + 0.9^2) = 0.9. Now we could add more neurons to a capsule to capture more dimensions: Scale and thickness, Width, Stroke thickness, Skew, etc. Hinton et al (2017) show the results of various dimensions in their DigitCaps layer capsules trained on MNIST dataset in their paper, which contained these dimensions:"
},
{
"code": null,
"e": 11227,
"s": 11069,
"text": "The capsule learns the right transformations and to optimize its outputs. How does that work? First, let’s recall what a trattditional neuron does in a CNN:"
},
{
"code": null,
"e": 11535,
"s": 11227,
"text": "Receives Scalars as inputs (X1, X2, X3), with additional constant (1) to represent a bias weightPerforms a weighted sum of the input scalars (by weights w1, w2, w3, and b which are scalars)Applies a nonlinearity activation function f(•)Outputs a scalar h (depending on its learned parameters of weights w,b."
},
{
"code": null,
"e": 11632,
"s": 11535,
"text": "Receives Scalars as inputs (X1, X2, X3), with additional constant (1) to represent a bias weight"
},
{
"code": null,
"e": 11726,
"s": 11632,
"text": "Performs a weighted sum of the input scalars (by weights w1, w2, w3, and b which are scalars)"
},
{
"code": null,
"e": 11774,
"s": 11726,
"text": "Applies a nonlinearity activation function f(•)"
},
{
"code": null,
"e": 11846,
"s": 11774,
"text": "Outputs a scalar h (depending on its learned parameters of weights w,b."
},
{
"code": null,
"e": 11928,
"s": 11846,
"text": "Out very own capsule operates in a similar manner but with important differences."
},
{
"code": null,
"e": 12439,
"s": 11928,
"text": "1. INPUTTED a VECTOR (u_i). Whereas traditional neurons receive a single scalar as input and output a single scalar, capsules recieve an input vector and they output a vector. These input vectors u1, u2, u3 came out from capsules in the layer before. Let’s say they represent eyes, nose/snout and dog_mouth. Their lengths represent the probability of them correctly recognizing what they received. Their directions represent the variation / state of the underlying object in the dimension space of the capsule."
},
{
"code": null,
"e": 12583,
"s": 12439,
"text": "Notice that the first layer of capsules will not have the same input since it was not produced by other capsules. This will be discussed later."
},
{
"code": null,
"e": 12788,
"s": 12583,
"text": "Notice also that there is no bias as input. The bias may be contained in the next phase “affine transformation” with the transformation matrix Wij, which can contain this bias and more complex operations."
},
{
"code": null,
"e": 12814,
"s": 12788,
"text": "2. AFFINE TRANSFORMATION."
},
{
"code": null,
"e": 13116,
"s": 12814,
"text": "This step is unique to capsules. It applies a transformation matrix Wij to the vectors u1/u2/u3 of the pervious layer. For example, assuming we start with a matrix of size m×k and an input vector ui of size (k, D), we transform that vector to a new matrix û ji with size (m,D). ((m×k) × (k×1) ⟹ m×1)."
},
{
"code": null,
"e": 14372,
"s": 13116,
"text": "This transformation matrix is important; it could represent the missing spatial relationships and other relationships between the inputted sub-objects (dog’s nose, dog’s right eye) and the outputted higher-level object (dog face). For example, one of the matrices W1j could represent the information that the right eye is in the right top part of the dog face, the dog face should be about 20 times bigger, and the angle of the face should be the same as the angle of the eye. This matrix aims to transform the input vector into the position of the predicted output vector representing the next level — the face (higher level feature). After this matrix multiplication, we get a predicted position of the face. This happens from each vector. So u1 represented the predicted position of the dog face according to the eye, u2 represented the predicted position of the dog face according to the snout, u1 represented the predicted position of the dog face according to the mouth. This way, we could overlay these predictions and see if they correlate or interfere. If they all predict there should be a dog in the same spot, we have more certainty in our prediction for dog_face. Example of what overlaying the predictions for a dog_face based on each input:"
},
{
"code": null,
"e": 14423,
"s": 14372,
"text": "3. WEIGHTED SUM (Sums C_ij) OF INPUT VECTORS U^j|i"
},
{
"code": null,
"e": 15081,
"s": 14423,
"text": "C_ij are “coupling coefficients” which we find using the dynamic routing algorithm (which will be explained next). Their weighted sum ∑cij are designed to sum to one. A short intuition for the dynamic routing, for now, is that it is a way for a capsule to “decide” where to send its output. It does so by projecting where out its transformation would land in space if it were to go with this capsule. We do with from all capsules to all capsules, so for each next capsule, we have a space full of hypothetical points from the previous layer’s capsules. This capsule will go where its projection lands closer to a cluster of other points from other capsules."
},
{
"code": null,
"e": 15484,
"s": 15081,
"text": "So the [snout capsule] (lower level) can project which higher level capsule would have more agreement with its projections — (between the face capsule, torso capsule, legs capsule; the projections of the snout would be closer to the projections onto the face capsule). Thus, it will optimize its C_ij weights based on this fit, maximizing for fit with face_capsule and minimizing fit with legs_capsule."
},
{
"code": null,
"e": 15558,
"s": 15484,
"text": "4. “SQUASHING FUNCTION”: An new Nonlinear Activation Function for vectors"
},
{
"code": null,
"e": 16717,
"s": 15558,
"text": "Traditionally, layers of neurons map into different layers of a nonlinearity “activation” function, which is most commonly ReLU (as simple as f(x)=max(0,x), which only eliminates all the negative values into 0).Capsule Networks need to convert from vectors to vector, and Hinton’s design necessitates the output vector’s length to be between 0–1 (or more precisely, 0 — unit length) to still represent probability. However, it must preserve its direction. How can it ensure that? They created a new kind of activation function called “squashing” function. It shrinks vectors to 1 or below while preserving their direction. Specifically, it shrinks long vectors above ~3–4 to around 1 (unit vector size), and vectors smaller than 1 are drastically downsized (by the left part of the equation, where they are squared and divided by themselves + 1. Note that this vector’s size represents the probability of the object to belong to this capsule.(For example, for ||Sj||=1 this part would be 1/2=0.5 but for a vector sized ||0.1||, 0.1/1.1 = 0.09091The squashing function can be computed as (from gram-ai’s PyTorch implementation which we will go through later):"
},
{
"code": null,
"e": 16929,
"s": 16717,
"text": "Traditionally, layers of neurons map into different layers of a nonlinearity “activation” function, which is most commonly ReLU (as simple as f(x)=max(0,x), which only eliminates all the negative values into 0)."
},
{
"code": null,
"e": 17661,
"s": 16929,
"text": "Capsule Networks need to convert from vectors to vector, and Hinton’s design necessitates the output vector’s length to be between 0–1 (or more precisely, 0 — unit length) to still represent probability. However, it must preserve its direction. How can it ensure that? They created a new kind of activation function called “squashing” function. It shrinks vectors to 1 or below while preserving their direction. Specifically, it shrinks long vectors above ~3–4 to around 1 (unit vector size), and vectors smaller than 1 are drastically downsized (by the left part of the equation, where they are squared and divided by themselves + 1. Note that this vector’s size represents the probability of the object to belong to this capsule."
},
{
"code": null,
"e": 17765,
"s": 17661,
"text": "(For example, for ||Sj||=1 this part would be 1/2=0.5 but for a vector sized ||0.1||, 0.1/1.1 = 0.09091"
},
{
"code": null,
"e": 17879,
"s": 17765,
"text": "The squashing function can be computed as (from gram-ai’s PyTorch implementation which we will go through later):"
},
{
"code": null,
"e": 18107,
"s": 17879,
"text": "# squashing function as we’ve seen beforedef squash(self, tensor, dim=-1): squared_norm = (tensor ** 2).sum(dim=dim, keepdim=True) scale = squared_norm / (1 + squared_norm) return scale * tensor / torch.sqrt(squared_norm)"
},
{
"code": null,
"e": 18159,
"s": 18107,
"text": "OUTPUT: The resulting Vector. The finished product."
},
{
"code": null,
"e": 18211,
"s": 18159,
"text": "OUTPUT: The resulting Vector. The finished product."
},
{
"code": null,
"e": 18259,
"s": 18211,
"text": "In summary, the inner working of a capsule was:"
},
{
"code": null,
"e": 18645,
"s": 18259,
"text": "Receiving an input vector (representing eye)Applying “affine transformation” or transformation matrix encoding spatial relationships (between eye and dog_face, projecting where should the face be)applying weighted sum by the C weights, learned by the routing algorithm“squashing” it to 0–1 with the nonlinear “squashing” activation functionGot our new vector, ready to be sent onwards."
},
{
"code": null,
"e": 18690,
"s": 18645,
"text": "Receiving an input vector (representing eye)"
},
{
"code": null,
"e": 18843,
"s": 18690,
"text": "Applying “affine transformation” or transformation matrix encoding spatial relationships (between eye and dog_face, projecting where should the face be)"
},
{
"code": null,
"e": 18916,
"s": 18843,
"text": "applying weighted sum by the C weights, learned by the routing algorithm"
},
{
"code": null,
"e": 18989,
"s": 18916,
"text": "“squashing” it to 0–1 with the nonlinear “squashing” activation function"
},
{
"code": null,
"e": 19035,
"s": 18989,
"text": "Got our new vector, ready to be sent onwards."
},
{
"code": null,
"e": 19153,
"s": 19035,
"text": "A summary of key differences between a normal ‘neuron’ and a capsule is well presented in this table from Naturomics:"
},
{
"code": null,
"e": 19310,
"s": 19153,
"text": "Congratulations. If you made it all the way here (even if skimming some of the technical parts), you know pretty much all you need to know about “capsules”!"
},
{
"code": null,
"e": 19528,
"s": 19310,
"text": "But still we need to know: what do you do with these capsules? how do you connect them into a neural network? Next post will explain the algorithm and architecture that routes information between capsules dynamically."
},
{
"code": null,
"e": 19604,
"s": 19528,
"text": "If you’d like to see the next post and more coming out in the future, clap!"
}
] |
How to set different opacity of edgecolor and facecolor of a patch in Matplotlib? | To set different opacity of edge and face color, we can use a color tuple and the 4th index of the tuple could set the opacity value of the colors.
Set the figure size and adjust the padding between and around the subplots.
Create a figure and a set of subplots using subplots() method.
Set different values for edge and face color opacity.
Add a rectangel patch using add_patch() method.
To display the figure, use show() method.
from matplotlib import pyplot as plt, patches
plt.rcParams["figure.figsize"] = [7.50, 3.50]
plt.rcParams["figure.autolayout"] = True
figure, ax = plt.subplots()
edge_color_opacity = 1 # 0<val<1
face_color_opacity = 0.75 # 0<val<1
ax.add_patch(patches.Rectangle((.25, .25), .50, .50,
edgecolor=(1, 0, 0, edge_color_opacity),
facecolor=(0, 1, 0, face_color_opacity),
linewidth=2))
plt.show() | [
{
"code": null,
"e": 1210,
"s": 1062,
"text": "To set different opacity of edge and face color, we can use a color tuple and the 4th index of the tuple could set the opacity value of the colors."
},
{
"code": null,
"e": 1286,
"s": 1210,
"text": "Set the figure size and adjust the padding between and around the subplots."
},
{
"code": null,
"e": 1349,
"s": 1286,
"text": "Create a figure and a set of subplots using subplots() method."
},
{
"code": null,
"e": 1403,
"s": 1349,
"text": "Set different values for edge and face color opacity."
},
{
"code": null,
"e": 1451,
"s": 1403,
"text": "Add a rectangel patch using add_patch() method."
},
{
"code": null,
"e": 1493,
"s": 1451,
"text": "To display the figure, use show() method."
},
{
"code": null,
"e": 1977,
"s": 1493,
"text": "from matplotlib import pyplot as plt, patches\n\nplt.rcParams[\"figure.figsize\"] = [7.50, 3.50]\nplt.rcParams[\"figure.autolayout\"] = True\n\nfigure, ax = plt.subplots()\nedge_color_opacity = 1 # 0<val<1\nface_color_opacity = 0.75 # 0<val<1\n\nax.add_patch(patches.Rectangle((.25, .25), .50, .50,\n edgecolor=(1, 0, 0, edge_color_opacity),\n facecolor=(0, 1, 0, face_color_opacity),\n linewidth=2))\n\nplt.show()"
}
] |
C++ Program to implement Linear Extrapolation | In this tutorial, we will be discussing a program to implement Linear Extrapolation.
Extrapolation is defined as a process in which the required value for a certain function is beyond the lower or the upper limits of the function definition.
In the case of Linear Extrapolation, the value beyond the scope is found using the tangent made on the graph of the function to determine the required value. Linear Extrapolation gives quite accurate results when applied.
#include <bits/stdc++.h>
using namespace std;
//structuring the values of x and y
struct Data {
double x, y;
};
//calculating the linear extrapolation
double calc_extrapolate(Data d[], double x){
double y;
y = d[0].y
+ (x - d[0].x)
/ (d[1].x - d[0].x)
* (d[1].y - d[0].y);
return y;
}
int main(){
Data d[] = { { 1.2, 2.7 }, { 1.4, 3.1 } };
double x = 2.1;
cout << "Value of y (x = 2.1) : " << calc_extrapolate(d, x) << endl;
return 0;
}
Value of y (x = 2.1) : 4.5 | [
{
"code": null,
"e": 1147,
"s": 1062,
"text": "In this tutorial, we will be discussing a program to implement Linear Extrapolation."
},
{
"code": null,
"e": 1304,
"s": 1147,
"text": "Extrapolation is defined as a process in which the required value for a certain function is beyond the lower or the upper limits of the function definition."
},
{
"code": null,
"e": 1526,
"s": 1304,
"text": "In the case of Linear Extrapolation, the value beyond the scope is found using the tangent made on the graph of the function to determine the required value. Linear Extrapolation gives quite accurate results when applied."
},
{
"code": null,
"e": 2008,
"s": 1526,
"text": "#include <bits/stdc++.h>\nusing namespace std;\n//structuring the values of x and y\nstruct Data {\n double x, y;\n};\n//calculating the linear extrapolation\ndouble calc_extrapolate(Data d[], double x){\n double y;\n y = d[0].y\n + (x - d[0].x)\n / (d[1].x - d[0].x)\n * (d[1].y - d[0].y);\n return y;\n}\nint main(){\n Data d[] = { { 1.2, 2.7 }, { 1.4, 3.1 } };\n double x = 2.1;\n cout << \"Value of y (x = 2.1) : \" << calc_extrapolate(d, x) << endl;\n return 0;\n}"
},
{
"code": null,
"e": 2035,
"s": 2008,
"text": "Value of y (x = 2.1) : 4.5"
}
] |
Python - Dictionary Key Value lists combinations - GeeksforGeeks | 01 Aug, 2020
Given dictionary with values as list, extract all the possible combinations, both cross keys and with values.
Input : test_dict = {“Gfg” : [4, 5], “is” : [1, 2], “Best” : [9, 4]}Output : {0: [[‘Gfg’, 4], [‘is’, 1], [‘Best’, 9]], 1: [[‘Gfg’, 4], [‘is’, 1], [‘Best’, 4]], 2: [[‘Gfg’, 4], [‘is’, 2], [‘Best’, 9]], 3: [[‘Gfg’, 4], [‘is’, 2], [‘Best’, 4]], 4: [[‘Gfg’, 5], [‘is’, 1], [‘Best’, 9]], 5: [[‘Gfg’, 5], [‘is’, 1], [‘Best’, 4]], 6: [[‘Gfg’, 5], [‘is’, 2], [‘Best’, 9]], 7: [[‘Gfg’, 5], [‘is’, 2], [‘Best’, 4]]}Explanation : Prints all possible combination of key with values and cross values as well.
Input : test_dict = {“Gfg” : [4], “is” : [1], “Best” : [4]}Output : {0: [[‘Gfg’, 4], [‘is’, 1], [‘Best’, 4]]}Explanation : Prints all possible combination of key with values and cross values as well.
Method #1 : Using product() + zip() + loop
The combination of above functions can be used to solve this problem. In this, we perform the first combination of keys with all values using product() and cross key combinations are performed using zip() and loop.
Python3
# Python3 code to demonstrate working of # Dictionary Key Value lists combinations# Using product() + zip() + loopfrom itertools import product # initializing dictionarytest_dict = {"Gfg" : [4, 5, 7], "is" : [1, 2, 9], "Best" : [9, 4, 2]} # printing original dictionaryprint("The original dictionary is : " + str(test_dict)) temp = list(test_dict.keys()) res = dict()cnt = 0 # making key-value combinations using productfor combs in product (*test_dict.values()): # zip used to perform cross keys combinations. res[cnt] = [[ele, cnt] for ele, cnt in zip(test_dict, combs)] cnt += 1 # printing result print("The computed combinations : " + str(res))
The original dictionary is : {‘Gfg’: [4, 5, 7], ‘is’: [1, 2, 9], ‘Best’: [9, 4, 2]}The computed combinations : {0: [[‘Gfg’, 4], [‘is’, 1], [‘Best’, 9]], 1: [[‘Gfg’, 4], [‘is’, 1], [‘Best’, 4]], 2: [[‘Gfg’, 4], [‘is’, 1], [‘Best’, 2]], 3: [[‘Gfg’, 4], [‘is’, 2], [‘Best’, 9]], 4: [[‘Gfg’, 4], [‘is’, 2], [‘Best’, 4]], 5: [[‘Gfg’, 4], [‘is’, 2], [‘Best’, 2]], 6: [[‘Gfg’, 4], [‘is’, 9], [‘Best’, 9]], 7: [[‘Gfg’, 4], [‘is’, 9], [‘Best’, 4]], 8: [[‘Gfg’, 4], [‘is’, 9], [‘Best’, 2]], 9: [[‘Gfg’, 5], [‘is’, 1], [‘Best’, 9]], 10: [[‘Gfg’, 5], [‘is’, 1], [‘Best’, 4]], 11: [[‘Gfg’, 5], [‘is’, 1], [‘Best’, 2]], 12: [[‘Gfg’, 5], [‘is’, 2], [‘Best’, 9]], 13: [[‘Gfg’, 5], [‘is’, 2], [‘Best’, 4]], 14: [[‘Gfg’, 5], [‘is’, 2], [‘Best’, 2]], 15: [[‘Gfg’, 5], [‘is’, 9], [‘Best’, 9]], 16: [[‘Gfg’, 5], [‘is’, 9], [‘Best’, 4]], 17: [[‘Gfg’, 5], [‘is’, 9], [‘Best’, 2]], 18: [[‘Gfg’, 7], [‘is’, 1], [‘Best’, 9]], 19: [[‘Gfg’, 7], [‘is’, 1], [‘Best’, 4]], 20: [[‘Gfg’, 7], [‘is’, 1], [‘Best’, 2]], 21: [[‘Gfg’, 7], [‘is’, 2], [‘Best’, 9]], 22: [[‘Gfg’, 7], [‘is’, 2], [‘Best’, 4]], 23: [[‘Gfg’, 7], [‘is’, 2], [‘Best’, 2]], 24: [[‘Gfg’, 7], [‘is’, 9], [‘Best’, 9]], 25: [[‘Gfg’, 7], [‘is’, 9], [‘Best’, 4]], 26: [[‘Gfg’, 7], [‘is’, 9], [‘Best’, 2]]}
Method #2 : Using product() + loop
The combination of above functions can also be used to solve this problem. In this, we perform the task of performing inner and cross keys combination using product(). Difference is that container of grouping is tuple rather than list.
Python3
# Python3 code to demonstrate working of # Dictionary Key Value lists combinations# Using product() + loopfrom itertools import product # initializing dictionarytest_dict = {"Gfg" : [4, 5, 7], "is" : [1, 2, 9], "Best" : [9, 4, 2]} # printing original dictionaryprint("The original dictionary is : " + str(test_dict)) res = {}for key, val in test_dict.items(): # for key-value combinations res[key] = product([key], val) # computing cross key combinationsres = product(*res.values()) # printing result print("The computed combinations : " + str(list(res)))
The original dictionary is : {‘Gfg’: [4, 5, 7], ‘is’: [1, 2, 9], ‘Best’: [9, 4, 2]}The computed combinations : [((‘Gfg’, 4), (‘is’, 1), (‘Best’, 9)), ((‘Gfg’, 4), (‘is’, 1), (‘Best’, 4)), ((‘Gfg’, 4), (‘is’, 1), (‘Best’, 2)), ((‘Gfg’, 4), (‘is’, 2), (‘Best’, 9)), ((‘Gfg’, 4), (‘is’, 2), (‘Best’, 4)), ((‘Gfg’, 4), (‘is’, 2), (‘Best’, 2)), ((‘Gfg’, 4), (‘is’, 9), (‘Best’, 9)), ((‘Gfg’, 4), (‘is’, 9), (‘Best’, 4)), ((‘Gfg’, 4), (‘is’, 9), (‘Best’, 2)), ((‘Gfg’, 5), (‘is’, 1), (‘Best’, 9)), ((‘Gfg’, 5), (‘is’, 1), (‘Best’, 4)), ((‘Gfg’, 5), (‘is’, 1), (‘Best’, 2)), ((‘Gfg’, 5), (‘is’, 2), (‘Best’, 9)), ((‘Gfg’, 5), (‘is’, 2), (‘Best’, 4)), ((‘Gfg’, 5), (‘is’, 2), (‘Best’, 2)), ((‘Gfg’, 5), (‘is’, 9), (‘Best’, 9)), ((‘Gfg’, 5), (‘is’, 9), (‘Best’, 4)), ((‘Gfg’, 5), (‘is’, 9), (‘Best’, 2)), ((‘Gfg’, 7), (‘is’, 1), (‘Best’, 9)), ((‘Gfg’, 7), (‘is’, 1), (‘Best’, 4)), ((‘Gfg’, 7), (‘is’, 1), (‘Best’, 2)), ((‘Gfg’, 7), (‘is’, 2), (‘Best’, 9)), ((‘Gfg’, 7), (‘is’, 2), (‘Best’, 4)), ((‘Gfg’, 7), (‘is’, 2), (‘Best’, 2)), ((‘Gfg’, 7), (‘is’, 9), (‘Best’, 9)), ((‘Gfg’, 7), (‘is’, 9), (‘Best’, 4)), ((‘Gfg’, 7), (‘is’, 9), (‘Best’, 2))]
Python dictionary-programs
Python list-programs
Python
Python Programs
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Python Dictionary
Read a file line by line in Python
How to Install PIP on Windows ?
Enumerate() in Python
Different ways to create Pandas Dataframe
Python program to convert a list to string
Defaultdict in Python
Python | Split string into list of characters
Python | Convert a list to dictionary
How to print without newline in Python? | [
{
"code": null,
"e": 25727,
"s": 25699,
"text": "\n01 Aug, 2020"
},
{
"code": null,
"e": 25837,
"s": 25727,
"text": "Given dictionary with values as list, extract all the possible combinations, both cross keys and with values."
},
{
"code": null,
"e": 26333,
"s": 25837,
"text": "Input : test_dict = {“Gfg” : [4, 5], “is” : [1, 2], “Best” : [9, 4]}Output : {0: [[‘Gfg’, 4], [‘is’, 1], [‘Best’, 9]], 1: [[‘Gfg’, 4], [‘is’, 1], [‘Best’, 4]], 2: [[‘Gfg’, 4], [‘is’, 2], [‘Best’, 9]], 3: [[‘Gfg’, 4], [‘is’, 2], [‘Best’, 4]], 4: [[‘Gfg’, 5], [‘is’, 1], [‘Best’, 9]], 5: [[‘Gfg’, 5], [‘is’, 1], [‘Best’, 4]], 6: [[‘Gfg’, 5], [‘is’, 2], [‘Best’, 9]], 7: [[‘Gfg’, 5], [‘is’, 2], [‘Best’, 4]]}Explanation : Prints all possible combination of key with values and cross values as well."
},
{
"code": null,
"e": 26533,
"s": 26333,
"text": "Input : test_dict = {“Gfg” : [4], “is” : [1], “Best” : [4]}Output : {0: [[‘Gfg’, 4], [‘is’, 1], [‘Best’, 4]]}Explanation : Prints all possible combination of key with values and cross values as well."
},
{
"code": null,
"e": 26576,
"s": 26533,
"text": "Method #1 : Using product() + zip() + loop"
},
{
"code": null,
"e": 26791,
"s": 26576,
"text": "The combination of above functions can be used to solve this problem. In this, we perform the first combination of keys with all values using product() and cross key combinations are performed using zip() and loop."
},
{
"code": null,
"e": 26799,
"s": 26791,
"text": "Python3"
},
{
"code": "# Python3 code to demonstrate working of # Dictionary Key Value lists combinations# Using product() + zip() + loopfrom itertools import product # initializing dictionarytest_dict = {\"Gfg\" : [4, 5, 7], \"is\" : [1, 2, 9], \"Best\" : [9, 4, 2]} # printing original dictionaryprint(\"The original dictionary is : \" + str(test_dict)) temp = list(test_dict.keys()) res = dict()cnt = 0 # making key-value combinations using productfor combs in product (*test_dict.values()): # zip used to perform cross keys combinations. res[cnt] = [[ele, cnt] for ele, cnt in zip(test_dict, combs)] cnt += 1 # printing result print(\"The computed combinations : \" + str(res)) ",
"e": 27501,
"s": 26799,
"text": null
},
{
"code": null,
"e": 28737,
"s": 27501,
"text": "The original dictionary is : {‘Gfg’: [4, 5, 7], ‘is’: [1, 2, 9], ‘Best’: [9, 4, 2]}The computed combinations : {0: [[‘Gfg’, 4], [‘is’, 1], [‘Best’, 9]], 1: [[‘Gfg’, 4], [‘is’, 1], [‘Best’, 4]], 2: [[‘Gfg’, 4], [‘is’, 1], [‘Best’, 2]], 3: [[‘Gfg’, 4], [‘is’, 2], [‘Best’, 9]], 4: [[‘Gfg’, 4], [‘is’, 2], [‘Best’, 4]], 5: [[‘Gfg’, 4], [‘is’, 2], [‘Best’, 2]], 6: [[‘Gfg’, 4], [‘is’, 9], [‘Best’, 9]], 7: [[‘Gfg’, 4], [‘is’, 9], [‘Best’, 4]], 8: [[‘Gfg’, 4], [‘is’, 9], [‘Best’, 2]], 9: [[‘Gfg’, 5], [‘is’, 1], [‘Best’, 9]], 10: [[‘Gfg’, 5], [‘is’, 1], [‘Best’, 4]], 11: [[‘Gfg’, 5], [‘is’, 1], [‘Best’, 2]], 12: [[‘Gfg’, 5], [‘is’, 2], [‘Best’, 9]], 13: [[‘Gfg’, 5], [‘is’, 2], [‘Best’, 4]], 14: [[‘Gfg’, 5], [‘is’, 2], [‘Best’, 2]], 15: [[‘Gfg’, 5], [‘is’, 9], [‘Best’, 9]], 16: [[‘Gfg’, 5], [‘is’, 9], [‘Best’, 4]], 17: [[‘Gfg’, 5], [‘is’, 9], [‘Best’, 2]], 18: [[‘Gfg’, 7], [‘is’, 1], [‘Best’, 9]], 19: [[‘Gfg’, 7], [‘is’, 1], [‘Best’, 4]], 20: [[‘Gfg’, 7], [‘is’, 1], [‘Best’, 2]], 21: [[‘Gfg’, 7], [‘is’, 2], [‘Best’, 9]], 22: [[‘Gfg’, 7], [‘is’, 2], [‘Best’, 4]], 23: [[‘Gfg’, 7], [‘is’, 2], [‘Best’, 2]], 24: [[‘Gfg’, 7], [‘is’, 9], [‘Best’, 9]], 25: [[‘Gfg’, 7], [‘is’, 9], [‘Best’, 4]], 26: [[‘Gfg’, 7], [‘is’, 9], [‘Best’, 2]]}"
},
{
"code": null,
"e": 28772,
"s": 28737,
"text": "Method #2 : Using product() + loop"
},
{
"code": null,
"e": 29008,
"s": 28772,
"text": "The combination of above functions can also be used to solve this problem. In this, we perform the task of performing inner and cross keys combination using product(). Difference is that container of grouping is tuple rather than list."
},
{
"code": null,
"e": 29016,
"s": 29008,
"text": "Python3"
},
{
"code": "# Python3 code to demonstrate working of # Dictionary Key Value lists combinations# Using product() + loopfrom itertools import product # initializing dictionarytest_dict = {\"Gfg\" : [4, 5, 7], \"is\" : [1, 2, 9], \"Best\" : [9, 4, 2]} # printing original dictionaryprint(\"The original dictionary is : \" + str(test_dict)) res = {}for key, val in test_dict.items(): # for key-value combinations res[key] = product([key], val) # computing cross key combinationsres = product(*res.values()) # printing result print(\"The computed combinations : \" + str(list(res))) ",
"e": 29615,
"s": 29016,
"text": null
},
{
"code": null,
"e": 30753,
"s": 29615,
"text": "The original dictionary is : {‘Gfg’: [4, 5, 7], ‘is’: [1, 2, 9], ‘Best’: [9, 4, 2]}The computed combinations : [((‘Gfg’, 4), (‘is’, 1), (‘Best’, 9)), ((‘Gfg’, 4), (‘is’, 1), (‘Best’, 4)), ((‘Gfg’, 4), (‘is’, 1), (‘Best’, 2)), ((‘Gfg’, 4), (‘is’, 2), (‘Best’, 9)), ((‘Gfg’, 4), (‘is’, 2), (‘Best’, 4)), ((‘Gfg’, 4), (‘is’, 2), (‘Best’, 2)), ((‘Gfg’, 4), (‘is’, 9), (‘Best’, 9)), ((‘Gfg’, 4), (‘is’, 9), (‘Best’, 4)), ((‘Gfg’, 4), (‘is’, 9), (‘Best’, 2)), ((‘Gfg’, 5), (‘is’, 1), (‘Best’, 9)), ((‘Gfg’, 5), (‘is’, 1), (‘Best’, 4)), ((‘Gfg’, 5), (‘is’, 1), (‘Best’, 2)), ((‘Gfg’, 5), (‘is’, 2), (‘Best’, 9)), ((‘Gfg’, 5), (‘is’, 2), (‘Best’, 4)), ((‘Gfg’, 5), (‘is’, 2), (‘Best’, 2)), ((‘Gfg’, 5), (‘is’, 9), (‘Best’, 9)), ((‘Gfg’, 5), (‘is’, 9), (‘Best’, 4)), ((‘Gfg’, 5), (‘is’, 9), (‘Best’, 2)), ((‘Gfg’, 7), (‘is’, 1), (‘Best’, 9)), ((‘Gfg’, 7), (‘is’, 1), (‘Best’, 4)), ((‘Gfg’, 7), (‘is’, 1), (‘Best’, 2)), ((‘Gfg’, 7), (‘is’, 2), (‘Best’, 9)), ((‘Gfg’, 7), (‘is’, 2), (‘Best’, 4)), ((‘Gfg’, 7), (‘is’, 2), (‘Best’, 2)), ((‘Gfg’, 7), (‘is’, 9), (‘Best’, 9)), ((‘Gfg’, 7), (‘is’, 9), (‘Best’, 4)), ((‘Gfg’, 7), (‘is’, 9), (‘Best’, 2))]"
},
{
"code": null,
"e": 30780,
"s": 30753,
"text": "Python dictionary-programs"
},
{
"code": null,
"e": 30801,
"s": 30780,
"text": "Python list-programs"
},
{
"code": null,
"e": 30808,
"s": 30801,
"text": "Python"
},
{
"code": null,
"e": 30824,
"s": 30808,
"text": "Python Programs"
},
{
"code": null,
"e": 30922,
"s": 30824,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 30940,
"s": 30922,
"text": "Python Dictionary"
},
{
"code": null,
"e": 30975,
"s": 30940,
"text": "Read a file line by line in Python"
},
{
"code": null,
"e": 31007,
"s": 30975,
"text": "How to Install PIP on Windows ?"
},
{
"code": null,
"e": 31029,
"s": 31007,
"text": "Enumerate() in Python"
},
{
"code": null,
"e": 31071,
"s": 31029,
"text": "Different ways to create Pandas Dataframe"
},
{
"code": null,
"e": 31114,
"s": 31071,
"text": "Python program to convert a list to string"
},
{
"code": null,
"e": 31136,
"s": 31114,
"text": "Defaultdict in Python"
},
{
"code": null,
"e": 31182,
"s": 31136,
"text": "Python | Split string into list of characters"
},
{
"code": null,
"e": 31220,
"s": 31182,
"text": "Python | Convert a list to dictionary"
}
] |
Count non-NA values by group in DataFrame in R - GeeksforGeeks | 30 Jun, 2021
In this article, we will discuss how to count non-NA values by the group in dataframe in R Programming Language.
The dplyr package is used to perform simulations in the data by performing manipulations and transformations. The group_by() method in R programming language is used to group the specified dataframe in R. It can be used to categorize data depending on various aggregate functions like count, minimum, maximum, or sum.
Syntax:
group_by(col-name)
On application of group_by() method, the summarize method is applied to compute a tally of the total values obtained according to each group. The summation of the non-null values is calculated using the designated column name and the aggregate method sum() supplied with the is.na() method as its argument.
Syntax:
summarise ( new-col-name = sum(is.na (col-name))
Both the methods are applied in order to the input dataframe using the pipe operator. The output is returned in the form of a tibble, with the first column consisting of the input arguments of the group_by method and the second column being assigned the new column name specified and containing a summation of the values of each column.
Example:
R
# creating a dataframedata_frame <- data.frame(col1 = sample(6:9, 9 , replace = TRUE), col2 = letters[1:3], col3 = c(1,4,NA,1,NA,NA,2,NA,2)) print ("Original DataFrame")print (data_frame) # grouping data by col1 and giving a total of# non na values in col3data_frame %>% group_by(col1) %>% summarise( non_na = sum(!is.na(col3)))
Output
[1] "Original DataFrame"
col1 col2 col3
1 6 a 1
2 8 b 4
3 6 c NA
4 8 a 1
5 8 b NA
6 9 c NA
7 8 a 2
8 7 b NA
9 6 c 2
# A tibble: 4 x 2
col1 non_na
<int> <int>
1 6 2
2 7 0
3 8 3
4 9 0
The library data.table in R is used to make statistical computations and deliberations based on the organization of data into well-defined tabular structures. The setDT method in R is used to convert lists (both named and unnamed) and dataframes to datatables by reference. The similar sum() and is.na() methods are applied over the columns of the dataframe in sequence to obtain the final output. The output returned is in the form of a data.table with row numbers followed by row identifiers followed by colon.
Syntax:
setDT(df)[, .(new-col-name = sum(!is.na(new-col-name))), col-name]
Example:
R
# importing required librarieslibrary(data.table) # creating a dataframedata_frame <- data.frame(col1 = sample(6:9, 9 , replace = TRUE), col2 = letters[1:3], col3 = c(1,4,NA,1,NA,NA,2,NA,2)) print ("Original DataFrame")print (data_frame) # grouping data by col1 and giving a total# of non na values in col3mod_df <- setDT(data_frame)[, .(non_na = sum(!is.na(col3))), col1]print ("Modified DataFrame")print (mod_df)
Output
[1] "Original DataFrame"
col1 col2 col3
1 7 a 1
2 6 b 4
3 6 c NA
4 7 a 1
5 9 b NA
6 8 c NA
7 6 a 2
8 8 b NA
9 8 c 2
[1] "Modified DataFrame"
col1 non_na
1: 7 2
2: 6 2
3: 9 0
4: 8 1
The aggregate method in R is used to create the subsets produced from the result of dataframe splitting and then computes the summary statistics for each of the returned group.
Syntax:
aggregate (x , data , FUN)
Parameter :
x – the R storage object.
data – the dataframe or list to apply the aggregate method to.
FUN – the function to apply to each of the groups of the dataframe.
The cbind() method in R programming language is used to produce a concatenation of the columns produced as the output. The FUN applied is the sum operation to compute the sum of the non-null values segregated based on groups. The data is the input dataframe over which the FUN is applied.
Example:
R
# importing required librarieslibrary(data.table) # creating a dataframedata_frame <- data.frame(col1 = sample(6:9, 9 , replace = TRUE), col2 = letters[1:3], col3 = c(1,4,NA,1,NA,NA,2,NA,2)) print ("Original DataFrame")print (data_frame) # grouping data by col1 and giving a total # of non na values in col3mod_df <- aggregate(cbind( non_na = !is.na(col3))~col1, data_frame, sum)print ("Modified DataFrame")print (mod_df)
Output
[1] "Original DataFrame"
col1 col2 col3
1 7 a 1
2 6 b 4
3 6 c NA
4 7 a 1
5 9 b NA
6 8 c NA
7 6 a 2
8 8 b NA
9 8 c 2
[1] "Modified DataFrame"
col1 non_na
1 7 2
2 6 2
3 9 0
4 8 1
The library data.table in R is used to make statistical computations and deliberations based on the organization of data into well-defined tabular structures. The table() method is used to generate a contingency table of the counts after computing the combination of each of the factor levels. Therefore, it is used to perform categorical tabulation of the data. Initially, the required column to check for NA values is specified under the constraint using the is.na() function. The non-null values are then extracted and a tally of them is produced using the data.table indexing methods.
Syntax:
is.na (df$col-name))
Example:
R
# importing required librarieslibrary(data.table) # creating a dataframedata_frame <- data.frame(col1 = sample(6:9, 9 , replace = TRUE), col2 = letters[1:3], col3 = c(1,4,NA,1,NA,NA,2,NA,2))print ("Original DataFrame")print (data_frame) # grouping data by col1 and giving a# total of non na values in col3mod_df <- table(data_frame$col1[!is.na(data_frame$col3)])print ("Modified DataFrame")print (mod_df)
Output
[1] "Original DataFrame"
col1 col2 col3
1 7 a 1
2 9 b 4
3 8 c NA
4 6 a 1
5 6 b NA
6 8 c NA
7 9 a 2
8 9 b NA
9 8 c 2
[1] "Modified DataFrame"
6 7 8 9
1 1 1 2
Picked
R DataFrame-Programs
R-DataFrame
R Language
R Programs
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Change Color of Bars in Barchart using ggplot2 in R
Group by function in R using Dplyr
How to Change Axis Scales in R Plots?
How to Split Column Into Multiple Columns in R DataFrame?
Replace Specific Characters in String in R
How to Split Column Into Multiple Columns in R DataFrame?
Replace Specific Characters in String in R
How to filter R DataFrame by values in a column?
How to filter R dataframe by multiple conditions?
Convert Matrix to Dataframe in R | [
{
"code": null,
"e": 26487,
"s": 26459,
"text": "\n30 Jun, 2021"
},
{
"code": null,
"e": 26600,
"s": 26487,
"text": "In this article, we will discuss how to count non-NA values by the group in dataframe in R Programming Language."
},
{
"code": null,
"e": 26919,
"s": 26600,
"text": "The dplyr package is used to perform simulations in the data by performing manipulations and transformations. The group_by() method in R programming language is used to group the specified dataframe in R. It can be used to categorize data depending on various aggregate functions like count, minimum, maximum, or sum. "
},
{
"code": null,
"e": 26927,
"s": 26919,
"text": "Syntax:"
},
{
"code": null,
"e": 26946,
"s": 26927,
"text": "group_by(col-name)"
},
{
"code": null,
"e": 27254,
"s": 26946,
"text": "On application of group_by() method, the summarize method is applied to compute a tally of the total values obtained according to each group. The summation of the non-null values is calculated using the designated column name and the aggregate method sum() supplied with the is.na() method as its argument. "
},
{
"code": null,
"e": 27262,
"s": 27254,
"text": "Syntax:"
},
{
"code": null,
"e": 27311,
"s": 27262,
"text": "summarise ( new-col-name = sum(is.na (col-name))"
},
{
"code": null,
"e": 27649,
"s": 27311,
"text": "Both the methods are applied in order to the input dataframe using the pipe operator. The output is returned in the form of a tibble, with the first column consisting of the input arguments of the group_by method and the second column being assigned the new column name specified and containing a summation of the values of each column. "
},
{
"code": null,
"e": 27658,
"s": 27649,
"text": "Example:"
},
{
"code": null,
"e": 27660,
"s": 27658,
"text": "R"
},
{
"code": "# creating a dataframedata_frame <- data.frame(col1 = sample(6:9, 9 , replace = TRUE), col2 = letters[1:3], col3 = c(1,4,NA,1,NA,NA,2,NA,2)) print (\"Original DataFrame\")print (data_frame) # grouping data by col1 and giving a total of# non na values in col3data_frame %>% group_by(col1) %>% summarise( non_na = sum(!is.na(col3)))",
"e": 28038,
"s": 27660,
"text": null
},
{
"code": null,
"e": 28045,
"s": 28038,
"text": "Output"
},
{
"code": null,
"e": 28377,
"s": 28045,
"text": "[1] \"Original DataFrame\"\ncol1 col2 col3\n1 6 a 1\n2 8 b 4\n3 6 c NA\n4 8 a 1\n5 8 b NA\n6 9 c NA\n7 8 a 2\n8 7 b NA\n9 6 c 2\n# A tibble: 4 x 2 \ncol1 non_na\n <int> <int>\n1 6 2\n2 7 0\n3 8 3\n4 9 0"
},
{
"code": null,
"e": 28891,
"s": 28377,
"text": "The library data.table in R is used to make statistical computations and deliberations based on the organization of data into well-defined tabular structures. The setDT method in R is used to convert lists (both named and unnamed) and dataframes to datatables by reference. The similar sum() and is.na() methods are applied over the columns of the dataframe in sequence to obtain the final output. The output returned is in the form of a data.table with row numbers followed by row identifiers followed by colon. "
},
{
"code": null,
"e": 28899,
"s": 28891,
"text": "Syntax:"
},
{
"code": null,
"e": 28966,
"s": 28899,
"text": "setDT(df)[, .(new-col-name = sum(!is.na(new-col-name))), col-name]"
},
{
"code": null,
"e": 28975,
"s": 28966,
"text": "Example:"
},
{
"code": null,
"e": 28977,
"s": 28975,
"text": "R"
},
{
"code": "# importing required librarieslibrary(data.table) # creating a dataframedata_frame <- data.frame(col1 = sample(6:9, 9 , replace = TRUE), col2 = letters[1:3], col3 = c(1,4,NA,1,NA,NA,2,NA,2)) print (\"Original DataFrame\")print (data_frame) # grouping data by col1 and giving a total# of non na values in col3mod_df <- setDT(data_frame)[, .(non_na = sum(!is.na(col3))), col1]print (\"Modified DataFrame\")print (mod_df)",
"e": 29441,
"s": 28977,
"text": null
},
{
"code": null,
"e": 29448,
"s": 29441,
"text": "Output"
},
{
"code": null,
"e": 29741,
"s": 29448,
"text": "[1] \"Original DataFrame\"\ncol1 col2 col3\n1 7 a 1\n2 6 b 4\n3 6 c NA\n4 7 a 1\n5 9 b NA\n6 8 c NA\n7 6 a 2\n8 8 b NA\n9 8 c 2\n[1] \"Modified DataFrame\"\n col1 non_na\n1: 7 2\n2: 6 2\n3: 9 0\n4: 8 1"
},
{
"code": null,
"e": 29919,
"s": 29741,
"text": "The aggregate method in R is used to create the subsets produced from the result of dataframe splitting and then computes the summary statistics for each of the returned group. "
},
{
"code": null,
"e": 29927,
"s": 29919,
"text": "Syntax:"
},
{
"code": null,
"e": 29954,
"s": 29927,
"text": "aggregate (x , data , FUN)"
},
{
"code": null,
"e": 29967,
"s": 29954,
"text": "Parameter : "
},
{
"code": null,
"e": 29993,
"s": 29967,
"text": "x – the R storage object."
},
{
"code": null,
"e": 30057,
"s": 29993,
"text": "data – the dataframe or list to apply the aggregate method to. "
},
{
"code": null,
"e": 30125,
"s": 30057,
"text": "FUN – the function to apply to each of the groups of the dataframe."
},
{
"code": null,
"e": 30415,
"s": 30125,
"text": "The cbind() method in R programming language is used to produce a concatenation of the columns produced as the output. The FUN applied is the sum operation to compute the sum of the non-null values segregated based on groups. The data is the input dataframe over which the FUN is applied. "
},
{
"code": null,
"e": 30424,
"s": 30415,
"text": "Example:"
},
{
"code": null,
"e": 30426,
"s": 30424,
"text": "R"
},
{
"code": "# importing required librarieslibrary(data.table) # creating a dataframedata_frame <- data.frame(col1 = sample(6:9, 9 , replace = TRUE), col2 = letters[1:3], col3 = c(1,4,NA,1,NA,NA,2,NA,2)) print (\"Original DataFrame\")print (data_frame) # grouping data by col1 and giving a total # of non na values in col3mod_df <- aggregate(cbind( non_na = !is.na(col3))~col1, data_frame, sum)print (\"Modified DataFrame\")print (mod_df)",
"e": 30898,
"s": 30426,
"text": null
},
{
"code": null,
"e": 30905,
"s": 30898,
"text": "Output"
},
{
"code": null,
"e": 31194,
"s": 30905,
"text": "[1] \"Original DataFrame\"\ncol1 col2 col3\n1 7 a 1\n2 6 b 4\n3 6 c NA\n4 7 a 1\n5 9 b NA\n6 8 c NA\n7 6 a 2\n8 8 b NA\n9 8 c 2\n[1] \"Modified DataFrame\"\n col1 non_na\n1 7 2\n2 6 2\n3 9 0\n4 8 1"
},
{
"code": null,
"e": 31784,
"s": 31194,
"text": "The library data.table in R is used to make statistical computations and deliberations based on the organization of data into well-defined tabular structures. The table() method is used to generate a contingency table of the counts after computing the combination of each of the factor levels. Therefore, it is used to perform categorical tabulation of the data. Initially, the required column to check for NA values is specified under the constraint using the is.na() function. The non-null values are then extracted and a tally of them is produced using the data.table indexing methods. "
},
{
"code": null,
"e": 31792,
"s": 31784,
"text": "Syntax:"
},
{
"code": null,
"e": 31813,
"s": 31792,
"text": "is.na (df$col-name))"
},
{
"code": null,
"e": 31822,
"s": 31813,
"text": "Example:"
},
{
"code": null,
"e": 31824,
"s": 31822,
"text": "R"
},
{
"code": "# importing required librarieslibrary(data.table) # creating a dataframedata_frame <- data.frame(col1 = sample(6:9, 9 , replace = TRUE), col2 = letters[1:3], col3 = c(1,4,NA,1,NA,NA,2,NA,2))print (\"Original DataFrame\")print (data_frame) # grouping data by col1 and giving a# total of non na values in col3mod_df <- table(data_frame$col1[!is.na(data_frame$col3)])print (\"Modified DataFrame\")print (mod_df)",
"e": 32277,
"s": 31824,
"text": null
},
{
"code": null,
"e": 32284,
"s": 32277,
"text": "Output"
},
{
"code": null,
"e": 32523,
"s": 32284,
"text": "[1] \"Original DataFrame\"\n col1 col2 col3\n1 7 a 1\n2 9 b 4\n3 8 c NA\n4 6 a 1\n5 6 b NA\n6 8 c NA\n7 9 a 2\n8 9 b NA\n9 8 c 2\n[1] \"Modified DataFrame\"\n6 7 8 9 \n1 1 1 2 "
},
{
"code": null,
"e": 32530,
"s": 32523,
"text": "Picked"
},
{
"code": null,
"e": 32551,
"s": 32530,
"text": "R DataFrame-Programs"
},
{
"code": null,
"e": 32563,
"s": 32551,
"text": "R-DataFrame"
},
{
"code": null,
"e": 32574,
"s": 32563,
"text": "R Language"
},
{
"code": null,
"e": 32585,
"s": 32574,
"text": "R Programs"
},
{
"code": null,
"e": 32683,
"s": 32585,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 32735,
"s": 32683,
"text": "Change Color of Bars in Barchart using ggplot2 in R"
},
{
"code": null,
"e": 32770,
"s": 32735,
"text": "Group by function in R using Dplyr"
},
{
"code": null,
"e": 32808,
"s": 32770,
"text": "How to Change Axis Scales in R Plots?"
},
{
"code": null,
"e": 32866,
"s": 32808,
"text": "How to Split Column Into Multiple Columns in R DataFrame?"
},
{
"code": null,
"e": 32909,
"s": 32866,
"text": "Replace Specific Characters in String in R"
},
{
"code": null,
"e": 32967,
"s": 32909,
"text": "How to Split Column Into Multiple Columns in R DataFrame?"
},
{
"code": null,
"e": 33010,
"s": 32967,
"text": "Replace Specific Characters in String in R"
},
{
"code": null,
"e": 33059,
"s": 33010,
"text": "How to filter R DataFrame by values in a column?"
},
{
"code": null,
"e": 33109,
"s": 33059,
"text": "How to filter R dataframe by multiple conditions?"
}
] |
How to design Meet the Team Page using HTML and CSS ? - GeeksforGeeks | 13 Aug, 2021
Creating Structure: In this section, we will create a basic structure for the meet the team page. We will attach the icon and put the text that will be placed on the card of members will add button.
CDN links for the Icons from the Font Awesome:
<link rel=”stylesheet” href=”https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.7.0/css/font-awesome.min.css”>
HTML code: The HTML code is used to create a structure of meet the team page. Since it does not contain CSS so it is just a basic structure. We will use some CSS property to make it attractive.
HTML
<!DOCTYPE html><html> <head> <meta name="viewport" content="width=device-width, initial-scale=1"> <!-- linking font awesome for icons --> <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.7.0/css/font-awesome.min.css"></head> <body> <center> <h1>Meet The Team Page</h1> <hr> <!-- First member of the team --> <div class="row"> <div class="column" id="gfg"> <div class="card"> <i class="fa fa-user-circle" style="font-size:68px;"></i> <div class="container"> <h2>Mike Tyson</h2> <p>CEO & Founder</p> <p> Feel your customer make them happy </p> <button class="button">View</button> </div> </div> </div> </div> <!-- Other members of the team --> <div class="row"> <div class="column"> <div class="card"> <i class="fa fa-user-circle" style="font-size:68px;"></i> <div class="container"> <h2>Ching Lee</h2> <p>Developer Head</p> <p> A website should be user-friendly and attractive </p> <button class="button">View</button> </div> </div> </div> <div class="column"> <div class="card"> <i class="fa fa-user-circle" style="font-size:68px;"></i> <div class="container"> <h2>Hashim Ahmed</h2> <p>Content Head</p> <p> Content should be popular and trending </p> <button class="button">View</button> </div> </div> </div> <div class="column"> <div class="card"> <i class="fa fa-user-circle" style="font-size:68px;"></i> <div class="container"> <h2>Rihana Gomez</h2> <p>Marketing Head</p> <p> Sell the product like Greatest Mary Kay Ash </p> <button class="button">View</button> </div> </div> </div> </div> </center></body> </html>
Designing Structure: In the previous section, we have created the structure of the basic structure of the team page and already added the icons for the members. In this section, we will add CSS property to design the card as required.
CSS code: CSS code is used to make an attractive team page. This CSS property is used to make the cards stylish and responsive.
HTML
<style> /* Whole html box designing */ html { box-sizing: border-box; } /* Body width fixing */ body { max-width: 100%; } /* Box sizing depending on parent */ *, *:before, *:after { box-sizing: inherit; } /* Styling column */ .column { float: left; width: 33%; margin-bottom: 16px; padding: 2px 10px; } /* Column width change depends on screen size */ @media screen and (max-width: 670px) { .column { width: 100%; text-align: none; } } /* Card designing */ .card { background-color: gray; border: 1px solid black; } .container { padding: 0 16px; } /* Icon styling */ .fa { margin: 10px; font-size:68px; } .fa:hover { transform: rotateY(180deg); transition: transform 0.8s; } .container::after, .row::after { content: ""; clear: both; display: table; } /* Button designing */ .button { border: none; padding: 8px; color: white; background-color: #449D44; text-align: center; cursor: pointer; width: 100%; margin-bottom: 10px; } /* Hover effect on button */ .button:hover { background-color: green; } /* Margin first member of team */ #gfg { float: none; margin: auto; }</style>
Combining the HTML and CSS Code: This example combines both HTML and CSS code to design the meet the team page.
HTML
<!DOCTYPE html><html> <head> <meta name="viewport" content="width=device-width, initial-scale=1"> <!-- linking font awesome for icons --> <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.7.0/css/font-awesome.min.css"> <style> /* Whole html box designing */ html { box-sizing: border-box; } /* Body width fixing */ body { max-width: 100% } /* Box sizing depending on parent */ *, *:before, *:after { box-sizing: inherit; } /* Styling column */ .column { float: left; width: 33%; margin-bottom: 16px; padding: 5px 10px; } /* Column width change depends on screen size */ @media screen and (max-width: 670px) { .column { width: 100%; text-align: none; } } /* Card designing */ .card { background-color: gray; border: 1px solid black; } .container { padding: 0 16px; } /* Icon styling */ .fa { margin: 10px; font-size:68px; } .fa:hover { transform: rotateY(180deg); transition: transform 0.8s; } .container::after, .row::after { content: ""; clear: both; display: table; } /* Button designing */ .button { border: none; padding: 8px; color: white; background-color: #449D44; text-align: center; cursor: pointer; width: 100%; margin-bottom: 10px; } /* Hover effect on button */ .button:hover { background-color: green; } /* Margining first member of team */ #gfg { float:none; margin:auto; } </style></head> <body> <center> <h1>Meet The Team Page</h1> <hr> <!-- First member of the team --> <div class="row"> <div class="column" id="gfg"> <div class="card"> <i class="fa fa-user-circle" style="font-size:68px;"></i> <div class="container"> <h2>Mike Tyson</h2> <p>CEO & Founder</p> <p> Feel your customer make them happy </p> <button class="button">View</button> </div> </div> </div> </div> <!-- Other members of the team --> <div class="row"> <div class="column"> <div class="card"> <i class="fa fa-user-circle" style="font-size:68px;"></i> <div class="container"> <h2>Ching Lee</h2> <p>Developer Head</p> <p> A website should be user-friendly and attractive </p> <button class="button">View</button> </div> </div> </div> <div class="column"> <div class="card"> <i class="fa fa-user-circle" style="font-size:68px;"></i> <div class="container"> <h2>Hashim Ahmed</h2> <p>Content Head</p> <p> Content should be popular and trending </p> <button class="button">View</button> </div> </div> </div> <div class="column"> <div class="card"> <i class="fa fa-user-circle" style="font-size:68px;"></i> <div class="container"> <h2>Rihana Gomez</h2> <p>Marketing Head</p> <p> Sell the product like Greatest Mary Kay Ash </p> <button class="button">View</button> </div> </div> </div> </div> </center></body> </html>
Output:
Supported Browser:
Google Chrome
Microsoft Edge
Firefox
Opera
Safari
Attention reader! Don’t stop learning now. Get hold of all the important HTML concepts with the Web Design for Beginners | HTML course.
ysachin2314
adnanirshad158
CSS-Misc
HTML-Misc
CSS
HTML
Web Technologies
Web technologies Questions
HTML
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Top 10 Projects For Beginners To Practice HTML and CSS Skills
How to insert spaces/tabs in text using HTML/CSS?
How to update Node.js and NPM to next version ?
How to create footer to stay at the bottom of a Web page?
How to apply style to parent if it has child with CSS?
Top 10 Projects For Beginners To Practice HTML and CSS Skills
How to insert spaces/tabs in text using HTML/CSS?
How to update Node.js and NPM to next version ?
How to set the default value for an HTML <select> element ?
Hide or show elements in HTML using display property | [
{
"code": null,
"e": 31624,
"s": 31596,
"text": "\n13 Aug, 2021"
},
{
"code": null,
"e": 31823,
"s": 31624,
"text": "Creating Structure: In this section, we will create a basic structure for the meet the team page. We will attach the icon and put the text that will be placed on the card of members will add button."
},
{
"code": null,
"e": 31871,
"s": 31823,
"text": "CDN links for the Icons from the Font Awesome: "
},
{
"code": null,
"e": 31985,
"s": 31871,
"text": "<link rel=”stylesheet” href=”https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.7.0/css/font-awesome.min.css”>"
},
{
"code": null,
"e": 32179,
"s": 31985,
"text": "HTML code: The HTML code is used to create a structure of meet the team page. Since it does not contain CSS so it is just a basic structure. We will use some CSS property to make it attractive."
},
{
"code": null,
"e": 32184,
"s": 32179,
"text": "HTML"
},
{
"code": "<!DOCTYPE html><html> <head> <meta name=\"viewport\" content=\"width=device-width, initial-scale=1\"> <!-- linking font awesome for icons --> <link rel=\"stylesheet\" href=\"https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.7.0/css/font-awesome.min.css\"></head> <body> <center> <h1>Meet The Team Page</h1> <hr> <!-- First member of the team --> <div class=\"row\"> <div class=\"column\" id=\"gfg\"> <div class=\"card\"> <i class=\"fa fa-user-circle\" style=\"font-size:68px;\"></i> <div class=\"container\"> <h2>Mike Tyson</h2> <p>CEO & Founder</p> <p> Feel your customer make them happy </p> <button class=\"button\">View</button> </div> </div> </div> </div> <!-- Other members of the team --> <div class=\"row\"> <div class=\"column\"> <div class=\"card\"> <i class=\"fa fa-user-circle\" style=\"font-size:68px;\"></i> <div class=\"container\"> <h2>Ching Lee</h2> <p>Developer Head</p> <p> A website should be user-friendly and attractive </p> <button class=\"button\">View</button> </div> </div> </div> <div class=\"column\"> <div class=\"card\"> <i class=\"fa fa-user-circle\" style=\"font-size:68px;\"></i> <div class=\"container\"> <h2>Hashim Ahmed</h2> <p>Content Head</p> <p> Content should be popular and trending </p> <button class=\"button\">View</button> </div> </div> </div> <div class=\"column\"> <div class=\"card\"> <i class=\"fa fa-user-circle\" style=\"font-size:68px;\"></i> <div class=\"container\"> <h2>Rihana Gomez</h2> <p>Marketing Head</p> <p> Sell the product like Greatest Mary Kay Ash </p> <button class=\"button\">View</button> </div> </div> </div> </div> </center></body> </html>",
"e": 35045,
"s": 32184,
"text": null
},
{
"code": null,
"e": 35281,
"s": 35045,
"text": "Designing Structure: In the previous section, we have created the structure of the basic structure of the team page and already added the icons for the members. In this section, we will add CSS property to design the card as required. "
},
{
"code": null,
"e": 35410,
"s": 35281,
"text": "CSS code: CSS code is used to make an attractive team page. This CSS property is used to make the cards stylish and responsive. "
},
{
"code": null,
"e": 35415,
"s": 35410,
"text": "HTML"
},
{
"code": "<style> /* Whole html box designing */ html { box-sizing: border-box; } /* Body width fixing */ body { max-width: 100%; } /* Box sizing depending on parent */ *, *:before, *:after { box-sizing: inherit; } /* Styling column */ .column { float: left; width: 33%; margin-bottom: 16px; padding: 2px 10px; } /* Column width change depends on screen size */ @media screen and (max-width: 670px) { .column { width: 100%; text-align: none; } } /* Card designing */ .card { background-color: gray; border: 1px solid black; } .container { padding: 0 16px; } /* Icon styling */ .fa { margin: 10px; font-size:68px; } .fa:hover { transform: rotateY(180deg); transition: transform 0.8s; } .container::after, .row::after { content: \"\"; clear: both; display: table; } /* Button designing */ .button { border: none; padding: 8px; color: white; background-color: #449D44; text-align: center; cursor: pointer; width: 100%; margin-bottom: 10px; } /* Hover effect on button */ .button:hover { background-color: green; } /* Margin first member of team */ #gfg { float: none; margin: auto; }</style>",
"e": 36970,
"s": 35415,
"text": null
},
{
"code": null,
"e": 37082,
"s": 36970,
"text": "Combining the HTML and CSS Code: This example combines both HTML and CSS code to design the meet the team page."
},
{
"code": null,
"e": 37087,
"s": 37082,
"text": "HTML"
},
{
"code": "<!DOCTYPE html><html> <head> <meta name=\"viewport\" content=\"width=device-width, initial-scale=1\"> <!-- linking font awesome for icons --> <link rel=\"stylesheet\" href=\"https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.7.0/css/font-awesome.min.css\"> <style> /* Whole html box designing */ html { box-sizing: border-box; } /* Body width fixing */ body { max-width: 100% } /* Box sizing depending on parent */ *, *:before, *:after { box-sizing: inherit; } /* Styling column */ .column { float: left; width: 33%; margin-bottom: 16px; padding: 5px 10px; } /* Column width change depends on screen size */ @media screen and (max-width: 670px) { .column { width: 100%; text-align: none; } } /* Card designing */ .card { background-color: gray; border: 1px solid black; } .container { padding: 0 16px; } /* Icon styling */ .fa { margin: 10px; font-size:68px; } .fa:hover { transform: rotateY(180deg); transition: transform 0.8s; } .container::after, .row::after { content: \"\"; clear: both; display: table; } /* Button designing */ .button { border: none; padding: 8px; color: white; background-color: #449D44; text-align: center; cursor: pointer; width: 100%; margin-bottom: 10px; } /* Hover effect on button */ .button:hover { background-color: green; } /* Margining first member of team */ #gfg { float:none; margin:auto; } </style></head> <body> <center> <h1>Meet The Team Page</h1> <hr> <!-- First member of the team --> <div class=\"row\"> <div class=\"column\" id=\"gfg\"> <div class=\"card\"> <i class=\"fa fa-user-circle\" style=\"font-size:68px;\"></i> <div class=\"container\"> <h2>Mike Tyson</h2> <p>CEO & Founder</p> <p> Feel your customer make them happy </p> <button class=\"button\">View</button> </div> </div> </div> </div> <!-- Other members of the team --> <div class=\"row\"> <div class=\"column\"> <div class=\"card\"> <i class=\"fa fa-user-circle\" style=\"font-size:68px;\"></i> <div class=\"container\"> <h2>Ching Lee</h2> <p>Developer Head</p> <p> A website should be user-friendly and attractive </p> <button class=\"button\">View</button> </div> </div> </div> <div class=\"column\"> <div class=\"card\"> <i class=\"fa fa-user-circle\" style=\"font-size:68px;\"></i> <div class=\"container\"> <h2>Hashim Ahmed</h2> <p>Content Head</p> <p> Content should be popular and trending </p> <button class=\"button\">View</button> </div> </div> </div> <div class=\"column\"> <div class=\"card\"> <i class=\"fa fa-user-circle\" style=\"font-size:68px;\"></i> <div class=\"container\"> <h2>Rihana Gomez</h2> <p>Marketing Head</p> <p> Sell the product like Greatest Mary Kay Ash </p> <button class=\"button\">View</button> </div> </div> </div> </div> </center></body> </html>",
"e": 41772,
"s": 37087,
"text": null
},
{
"code": null,
"e": 41781,
"s": 41772,
"text": "Output: "
},
{
"code": null,
"e": 41800,
"s": 41781,
"text": "Supported Browser:"
},
{
"code": null,
"e": 41814,
"s": 41800,
"text": "Google Chrome"
},
{
"code": null,
"e": 41829,
"s": 41814,
"text": "Microsoft Edge"
},
{
"code": null,
"e": 41837,
"s": 41829,
"text": "Firefox"
},
{
"code": null,
"e": 41843,
"s": 41837,
"text": "Opera"
},
{
"code": null,
"e": 41850,
"s": 41843,
"text": "Safari"
},
{
"code": null,
"e": 41987,
"s": 41850,
"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": 41999,
"s": 41987,
"text": "ysachin2314"
},
{
"code": null,
"e": 42014,
"s": 41999,
"text": "adnanirshad158"
},
{
"code": null,
"e": 42023,
"s": 42014,
"text": "CSS-Misc"
},
{
"code": null,
"e": 42033,
"s": 42023,
"text": "HTML-Misc"
},
{
"code": null,
"e": 42037,
"s": 42033,
"text": "CSS"
},
{
"code": null,
"e": 42042,
"s": 42037,
"text": "HTML"
},
{
"code": null,
"e": 42059,
"s": 42042,
"text": "Web Technologies"
},
{
"code": null,
"e": 42086,
"s": 42059,
"text": "Web technologies Questions"
},
{
"code": null,
"e": 42091,
"s": 42086,
"text": "HTML"
},
{
"code": null,
"e": 42189,
"s": 42091,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 42251,
"s": 42189,
"text": "Top 10 Projects For Beginners To Practice HTML and CSS Skills"
},
{
"code": null,
"e": 42301,
"s": 42251,
"text": "How to insert spaces/tabs in text using HTML/CSS?"
},
{
"code": null,
"e": 42349,
"s": 42301,
"text": "How to update Node.js and NPM to next version ?"
},
{
"code": null,
"e": 42407,
"s": 42349,
"text": "How to create footer to stay at the bottom of a Web page?"
},
{
"code": null,
"e": 42462,
"s": 42407,
"text": "How to apply style to parent if it has child with CSS?"
},
{
"code": null,
"e": 42524,
"s": 42462,
"text": "Top 10 Projects For Beginners To Practice HTML and CSS Skills"
},
{
"code": null,
"e": 42574,
"s": 42524,
"text": "How to insert spaces/tabs in text using HTML/CSS?"
},
{
"code": null,
"e": 42622,
"s": 42574,
"text": "How to update Node.js and NPM to next version ?"
},
{
"code": null,
"e": 42682,
"s": 42622,
"text": "How to set the default value for an HTML <select> element ?"
}
] |
Loops in MySQL - GeeksforGeeks | 17 Jan, 2022
The MySQL LOOP statement could be used to run a block of code or set of statements, again and again, depends on the condition.
Syntax :
[labelname:] LOOP
statements
END LOOP [labelname]
Parameters –
labelname : It is an optional label at the start and end.
statements : They could have one or multiple statements, each ended by a semicolon (;) and executed by LOOP.
Syntax of the LOOP statement with LEAVE statement :
[labelname]: LOOP
-- terminate the loop
IF condition THEN
LEAVE [labelname];
END IF;
END LOOP;
Example-1 :
DROP PROCEDURE IF EXISTS GeekLoop();
DELIMITER $$
CREATE PROCEDURE GeekLoop()
BEGIN
DECLARE no INT;
SET no = 0;
loop: LOOP
SET no = no +1;
select no ;
IF no =5 THEN
LEAVE loop;
END IF;
END LOOP loop;
SELECT no;
END $$
DELIMITER ;
Statement to check the output :
CALL GeekLoop();
Output –
0, 1, 2, 3, 4, 5
Example-2 :
DELIMITER $$
CREATE FUNCTION Geekdemo (value1 INT)
RETURNS INT
BEGIN
DECLARE value2 INT;
SET value2 = 0;
label: LOOP
SET income = value2 + value1 ;
IF value2 < 4000 THEN
ITERATE label;
END IF;
LEAVE label;
END LOOP label;
RETURN value2 ;
END $$
DELIMITER ;
Queries to check the output :
CALL Geekdemo();
Input –
value1: 3500
Output –
value2: 3500
Example-3 :
CREATE TABLE Geektable (value VARCHAR(50) NULL DEFAULT NULL);
DELIMITER $$
CREATE PROCEDURE ADD()
BEGIN
DECLARE a INT Default 1 ;
simple_loop: LOOP
insert into table1 values(a);
SET a=a+1;
IF a=11 THEN
LEAVE simple_loop;
END IF;
END LOOP simple_loop;
END $$
Queries to check the output –
CALL ADD();
Select value
from Geektable;
Output –
1
2
3
4
5
6
7
8
9
10
kk9826225
mysql
SQL
SQL
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
SQL Interview Questions
CTE in SQL
How to Update Multiple Columns in Single Update Statement in SQL?
Difference between SQL and NoSQL
Difference between DELETE, DROP and TRUNCATE
MySQL | Group_CONCAT() Function
Difference between DELETE and TRUNCATE
SQL - ORDER BY
SQL | Subquery
How to Create a Table With Multiple Foreign Keys in SQL? | [
{
"code": null,
"e": 25562,
"s": 25534,
"text": "\n17 Jan, 2022"
},
{
"code": null,
"e": 25689,
"s": 25562,
"text": "The MySQL LOOP statement could be used to run a block of code or set of statements, again and again, depends on the condition."
},
{
"code": null,
"e": 25698,
"s": 25689,
"text": "Syntax :"
},
{
"code": null,
"e": 25751,
"s": 25698,
"text": "[labelname:] LOOP\n statements\nEND LOOP [labelname]"
},
{
"code": null,
"e": 25764,
"s": 25751,
"text": "Parameters –"
},
{
"code": null,
"e": 25822,
"s": 25764,
"text": "labelname : It is an optional label at the start and end."
},
{
"code": null,
"e": 25931,
"s": 25822,
"text": "statements : They could have one or multiple statements, each ended by a semicolon (;) and executed by LOOP."
},
{
"code": null,
"e": 25983,
"s": 25931,
"text": "Syntax of the LOOP statement with LEAVE statement :"
},
{
"code": null,
"e": 26096,
"s": 25983,
"text": "[labelname]: LOOP\n -- terminate the loop\n IF condition THEN\n LEAVE [labelname];\n END IF;\nEND LOOP;"
},
{
"code": null,
"e": 26108,
"s": 26096,
"text": "Example-1 :"
},
{
"code": null,
"e": 26145,
"s": 26108,
"text": "DROP PROCEDURE IF EXISTS GeekLoop();"
},
{
"code": null,
"e": 26367,
"s": 26145,
"text": "DELIMITER $$ \nCREATE PROCEDURE GeekLoop()\n BEGIN\nDECLARE no INT;\n SET no = 0;\n loop: LOOP\n SET no = no +1;\n select no ;\n IF no =5 THEN\n LEAVE loop;\n END IF;\n END LOOP loop;\nSELECT no;\nEND $$\nDELIMITER ;\n"
},
{
"code": null,
"e": 26399,
"s": 26367,
"text": "Statement to check the output :"
},
{
"code": null,
"e": 26416,
"s": 26399,
"text": "CALL GeekLoop();"
},
{
"code": null,
"e": 26425,
"s": 26416,
"text": "Output –"
},
{
"code": null,
"e": 26442,
"s": 26425,
"text": "0, 1, 2, 3, 4, 5"
},
{
"code": null,
"e": 26454,
"s": 26442,
"text": "Example-2 :"
},
{
"code": null,
"e": 26729,
"s": 26454,
"text": "DELIMITER $$\nCREATE FUNCTION Geekdemo (value1 INT)\nRETURNS INT\nBEGIN\n DECLARE value2 INT;\n SET value2 = 0;\n label: LOOP\n SET income = value2 + value1 ;\n IF value2 < 4000 THEN\n ITERATE label;\n END IF;\n LEAVE label;\n END LOOP label;\n RETURN value2 ;\nEND $$\nDELIMITER ;\n"
},
{
"code": null,
"e": 26759,
"s": 26729,
"text": "Queries to check the output :"
},
{
"code": null,
"e": 26776,
"s": 26759,
"text": "CALL Geekdemo();"
},
{
"code": null,
"e": 26784,
"s": 26776,
"text": "Input –"
},
{
"code": null,
"e": 26797,
"s": 26784,
"text": "value1: 3500"
},
{
"code": null,
"e": 26806,
"s": 26797,
"text": "Output –"
},
{
"code": null,
"e": 26819,
"s": 26806,
"text": "value2: 3500"
},
{
"code": null,
"e": 26831,
"s": 26819,
"text": "Example-3 :"
},
{
"code": null,
"e": 26893,
"s": 26831,
"text": "CREATE TABLE Geektable (value VARCHAR(50) NULL DEFAULT NULL);"
},
{
"code": null,
"e": 27124,
"s": 26893,
"text": "DELIMITER $$ \nCREATE PROCEDURE ADD()\n BEGIN\n DECLARE a INT Default 1 ;\n simple_loop: LOOP \n insert into table1 values(a);\n SET a=a+1;\n IF a=11 THEN\n LEAVE simple_loop;\n END IF;\n END LOOP simple_loop;\nEND $$\n"
},
{
"code": null,
"e": 27154,
"s": 27124,
"text": "Queries to check the output –"
},
{
"code": null,
"e": 27196,
"s": 27154,
"text": "CALL ADD();\nSelect value \nfrom Geektable;"
},
{
"code": null,
"e": 27205,
"s": 27196,
"text": "Output –"
},
{
"code": null,
"e": 27227,
"s": 27205,
"text": "1\n2\n3\n4\n5\n6\n7\n8\n9\n10 "
},
{
"code": null,
"e": 27237,
"s": 27227,
"text": "kk9826225"
},
{
"code": null,
"e": 27243,
"s": 27237,
"text": "mysql"
},
{
"code": null,
"e": 27247,
"s": 27243,
"text": "SQL"
},
{
"code": null,
"e": 27251,
"s": 27247,
"text": "SQL"
},
{
"code": null,
"e": 27349,
"s": 27251,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 27373,
"s": 27349,
"text": "SQL Interview Questions"
},
{
"code": null,
"e": 27384,
"s": 27373,
"text": "CTE in SQL"
},
{
"code": null,
"e": 27450,
"s": 27384,
"text": "How to Update Multiple Columns in Single Update Statement in SQL?"
},
{
"code": null,
"e": 27483,
"s": 27450,
"text": "Difference between SQL and NoSQL"
},
{
"code": null,
"e": 27528,
"s": 27483,
"text": "Difference between DELETE, DROP and TRUNCATE"
},
{
"code": null,
"e": 27560,
"s": 27528,
"text": "MySQL | Group_CONCAT() Function"
},
{
"code": null,
"e": 27599,
"s": 27560,
"text": "Difference between DELETE and TRUNCATE"
},
{
"code": null,
"e": 27614,
"s": 27599,
"text": "SQL - ORDER BY"
},
{
"code": null,
"e": 27629,
"s": 27614,
"text": "SQL | Subquery"
}
] |
How to pass an argument to the event handler in Tkinter? | In most situations, the callback functions can refer to as an Instance Method. An instance method accesses all its members and performs operations with them without specifying any arguments.
Let's consider a case where more than one component is defined and we want to handle some events with those components. To run multiple events, we prefer to pass multiple arguments in event handlers.
In this example, we have created multiple button widgets in a frame, and we will handle various events by passing the name of the widget as arguments. Once a Button will be clicked, it will update the Label widget and so on.
#Import the Tkinter library
from tkinter import *
from tkinter import ttk
from tkinter import filedialog
#Create an instance of Tkinter frame
win= Tk()
#Define the geometry
win.geometry("750x250")
#Define Event handlers for different Operations
def event_low(button1):
label.config(text="This is Lower Value")
def event_mid(button2):
label.config(text="This is Medium Value")
def event_high(button3):
label.config(text="This is Highest value")
#Create a Label
label= Label(win, text="",font=('Helvetica 15 underline'))
label.pack()
#Create a frame
frame= Frame(win)
#Create Buttons in the frame
button1= ttk.Button(frame, text="Low", command=lambda:event_low(button1))
button1.pack(pady=10)
button2= ttk.Button(frame, text="Medium",command= lambda:event_mid(button2))
button2.pack(pady=10)
button3= ttk.Button(frame, text="High",command= lambda:event_high(button3))
button3.pack(pady=10)
frame.pack()
win.mainloop()
Running the above code will display a window that contains Buttons Low, Medium, and High. When we click a button, it will show some label text on the window. | [
{
"code": null,
"e": 1253,
"s": 1062,
"text": "In most situations, the callback functions can refer to as an Instance Method. An instance method accesses all its members and performs operations with them without specifying any arguments."
},
{
"code": null,
"e": 1453,
"s": 1253,
"text": "Let's consider a case where more than one component is defined and we want to handle some events with those components. To run multiple events, we prefer to pass multiple arguments in event handlers."
},
{
"code": null,
"e": 1678,
"s": 1453,
"text": "In this example, we have created multiple button widgets in a frame, and we will handle various events by passing the name of the widget as arguments. Once a Button will be clicked, it will update the Label widget and so on."
},
{
"code": null,
"e": 2603,
"s": 1678,
"text": "#Import the Tkinter library\nfrom tkinter import *\nfrom tkinter import ttk\nfrom tkinter import filedialog\n#Create an instance of Tkinter frame\nwin= Tk()\n#Define the geometry\nwin.geometry(\"750x250\")\n#Define Event handlers for different Operations\ndef event_low(button1):\n label.config(text=\"This is Lower Value\")\ndef event_mid(button2):\n label.config(text=\"This is Medium Value\")\ndef event_high(button3):\n label.config(text=\"This is Highest value\")\n#Create a Label\nlabel= Label(win, text=\"\",font=('Helvetica 15 underline'))\nlabel.pack()\n#Create a frame\nframe= Frame(win)\n#Create Buttons in the frame\nbutton1= ttk.Button(frame, text=\"Low\", command=lambda:event_low(button1))\nbutton1.pack(pady=10)\nbutton2= ttk.Button(frame, text=\"Medium\",command= lambda:event_mid(button2))\nbutton2.pack(pady=10)\nbutton3= ttk.Button(frame, text=\"High\",command= lambda:event_high(button3))\nbutton3.pack(pady=10)\nframe.pack()\nwin.mainloop()"
},
{
"code": null,
"e": 2761,
"s": 2603,
"text": "Running the above code will display a window that contains Buttons Low, Medium, and High. When we click a button, it will show some label text on the window."
}
] |
\bf - Tex Command | \bf - Used to turn on boldface; affects uppercase and lowercase letters, and digits.
{ \bf ... }
\bf command is used to turn on boldface; affects uppercase and lowercase letters, and digits.
\bf AaBb\alpha\beta123
AaBbαβ123
{\bf A B} A B
ABAB
\bf AB \rm CD
ABCD
\bf{AB}CD
ABCD
\bf AaBb\alpha\beta123
AaBbαβ123
\bf AaBb\alpha\beta123
{\bf A B} A B
ABAB
{\bf A B} A B
\bf AB \rm CD
ABCD
\bf AB \rm CD
\bf{AB}CD
ABCD
\bf{AB}CD
14 Lectures
52 mins
Ashraf Said
11 Lectures
1 hours
Ashraf Said
9 Lectures
1 hours
Emenwa Global, Ejike IfeanyiChukwu
29 Lectures
2.5 hours
Mohammad Nauman
14 Lectures
1 hours
Daniel Stern
15 Lectures
47 mins
Nishant Kumar
Print
Add Notes
Bookmark this page | [
{
"code": null,
"e": 8071,
"s": 7986,
"text": "\\bf - Used to turn on boldface; affects uppercase and lowercase letters, and digits."
},
{
"code": null,
"e": 8083,
"s": 8071,
"text": "{ \\bf ... }"
},
{
"code": null,
"e": 8177,
"s": 8083,
"text": "\\bf command is used to turn on boldface; affects uppercase and lowercase letters, and digits."
},
{
"code": null,
"e": 8281,
"s": 8177,
"text": "\n\\bf AaBb\\alpha\\beta123 \n\nAaBbαβ123\n\n\n{\\bf A B} A B \n\nABAB\n\n\n\\bf AB \\rm CD \n\nABCD\n\n\n\\bf{AB}CD \n\nABCD\n\n\n"
},
{
"code": null,
"e": 8318,
"s": 8281,
"text": "\\bf AaBb\\alpha\\beta123 \n\nAaBbαβ123\n\n"
},
{
"code": null,
"e": 8342,
"s": 8318,
"text": "\\bf AaBb\\alpha\\beta123 "
},
{
"code": null,
"e": 8365,
"s": 8342,
"text": "{\\bf A B} A B \n\nABAB\n\n"
},
{
"code": null,
"e": 8380,
"s": 8365,
"text": "{\\bf A B} A B "
},
{
"code": null,
"e": 8403,
"s": 8380,
"text": "\\bf AB \\rm CD \n\nABCD\n\n"
},
{
"code": null,
"e": 8418,
"s": 8403,
"text": "\\bf AB \\rm CD "
},
{
"code": null,
"e": 8437,
"s": 8418,
"text": "\\bf{AB}CD \n\nABCD\n\n"
},
{
"code": null,
"e": 8448,
"s": 8437,
"text": "\\bf{AB}CD "
},
{
"code": null,
"e": 8480,
"s": 8448,
"text": "\n 14 Lectures \n 52 mins\n"
},
{
"code": null,
"e": 8493,
"s": 8480,
"text": " Ashraf Said"
},
{
"code": null,
"e": 8526,
"s": 8493,
"text": "\n 11 Lectures \n 1 hours \n"
},
{
"code": null,
"e": 8539,
"s": 8526,
"text": " Ashraf Said"
},
{
"code": null,
"e": 8571,
"s": 8539,
"text": "\n 9 Lectures \n 1 hours \n"
},
{
"code": null,
"e": 8607,
"s": 8571,
"text": " Emenwa Global, Ejike IfeanyiChukwu"
},
{
"code": null,
"e": 8642,
"s": 8607,
"text": "\n 29 Lectures \n 2.5 hours \n"
},
{
"code": null,
"e": 8659,
"s": 8642,
"text": " Mohammad Nauman"
},
{
"code": null,
"e": 8692,
"s": 8659,
"text": "\n 14 Lectures \n 1 hours \n"
},
{
"code": null,
"e": 8706,
"s": 8692,
"text": " Daniel Stern"
},
{
"code": null,
"e": 8738,
"s": 8706,
"text": "\n 15 Lectures \n 47 mins\n"
},
{
"code": null,
"e": 8753,
"s": 8738,
"text": " Nishant Kumar"
},
{
"code": null,
"e": 8760,
"s": 8753,
"text": " Print"
},
{
"code": null,
"e": 8771,
"s": 8760,
"text": " Add Notes"
}
] |
Mobile Angular UI - Accordions | Accordions are mostly used when the content is supposed to be in section type of view and any one section is visible at a time. You can hide and open the next section to view the contents in it.
Let us work on an example to see the working of an Accordion in Mobile Angular UI.
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<title>Mobile Angular UI Demo</title>
<meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1" />
<meta name="apple-mobile-web-app-capable" content="yes" />
<meta name="viewport" content="user-scalable=no, initial-scale=1.0, maximum-scale=1.0, minimal-ui" />
<meta name="apple-mobile-web-app-status-bar-style" content="yes" />
<link rel="shortcut icon" href="/assets/img/favicon.png" type="image/x-icon" />
<link rel="stylesheet" href="node_modules/mobile-angular-ui/dist/css/mobile-angular-ui-hover.min.css" />
<link rel="stylesheet" href="node_modules/mobile-angular-ui/dist/css/mobile-angular-ui-base.min.css" />
<link rel="stylesheet" href="node_modules/mobile-angular-ui/dist/css/mobile-angular-ui-desktop.min.css" />
<script src="node_modules/angular/angular.min.js"></script>
<script src="node_modules/angular-route/angular-route.min.js"></script>
<script src="node_modules/mobile-angular-ui/dist/js/mobile-angular-ui.min.js"></script>
<script src="node_modules/angular-route/angular-route.min.js"></script>
<link rel="stylesheet" href="src/css/app.css" />
<script src="src/js/app.js"></script>
</head>
<body ng-app="myFirstApp" ng-controller="MainController">
<!-- Sidebars -->
<div class="sidebar sidebar-left">
<div class="scrollable">
<h1 class="scrollable-header app-name">Tutorials</h1>
<div class="scrollable-content">
<div class="list-group" ui-turn-off='uiSidebarLeft'>
<a class="list-group-item" href="/">Home Page </a>
<a class="list-group-item" href="#/academic"><i class="fa fa-caret-right"></i>Academic Tutorials </a>
<a class="list-group-item" href="#/bigdata"><i class="fa fa-caret-right"></i>Big Data & Analytics </a>
<a class="list-group-item" href="#/computerProg"><i class="fa fa-caret-right"></i>Computer Programming </a>
<a class="list-group-item" href="#/computerscience"><i class="fa fa-caret-right"></i>Computer Science </a>
<a class="list-group-item" href="#/databases"><i class="fa fa-caret-right"></i>Databases </a>
<a class="list-group-item" href="#/devops"><i class="fa fa-caret-right"></i>DevOps </a>
</div>
</div>
</div>
</div>
<div class="sidebar sidebar-right">
<div class="scrollable">
<h1 class="scrollable-header app-name">eBooks</h1>
<div class="scrollable-content">
<div class="list-group" ui-toggle="uiSidebarRight">
<a class="list-group-item" href="#/php"><i class="fa fa-caret-right"></i>PHP </a>
<a class="list-group-item" href="#/Javascript"><i class="fa fa-caret-right"></i>Javascript </a>
</div>
</div>
</div>
</div>
<div class="app">
<div class="navbar navbar-app navbar-absolute-top">
<div class="navbar-brand navbar-brand-center" ui-yield-to="title">
TutorialsPoint
</div>
<div class="btn-group pull-left">
<div ui-toggle="uiSidebarLeft" class="btn sidebar-left-toggle">
<i class="fa fa-th-large "></i> Tutorials
</div>
</div>
<div class="btn-group pull-right" ui-yield-to="navbarAction">
<div ui-toggle="uiSidebarRight" class="btn sidebar-right-toggle">
<i class="fal fa-search"></i> eBooks
</div>
</div>
</div>
<div class="navbar navbar-app navbar-absolute-bottom">
<div class="btn-group justified">
<a ui-turn-on="aboutus_modal" class="btn btn-navbar"><i class="fal fa-globe"></i> About us</a>
<a ui-turn-on="contactus_overlay" class="btn btn-navbar"><i class="fal fa-map-marker-alt"></i> Contact us</a>
</div>
</div>
<!-- App body -->
<div class='app-body'>
<div class='app-content'>
<ng-view></ng-view>
</div>
</div>
</div><!-- ~ .app -->
<!-- Modals and Overlays -->
<div ui-yield-to="modals"></div>
</body>
</html>
/* eslint no-alert: 0 */
'use strict';
//
// Here is how to define your module
// has dependent on mobile-angular-ui
//
var app=angular.module('myFirstApp', [
'ngRoute',
'mobile-angular-ui'
]);
app.config(function($routeProvider, $locationProvider) {
$routeProvider
.when("/", {
templateUrl : "src/home/home.html"
});
$locationProvider.html5Mode({enabled:true, requireBase:false});
});
app.controller('MainController', function($rootScope, $scope, $routeParams) {
$scope.msg="Welcome to Tutorialspoint!"
$scope.sections="Testing of Accordion using
Mobile Angular UI!Testing of Accordion using
Mobile Angular UI!Testing of Accordion using
Mobile Angular UI!";
});
The accordion template is added inside src/home/home.html.
<div class="scrollable">
<div class="scrollable-content">
<div class="section">
<div class="panel-group"
ui-shared-state="testAccordion"
ui-default='2'>
<div class="panel panel-default" ng-repeat="i in [1,2,3,4,5]">
<div class="panel-heading" ui-set="{'testAccordion': i}">
<h4 class="panel-title">
Accordion Group Item #{{i}}
</h4>
</div>
<div ui-if="testAccordion == {{i}}">
<div class="panel-body">
{{sections}}
</div>
</div>
</div>
</div>
</div>
</div>
</div>
Following is the display in the browser −
28 Lectures
3 hours
Asif Hussain
19 Lectures
5.5 hours
Eduonix Learning Solutions
30 Lectures
3.5 hours
Abhilash Nelson
16 Lectures
2.5 hours
Frahaan Hussain
62 Lectures
4.5 hours
Senol Atac
22 Lectures
3 hours
Sandip Bhattacharya
Print
Add Notes
Bookmark this page | [
{
"code": null,
"e": 2506,
"s": 2311,
"text": "Accordions are mostly used when the content is supposed to be in section type of view and any one section is visible at a time. You can hide and open the next section to view the contents in it."
},
{
"code": null,
"e": 2589,
"s": 2506,
"text": "Let us work on an example to see the working of an Accordion in Mobile Angular UI."
},
{
"code": null,
"e": 6968,
"s": 2589,
"text": "<!DOCTYPE html>\n<html>\n <head>\n <meta charset=\"utf-8\" />\n <title>Mobile Angular UI Demo</title>\n <meta http-equiv=\"X-UA-Compatible\" content=\"IE=edge,chrome=1\" />\n <meta name=\"apple-mobile-web-app-capable\" content=\"yes\" />\n <meta name=\"viewport\" content=\"user-scalable=no, initial-scale=1.0, maximum-scale=1.0, minimal-ui\" />\n <meta name=\"apple-mobile-web-app-status-bar-style\" content=\"yes\" />\n <link rel=\"shortcut icon\" href=\"/assets/img/favicon.png\" type=\"image/x-icon\" />\n <link rel=\"stylesheet\" href=\"node_modules/mobile-angular-ui/dist/css/mobile-angular-ui-hover.min.css\" />\n <link rel=\"stylesheet\" href=\"node_modules/mobile-angular-ui/dist/css/mobile-angular-ui-base.min.css\" />\n <link rel=\"stylesheet\" href=\"node_modules/mobile-angular-ui/dist/css/mobile-angular-ui-desktop.min.css\" />\n <script src=\"node_modules/angular/angular.min.js\"></script>\n <script src=\"node_modules/angular-route/angular-route.min.js\"></script>\n <script src=\"node_modules/mobile-angular-ui/dist/js/mobile-angular-ui.min.js\"></script>\n <script src=\"node_modules/angular-route/angular-route.min.js\"></script>\n <link rel=\"stylesheet\" href=\"src/css/app.css\" />\n <script src=\"src/js/app.js\"></script>\n </head>\n <body ng-app=\"myFirstApp\" ng-controller=\"MainController\">\n <!-- Sidebars -->\n <div class=\"sidebar sidebar-left\">\n <div class=\"scrollable\">\n <h1 class=\"scrollable-header app-name\">Tutorials</h1>\n <div class=\"scrollable-content\">\n <div class=\"list-group\" ui-turn-off='uiSidebarLeft'>\n <a class=\"list-group-item\" href=\"/\">Home Page </a>\n <a class=\"list-group-item\" href=\"#/academic\"><i class=\"fa fa-caret-right\"></i>Academic Tutorials </a>\n <a class=\"list-group-item\" href=\"#/bigdata\"><i class=\"fa fa-caret-right\"></i>Big Data & Analytics </a>\n <a class=\"list-group-item\" href=\"#/computerProg\"><i class=\"fa fa-caret-right\"></i>Computer Programming </a>\n <a class=\"list-group-item\" href=\"#/computerscience\"><i class=\"fa fa-caret-right\"></i>Computer Science </a>\n <a class=\"list-group-item\" href=\"#/databases\"><i class=\"fa fa-caret-right\"></i>Databases </a>\n <a class=\"list-group-item\" href=\"#/devops\"><i class=\"fa fa-caret-right\"></i>DevOps </a>\n </div>\n </div>\n </div>\n </div>\n <div class=\"sidebar sidebar-right\">\n <div class=\"scrollable\">\n <h1 class=\"scrollable-header app-name\">eBooks</h1>\n <div class=\"scrollable-content\">\n <div class=\"list-group\" ui-toggle=\"uiSidebarRight\">\n <a class=\"list-group-item\" href=\"#/php\"><i class=\"fa fa-caret-right\"></i>PHP </a>\n <a class=\"list-group-item\" href=\"#/Javascript\"><i class=\"fa fa-caret-right\"></i>Javascript </a>\n </div>\n </div>\n </div>\n </div>\n \n <div class=\"app\">\n <div class=\"navbar navbar-app navbar-absolute-top\">\n <div class=\"navbar-brand navbar-brand-center\" ui-yield-to=\"title\">\n TutorialsPoint\n </div>\n <div class=\"btn-group pull-left\">\n <div ui-toggle=\"uiSidebarLeft\" class=\"btn sidebar-left-toggle\">\n <i class=\"fa fa-th-large \"></i> Tutorials\n </div>\n </div>\n <div class=\"btn-group pull-right\" ui-yield-to=\"navbarAction\">\n <div ui-toggle=\"uiSidebarRight\" class=\"btn sidebar-right-toggle\">\n <i class=\"fal fa-search\"></i> eBooks\n </div>\n </div>\n </div>\n <div class=\"navbar navbar-app navbar-absolute-bottom\">\n <div class=\"btn-group justified\">\n <a ui-turn-on=\"aboutus_modal\" class=\"btn btn-navbar\"><i class=\"fal fa-globe\"></i> About us</a>\n <a ui-turn-on=\"contactus_overlay\" class=\"btn btn-navbar\"><i class=\"fal fa-map-marker-alt\"></i> Contact us</a>\n </div>\n </div>\n\n <!-- App body -->\n <div class='app-body'>\n <div class='app-content'>\n <ng-view></ng-view>\n </div>\n </div>\n </div><!-- ~ .app -->\n\n <!-- Modals and Overlays -->\n <div ui-yield-to=\"modals\"></div>\n </body>\n</html>"
},
{
"code": null,
"e": 7677,
"s": 6968,
"text": "/* eslint no-alert: 0 */\n\n'use strict';\n\n//\n// Here is how to define your module\n// has dependent on mobile-angular-ui\n//\nvar app=angular.module('myFirstApp', [\n 'ngRoute',\n 'mobile-angular-ui'\n]);\napp.config(function($routeProvider, $locationProvider) {\n $routeProvider\n .when(\"/\", {\n templateUrl : \"src/home/home.html\"\n });\n $locationProvider.html5Mode({enabled:true, requireBase:false});\n});\n\napp.controller('MainController', function($rootScope, $scope, $routeParams) {\n $scope.msg=\"Welcome to Tutorialspoint!\"\n $scope.sections=\"Testing of Accordion using \n Mobile Angular UI!Testing of Accordion using \n Mobile Angular UI!Testing of Accordion using \n Mobile Angular UI!\";\n});\n"
},
{
"code": null,
"e": 7736,
"s": 7677,
"text": "The accordion template is added inside src/home/home.html."
},
{
"code": null,
"e": 8396,
"s": 7736,
"text": "<div class=\"scrollable\">\n <div class=\"scrollable-content\">\n <div class=\"section\">\n <div class=\"panel-group\"\n ui-shared-state=\"testAccordion\"\n ui-default='2'>\n \n <div class=\"panel panel-default\" ng-repeat=\"i in [1,2,3,4,5]\">\n <div class=\"panel-heading\" ui-set=\"{'testAccordion': i}\">\n\n <h4 class=\"panel-title\">\n Accordion Group Item #{{i}}\n </h4>\n </div>\n \n <div ui-if=\"testAccordion == {{i}}\">\n <div class=\"panel-body\">\n {{sections}}\n </div>\n </div>\n </div>\n </div>\n </div>\n</div>\n</div>\n"
},
{
"code": null,
"e": 8438,
"s": 8396,
"text": "Following is the display in the browser −"
},
{
"code": null,
"e": 8471,
"s": 8438,
"text": "\n 28 Lectures \n 3 hours \n"
},
{
"code": null,
"e": 8485,
"s": 8471,
"text": " Asif Hussain"
},
{
"code": null,
"e": 8520,
"s": 8485,
"text": "\n 19 Lectures \n 5.5 hours \n"
},
{
"code": null,
"e": 8548,
"s": 8520,
"text": " Eduonix Learning Solutions"
},
{
"code": null,
"e": 8583,
"s": 8548,
"text": "\n 30 Lectures \n 3.5 hours \n"
},
{
"code": null,
"e": 8600,
"s": 8583,
"text": " Abhilash Nelson"
},
{
"code": null,
"e": 8635,
"s": 8600,
"text": "\n 16 Lectures \n 2.5 hours \n"
},
{
"code": null,
"e": 8652,
"s": 8635,
"text": " Frahaan Hussain"
},
{
"code": null,
"e": 8687,
"s": 8652,
"text": "\n 62 Lectures \n 4.5 hours \n"
},
{
"code": null,
"e": 8699,
"s": 8687,
"text": " Senol Atac"
},
{
"code": null,
"e": 8732,
"s": 8699,
"text": "\n 22 Lectures \n 3 hours \n"
},
{
"code": null,
"e": 8753,
"s": 8732,
"text": " Sandip Bhattacharya"
},
{
"code": null,
"e": 8760,
"s": 8753,
"text": " Print"
},
{
"code": null,
"e": 8771,
"s": 8760,
"text": " Add Notes"
}
] |
Displaying distinct values in a column filtered on other column in SAP BO report | There are multiple ways to do this. First is by creating a variable like this:
Terms Count =Count([Terms Code]) in ([Sales #])
You have to add this variable to your report. It will display 1 for all Sales # 1000 and 2 for all Sales # 1001. You can apply a filter on Count > 1.
You can also do this using PREVIOUS() function as below:
Previous([Payment Terms Code]; ([Sales #];[Line #])) | [
{
"code": null,
"e": 1141,
"s": 1062,
"text": "There are multiple ways to do this. First is by creating a variable like this:"
},
{
"code": null,
"e": 1189,
"s": 1141,
"text": "Terms Count =Count([Terms Code]) in ([Sales #])"
},
{
"code": null,
"e": 1339,
"s": 1189,
"text": "You have to add this variable to your report. It will display 1 for all Sales # 1000 and 2 for all Sales # 1001. You can apply a filter on Count > 1."
},
{
"code": null,
"e": 1396,
"s": 1339,
"text": "You can also do this using PREVIOUS() function as below:"
},
{
"code": null,
"e": 1449,
"s": 1396,
"text": "Previous([Payment Terms Code]; ([Sales #];[Line #]))"
}
] |
C# | Remove() Method - GeeksforGeeks | 31 Jan, 2019
In C#, Remove() method is a String Method. It is used for removing all the characters from the specified position of a string. If the length is not specified, then it will remove all the characters after specified position. This method can be overloaded by changing the number of arguments passed to it.
Syntax:
public string Remove(int StartIndex)
or
public string Remove(int StartIndex, int count)
Explanation:public string Remove(int StartIndex) method will take a single parameter which is the starting index or we can say the specified position from where it will start to remove characters from the current String object. And this method will continue to remove the characters till the end of the current string object.
public string Remove(int StartIndex, int count) method will take two arguments i.e first is start position of specified string and the second one is the number of characters to be removed. The return type value of both the methods is System.String.
Exceptions: There can be two cases where exception ArgumentOutOfRangeException may occur are as follows:
Either StartIndex or (StartIndex + count) indicates a position which may outside the current string object.
StartIndex or count is less than zero.
Below are the programs to demonstrate the above Methods :
Example 1: Program to demonstrate the public string Remove(int StartIndex) method. The Remove method will removes all the characters from the specified index till the end of the string.// C# program to illustrate the// public string Remove(int StartIndex)using System; class Geeks { // Main Method public static void Main() { // define string String str = "GeeksForGeeks"; Console.WriteLine("Given String : " + str); // delete from index 5 to end of string Console.WriteLine("New String1 : " + str.Remove(5)); // delete character from index 8 to end of string Console.WriteLine("New String2 : " + str.Remove(8)); }}Output:Given String : GeeksForGeeks
New String1 : Geeks
New String2 : GeeksFor
// C# program to illustrate the// public string Remove(int StartIndex)using System; class Geeks { // Main Method public static void Main() { // define string String str = "GeeksForGeeks"; Console.WriteLine("Given String : " + str); // delete from index 5 to end of string Console.WriteLine("New String1 : " + str.Remove(5)); // delete character from index 8 to end of string Console.WriteLine("New String2 : " + str.Remove(8)); }}
Given String : GeeksForGeeks
New String1 : Geeks
New String2 : GeeksFor
Example 2: Program to demonstrate the public string Remove(int StartIndex, int count) method. This method will remove the characters from the specified index to specified index + (count – 1) of the string where count is the number of the characters to be removed.// C# program to illustrate the// public string Remove(int StartIndex, int count)using System; class Geeks { // Main Method public static void Main() { // original string String str = "GeeksForGeeks"; Console.WriteLine("Given String : " + str); // delete the string from index 2 to length 4 Console.WriteLine("New String1 : " + str.Remove(2, 4)); // delete the string from index 5 to length 3 Console.WriteLine("New String2 : " + str.Remove(5, 3)); }}Output:Given String : GeeksForGeeks
New String1 : GeorGeeks
New String2 : GeeksGeeks
// C# program to illustrate the// public string Remove(int StartIndex, int count)using System; class Geeks { // Main Method public static void Main() { // original string String str = "GeeksForGeeks"; Console.WriteLine("Given String : " + str); // delete the string from index 2 to length 4 Console.WriteLine("New String1 : " + str.Remove(2, 4)); // delete the string from index 5 to length 3 Console.WriteLine("New String2 : " + str.Remove(5, 3)); }}
Given String : GeeksForGeeks
New String1 : GeorGeeks
New String2 : GeeksGeeks
Important Point to Remember:
Both above methods do not modify the value of the current string object. Instead, they return a new modified string.
If StartIndex is equal to the length of string and length is zero, the method will not remove any character from the string.
References:https://msdn.microsoft.com/en-us/library/system.string.remove1
https://msdn.microsoft.com/en-us/library/system.string.remove2
CSharp-method
CSharp-string
C#
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
C# | Method Overriding
C# Dictionary with examples
Difference between Ref and Out keywords in C#
C# | Constructors
C# | Class and Object
C# | Delegates
Introduction to .NET Framework
Extension Method in C#
C# | Abstract Classes
C# | Data Types | [
{
"code": null,
"e": 24436,
"s": 24408,
"text": "\n31 Jan, 2019"
},
{
"code": null,
"e": 24740,
"s": 24436,
"text": "In C#, Remove() method is a String Method. It is used for removing all the characters from the specified position of a string. If the length is not specified, then it will remove all the characters after specified position. This method can be overloaded by changing the number of arguments passed to it."
},
{
"code": null,
"e": 24748,
"s": 24740,
"text": "Syntax:"
},
{
"code": null,
"e": 24841,
"s": 24748,
"text": "public string Remove(int StartIndex) \nor\npublic string Remove(int StartIndex, int count) \n"
},
{
"code": null,
"e": 25167,
"s": 24841,
"text": "Explanation:public string Remove(int StartIndex) method will take a single parameter which is the starting index or we can say the specified position from where it will start to remove characters from the current String object. And this method will continue to remove the characters till the end of the current string object."
},
{
"code": null,
"e": 25416,
"s": 25167,
"text": "public string Remove(int StartIndex, int count) method will take two arguments i.e first is start position of specified string and the second one is the number of characters to be removed. The return type value of both the methods is System.String."
},
{
"code": null,
"e": 25521,
"s": 25416,
"text": "Exceptions: There can be two cases where exception ArgumentOutOfRangeException may occur are as follows:"
},
{
"code": null,
"e": 25629,
"s": 25521,
"text": "Either StartIndex or (StartIndex + count) indicates a position which may outside the current string object."
},
{
"code": null,
"e": 25668,
"s": 25629,
"text": "StartIndex or count is less than zero."
},
{
"code": null,
"e": 25726,
"s": 25668,
"text": "Below are the programs to demonstrate the above Methods :"
},
{
"code": null,
"e": 26493,
"s": 25726,
"text": "Example 1: Program to demonstrate the public string Remove(int StartIndex) method. The Remove method will removes all the characters from the specified index till the end of the string.// C# program to illustrate the// public string Remove(int StartIndex)using System; class Geeks { // Main Method public static void Main() { // define string String str = \"GeeksForGeeks\"; Console.WriteLine(\"Given String : \" + str); // delete from index 5 to end of string Console.WriteLine(\"New String1 : \" + str.Remove(5)); // delete character from index 8 to end of string Console.WriteLine(\"New String2 : \" + str.Remove(8)); }}Output:Given String : GeeksForGeeks\nNew String1 : Geeks\nNew String2 : GeeksFor\n"
},
{
"code": "// C# program to illustrate the// public string Remove(int StartIndex)using System; class Geeks { // Main Method public static void Main() { // define string String str = \"GeeksForGeeks\"; Console.WriteLine(\"Given String : \" + str); // delete from index 5 to end of string Console.WriteLine(\"New String1 : \" + str.Remove(5)); // delete character from index 8 to end of string Console.WriteLine(\"New String2 : \" + str.Remove(8)); }}",
"e": 26996,
"s": 26493,
"text": null
},
{
"code": null,
"e": 27069,
"s": 26996,
"text": "Given String : GeeksForGeeks\nNew String1 : Geeks\nNew String2 : GeeksFor\n"
},
{
"code": null,
"e": 27941,
"s": 27069,
"text": "Example 2: Program to demonstrate the public string Remove(int StartIndex, int count) method. This method will remove the characters from the specified index to specified index + (count – 1) of the string where count is the number of the characters to be removed.// C# program to illustrate the// public string Remove(int StartIndex, int count)using System; class Geeks { // Main Method public static void Main() { // original string String str = \"GeeksForGeeks\"; Console.WriteLine(\"Given String : \" + str); // delete the string from index 2 to length 4 Console.WriteLine(\"New String1 : \" + str.Remove(2, 4)); // delete the string from index 5 to length 3 Console.WriteLine(\"New String2 : \" + str.Remove(5, 3)); }}Output:Given String : GeeksForGeeks\nNew String1 : GeorGeeks\nNew String2 : GeeksGeeks\n"
},
{
"code": "// C# program to illustrate the// public string Remove(int StartIndex, int count)using System; class Geeks { // Main Method public static void Main() { // original string String str = \"GeeksForGeeks\"; Console.WriteLine(\"Given String : \" + str); // delete the string from index 2 to length 4 Console.WriteLine(\"New String1 : \" + str.Remove(2, 4)); // delete the string from index 5 to length 3 Console.WriteLine(\"New String2 : \" + str.Remove(5, 3)); }}",
"e": 28465,
"s": 27941,
"text": null
},
{
"code": null,
"e": 28544,
"s": 28465,
"text": "Given String : GeeksForGeeks\nNew String1 : GeorGeeks\nNew String2 : GeeksGeeks\n"
},
{
"code": null,
"e": 28573,
"s": 28544,
"text": "Important Point to Remember:"
},
{
"code": null,
"e": 28690,
"s": 28573,
"text": "Both above methods do not modify the value of the current string object. Instead, they return a new modified string."
},
{
"code": null,
"e": 28815,
"s": 28690,
"text": "If StartIndex is equal to the length of string and length is zero, the method will not remove any character from the string."
},
{
"code": null,
"e": 28889,
"s": 28815,
"text": "References:https://msdn.microsoft.com/en-us/library/system.string.remove1"
},
{
"code": null,
"e": 28952,
"s": 28889,
"text": "https://msdn.microsoft.com/en-us/library/system.string.remove2"
},
{
"code": null,
"e": 28966,
"s": 28952,
"text": "CSharp-method"
},
{
"code": null,
"e": 28980,
"s": 28966,
"text": "CSharp-string"
},
{
"code": null,
"e": 28983,
"s": 28980,
"text": "C#"
},
{
"code": null,
"e": 29081,
"s": 28983,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 29104,
"s": 29081,
"text": "C# | Method Overriding"
},
{
"code": null,
"e": 29132,
"s": 29104,
"text": "C# Dictionary with examples"
},
{
"code": null,
"e": 29178,
"s": 29132,
"text": "Difference between Ref and Out keywords in C#"
},
{
"code": null,
"e": 29196,
"s": 29178,
"text": "C# | Constructors"
},
{
"code": null,
"e": 29218,
"s": 29196,
"text": "C# | Class and Object"
},
{
"code": null,
"e": 29233,
"s": 29218,
"text": "C# | Delegates"
},
{
"code": null,
"e": 29264,
"s": 29233,
"text": "Introduction to .NET Framework"
},
{
"code": null,
"e": 29287,
"s": 29264,
"text": "Extension Method in C#"
},
{
"code": null,
"e": 29309,
"s": 29287,
"text": "C# | Abstract Classes"
}
] |
Batch Script - NET STOP/START | This command is used to stop and start a particular service.
Net stop/start [servicename]
NET STOP Spooler
The above command is used to stop the printer spooler service. Following is the output of the above command.
The Print Spooler service is stopping.
The Print Spooler service was stopped successfully.
NET START Spooler
The above command is used to start the printer spooler service. Following is the output of the above command.
The Print Spooler service is starting.
The Print Spooler service was started successfully.
Print
Add Notes
Bookmark this page | [
{
"code": null,
"e": 2230,
"s": 2169,
"text": "This command is used to stop and start a particular service."
},
{
"code": null,
"e": 2260,
"s": 2230,
"text": "Net stop/start [servicename]\n"
},
{
"code": null,
"e": 2277,
"s": 2260,
"text": "NET STOP Spooler"
},
{
"code": null,
"e": 2386,
"s": 2277,
"text": "The above command is used to stop the printer spooler service. Following is the output of the above command."
},
{
"code": null,
"e": 2496,
"s": 2386,
"text": "The Print Spooler service is stopping.\nThe Print Spooler service was stopped successfully.\nNET START Spooler\n"
},
{
"code": null,
"e": 2606,
"s": 2496,
"text": "The above command is used to start the printer spooler service. Following is the output of the above command."
},
{
"code": null,
"e": 2698,
"s": 2606,
"text": "The Print Spooler service is starting.\nThe Print Spooler service was started successfully.\n"
},
{
"code": null,
"e": 2705,
"s": 2698,
"text": " Print"
},
{
"code": null,
"e": 2716,
"s": 2705,
"text": " Add Notes"
}
] |
Python - Merge DataFrames of different length | To merge dataframes of different length, we need to use the merge() method. Let’s say the following is our 1st DataFrame with length 4 −
dataFrame1 = pd.DataFrame(
{
"Car": ['BMW', 'Lexus', 'Audi', 'Jaguar']
}
)
print("DataFrame1 ...\n",dataFrame1)
print("DataFrame1 length = ", len(dataFrame1))
Following is our 2nd DataFrame with length 6 −
dataFrame2 = pd.DataFrame(
{
"Car": ['BMW', 'Lexus', 'Audi', 'Mercedes', 'Jaguar', 'Bentley']
}
)
print("\nDataFrame2 ...\n",dataFrame2) print("DataFrame2 length = ", len(dataFrame2))
Now, merge DataFrames using the merge() −
mergedRes = dataFrame2.merge(dataFrame1, how='left')
Following is the code −
import pandas as pd
# Create DataFrame1
dataFrame1 = pd.DataFrame(
{
"Car": ['BMW', 'Lexus', 'Audi', 'Jaguar']
}
)
print("DataFrame1 ...\n",dataFrame1)
# Find length of DataFrame1
print("DataFrame1 length = ", len(dataFrame1))
# Create DataFrame2
dataFrame2 = pd.DataFrame(
{
"Car": ['BMW', 'Lexus', 'Audi', 'Mercedes', 'Jaguar', 'Bentley']
}
)
print("\nDataFrame2 ...\n",dataFrame2)
# Find length of DataFrame2
print("DataFrame2 length = ", len(dataFrame2))
# merge DataFrames
mergedRes = dataFrame2.merge(dataFrame1, how='left')
print("\nMerged data frame...\n", mergedRes)
This will produce the following output −
DataFrame1 ...
Car
0 BMW
1 Lexus
2 Audi
3 Jaguar
DataFrame1 length = 4
DataFrame2 ...
Car
0 BMW
1 Lexus
2 Audi
3 Mercedes
4 Jaguar
5 Bentley
DataFrame2 length = 6
Merged data frame...
Car
0 BMW
1 Lexus
2 Audi
3 Mercedes
4 Jaguar
5 Bentley | [
{
"code": null,
"e": 1199,
"s": 1062,
"text": "To merge dataframes of different length, we need to use the merge() method. Let’s say the following is our 1st DataFrame with length 4 −"
},
{
"code": null,
"e": 1371,
"s": 1199,
"text": "dataFrame1 = pd.DataFrame(\n {\n \"Car\": ['BMW', 'Lexus', 'Audi', 'Jaguar']\n }\n)\n\nprint(\"DataFrame1 ...\\n\",dataFrame1)\nprint(\"DataFrame1 length = \", len(dataFrame1))"
},
{
"code": null,
"e": 1418,
"s": 1371,
"text": "Following is our 2nd DataFrame with length 6 −"
},
{
"code": null,
"e": 1615,
"s": 1418,
"text": "dataFrame2 = pd.DataFrame(\n {\n \"Car\": ['BMW', 'Lexus', 'Audi', 'Mercedes', 'Jaguar', 'Bentley']\n }\n)\n\nprint(\"\\nDataFrame2 ...\\n\",dataFrame2) print(\"DataFrame2 length = \", len(dataFrame2))"
},
{
"code": null,
"e": 1657,
"s": 1615,
"text": "Now, merge DataFrames using the merge() −"
},
{
"code": null,
"e": 1710,
"s": 1657,
"text": "mergedRes = dataFrame2.merge(dataFrame1, how='left')"
},
{
"code": null,
"e": 1734,
"s": 1710,
"text": "Following is the code −"
},
{
"code": null,
"e": 2334,
"s": 1734,
"text": "import pandas as pd\n# Create DataFrame1\ndataFrame1 = pd.DataFrame(\n {\n \"Car\": ['BMW', 'Lexus', 'Audi', 'Jaguar']\n }\n)\nprint(\"DataFrame1 ...\\n\",dataFrame1)\n# Find length of DataFrame1\nprint(\"DataFrame1 length = \", len(dataFrame1))\n# Create DataFrame2\ndataFrame2 = pd.DataFrame(\n {\n \"Car\": ['BMW', 'Lexus', 'Audi', 'Mercedes', 'Jaguar', 'Bentley']\n }\n)\nprint(\"\\nDataFrame2 ...\\n\",dataFrame2)\n# Find length of DataFrame2\nprint(\"DataFrame2 length = \", len(dataFrame2))\n# merge DataFrames\nmergedRes = dataFrame2.merge(dataFrame1, how='left')\nprint(\"\\nMerged data frame...\\n\", mergedRes)"
},
{
"code": null,
"e": 2375,
"s": 2334,
"text": "This will produce the following output −"
},
{
"code": null,
"e": 2690,
"s": 2375,
"text": "DataFrame1 ...\n Car\n0 BMW\n1 Lexus\n2 Audi\n3 Jaguar\nDataFrame1 length = 4\n\nDataFrame2 ...\n Car\n0 BMW\n1 Lexus\n2 Audi\n3 Mercedes\n4 Jaguar\n5 Bentley\nDataFrame2 length = 6\n\nMerged data frame...\n Car\n0 BMW\n1 Lexus\n2 Audi\n3 Mercedes\n4 Jaguar\n5 Bentley"
}
] |
Solidity - Libraries | Libraries are similar to Contracts but are mainly intended for reuse. A Library contains functions which other contracts can call. Solidity have certain restrictions on use of a Library. Following are the key characteristics of a Solidity Library.
Library functions can be called directly if they do not modify the state. That means pure or view functions only can be called from outside the library.
Library functions can be called directly if they do not modify the state. That means pure or view functions only can be called from outside the library.
Library can not be destroyed as it is assumed to be stateless.
Library can not be destroyed as it is assumed to be stateless.
A Library cannot have state variables.
A Library cannot have state variables.
A Library cannot inherit any element.
A Library cannot inherit any element.
A Library cannot be inherited.
A Library cannot be inherited.
Try the following code to understand how a Library works in Solidity.
pragma solidity ^0.5.0;
library Search {
function indexOf(uint[] storage self, uint value) public view returns (uint) {
for (uint i = 0; i < self.length; i++) if (self[i] == value) return i;
return uint(-1);
}
}
contract Test {
uint[] data;
constructor() public {
data.push(1);
data.push(2);
data.push(3);
data.push(4);
data.push(5);
}
function isValuePresent() external view returns(uint){
uint value = 4;
//search if value is present in the array using Library function
uint index = Search.indexOf(data, value);
return index;
}
}
Run the above program using steps provided in Solidity First Application chapter.
Note − Select Test from dropdown before clicking the deploy button.
0: uint256: 3
The directive using A for B; can be used to attach library functions of library A to a given type B. These functions will used the caller type as their first parameter (identified using self).
Try the following code to understand how a Library works in Solidity.
pragma solidity ^0.5.0;
library Search {
function indexOf(uint[] storage self, uint value) public view returns (uint) {
for (uint i = 0; i < self.length; i++)if (self[i] == value) return i;
return uint(-1);
}
}
contract Test {
using Search for uint[];
uint[] data;
constructor() public {
data.push(1);
data.push(2);
data.push(3);
data.push(4);
data.push(5);
}
function isValuePresent() external view returns(uint){
uint value = 4;
//Now data is representing the Library
uint index = data.indexOf(value);
return index;
}
}
Run the above program using steps provided in Solidity First Application chapter.
Note − Select Test from dropdown before clicking the deploy button.
0: uint256: 3
38 Lectures
4.5 hours
Abhilash Nelson
62 Lectures
8.5 hours
Frahaan Hussain
31 Lectures
3.5 hours
Swapnil Kole
Print
Add Notes
Bookmark this page | [
{
"code": null,
"e": 2803,
"s": 2555,
"text": "Libraries are similar to Contracts but are mainly intended for reuse. A Library contains functions which other contracts can call. Solidity have certain restrictions on use of a Library. Following are the key characteristics of a Solidity Library."
},
{
"code": null,
"e": 2956,
"s": 2803,
"text": "Library functions can be called directly if they do not modify the state. That means pure or view functions only can be called from outside the library."
},
{
"code": null,
"e": 3109,
"s": 2956,
"text": "Library functions can be called directly if they do not modify the state. That means pure or view functions only can be called from outside the library."
},
{
"code": null,
"e": 3172,
"s": 3109,
"text": "Library can not be destroyed as it is assumed to be stateless."
},
{
"code": null,
"e": 3235,
"s": 3172,
"text": "Library can not be destroyed as it is assumed to be stateless."
},
{
"code": null,
"e": 3274,
"s": 3235,
"text": "A Library cannot have state variables."
},
{
"code": null,
"e": 3313,
"s": 3274,
"text": "A Library cannot have state variables."
},
{
"code": null,
"e": 3351,
"s": 3313,
"text": "A Library cannot inherit any element."
},
{
"code": null,
"e": 3389,
"s": 3351,
"text": "A Library cannot inherit any element."
},
{
"code": null,
"e": 3420,
"s": 3389,
"text": "A Library cannot be inherited."
},
{
"code": null,
"e": 3451,
"s": 3420,
"text": "A Library cannot be inherited."
},
{
"code": null,
"e": 3521,
"s": 3451,
"text": "Try the following code to understand how a Library works in Solidity."
},
{
"code": null,
"e": 4148,
"s": 3521,
"text": "pragma solidity ^0.5.0;\n\nlibrary Search {\n function indexOf(uint[] storage self, uint value) public view returns (uint) {\n for (uint i = 0; i < self.length; i++) if (self[i] == value) return i;\n return uint(-1);\n }\n}\ncontract Test {\n uint[] data;\n constructor() public {\n data.push(1);\n data.push(2);\n data.push(3);\n data.push(4);\n data.push(5);\n }\n function isValuePresent() external view returns(uint){\n uint value = 4;\n \n //search if value is present in the array using Library function\n uint index = Search.indexOf(data, value);\n return index;\n }\n}"
},
{
"code": null,
"e": 4230,
"s": 4148,
"text": "Run the above program using steps provided in Solidity First Application chapter."
},
{
"code": null,
"e": 4298,
"s": 4230,
"text": "Note − Select Test from dropdown before clicking the deploy button."
},
{
"code": null,
"e": 4313,
"s": 4298,
"text": "0: uint256: 3\n"
},
{
"code": null,
"e": 4506,
"s": 4313,
"text": "The directive using A for B; can be used to attach library functions of library A to a given type B. These functions will used the caller type as their first parameter (identified using self)."
},
{
"code": null,
"e": 4576,
"s": 4506,
"text": "Try the following code to understand how a Library works in Solidity."
},
{
"code": null,
"e": 5202,
"s": 4576,
"text": "pragma solidity ^0.5.0;\n\nlibrary Search {\n function indexOf(uint[] storage self, uint value) public view returns (uint) {\n for (uint i = 0; i < self.length; i++)if (self[i] == value) return i;\n return uint(-1);\n }\n}\ncontract Test {\n using Search for uint[];\n uint[] data;\n constructor() public {\n data.push(1);\n data.push(2);\n data.push(3);\n data.push(4);\n data.push(5);\n }\n function isValuePresent() external view returns(uint){\n uint value = 4; \n \n //Now data is representing the Library\n uint index = data.indexOf(value);\n return index;\n }\n}"
},
{
"code": null,
"e": 5284,
"s": 5202,
"text": "Run the above program using steps provided in Solidity First Application chapter."
},
{
"code": null,
"e": 5352,
"s": 5284,
"text": "Note − Select Test from dropdown before clicking the deploy button."
},
{
"code": null,
"e": 5367,
"s": 5352,
"text": "0: uint256: 3\n"
},
{
"code": null,
"e": 5402,
"s": 5367,
"text": "\n 38 Lectures \n 4.5 hours \n"
},
{
"code": null,
"e": 5419,
"s": 5402,
"text": " Abhilash Nelson"
},
{
"code": null,
"e": 5454,
"s": 5419,
"text": "\n 62 Lectures \n 8.5 hours \n"
},
{
"code": null,
"e": 5471,
"s": 5454,
"text": " Frahaan Hussain"
},
{
"code": null,
"e": 5506,
"s": 5471,
"text": "\n 31 Lectures \n 3.5 hours \n"
},
{
"code": null,
"e": 5520,
"s": 5506,
"text": " Swapnil Kole"
},
{
"code": null,
"e": 5527,
"s": 5520,
"text": " Print"
},
{
"code": null,
"e": 5538,
"s": 5527,
"text": " Add Notes"
}
] |
YouTube Downloader with Python | Towards Data Science | Hello readers! Today, we will be building a YouTube downloader inPython3 using the PyTube3 library. The original pytube library no longer works and so we need to use the pytube3 library which only works with Python3 and not with Python2.
We will see various things we can do with our Youtube Downloader and the various functionalities it offers to us. So, let’s do it step by step.
First things first, before doing anything else, you need to download the pytube3 library in your system. To do this we will be using python3.
Type in the following command in the CLI to download and install pytube3 in your system.
pip install pytube3
This command will download and install pytube3 in your system.
Now we can start building our YouTube Downloader. Now we need to import the library in our program for using its functionalities.
So, we start our program with the following command:
from pytube import YouTube
You will notice that while we downloaded and installed pytube3 in our system but we are here importing pytube in the code.
To clear up the confusion, pytube3 is also imported by writing pytube only. We do not import it by writing it as pytube3.
Our next step would be to ask the user to provide us with the link to the youtube video which we need to download. The user will then provide us with the link to the video he intends to download.
link = input(“Enter the link: “)yt = YouTube(link)
So, we have accepted input from the user and passed on the link to our YouTube class. It will help us reveal all the information about the video and also will let us download it.
Now, we have the link, we have passed it into the YouTube class. Now, we can play with the link and reveal all sorts of information about the video like its title, number of views, ratings, description, length of the video and various other things.
#Title of videoprint(“Title: “,yt.title)#Number of views of videoprint(“Number of views: “,yt.views)#Length of the videoprint(“Length of video: “,yt.length,”seconds”)#Description of videoprint("Description: ",yt.description)#Ratingprint("Ratings: ",yt.rating)
Now, when we will run this code, we will get to see various details about the video whose link we have fed into the program. Also, there are many more such operations that can be performed which you can find in the official documentation of pytube3.
So, for output purposes, we are not printing descriptions (it’s large), so we are printing the rest four things.
We have used the link for the official trailer of Dark Season 3 here. You can use any link as per your choice.
So, as you can see above, we have printed various details about the show.
You must have seen there are various qualities available for viewing on youtube. So, while downloading using pytube, we also get the options for all streams available.
pytube offers a very easy way to see all the available streams for the link user has provided. So, let’s run the code to view all the streams available for that particular video.
#printing all the available streamsprint(yt.streams)
On running the above code, we get all the available streams for that video. Below is the output generated:
Now, you may be seeing both video and audio streams available. So, you can also filter out only audio or video streams. You can also filter out streams based on the file format. We can also filter out progressive and Dash streams (will talk about them in a second).
So, let’s filter out audio-only streams. To do so, we need to write code as such:
print(yt.streams.filter(only_audio=True))
The output we will get is as such:
Now, let’s filter out video-only streams. It will show us only the streams which contain video but no audio. So, it will also filter out all the progressive streams. For that, we will write as such:
print(yt.streams.filter(only_video=True))
The output we will get is as such:
Now, let’s talk about Progressive v/s Dash streams. YouTube uses Dash streams for higher-quality rendering.
Progressive streams are limited to 720p and contain both audio and video codec files while Dash streams have higher quality but only have video codecs.
So, if we want to download a progressive stream, we will get a ready to play video which also has built-in audio.
But, for the higher quality, we should use Dash streams for video and should also download an audio stream and then later merge them using any mixing tool.
So, for this article, we will be using progressive stream download to get ready to play videos. You are free to choose your quality of download and choice of stream.
So, let’s filter out progressive streams first. The code below will do it for us:
print(yt.streams.filter(progressive=True))
It will list the progressive streams available for download to us. It will have limited options but it does the work for us. The output will look like this:
To get the highest resolution progressive stream available, we can just write the code below:
ys = yt.streams.get_highest_resolution()
This will create store the highest resolution stream in the ys variable.
We can also choose any stream with the help of its itag.
ys = yt.streams.get_by_itag('22')
So, now we have stored our preferred stream in a variable. Now, let’s download it to our system.
ys.download()
The above code will download our preferred stream and save it in the current working directory.
We can also specify the location in our system where we want to download the youtube video. We can do so by specifying the absolute path in between the braces of download.
The code below helps you to download it in your preferred location.
ys.download('location')
That’s all! Congrats, you have just built your first simple YouTube downloader using Python. Use it for testing and educational purposes only. Do not misuse this knowledge.
Here’s the complete code for downloading a youtube video using the highest quality progressive streams available:
Do visit my Github Repository for more details and updates. I encourage you all to try something new out of this code and then please do share your thoughts and experience in the comments. I would love to hear what you learned and what more you built. All the best everyone!
See, what we built here is a very simple version. We can also try to convert the same concept into an application or a website that would perform the same functions in a user-friendly way. You can also add support for different websites by using their respective APIs. There are many such feature-rich video downloaders out there that use similar concepts and gives the user an option to download videos easily.
One of my favourites is YTSaver which is a feature-rich application to download videos or playlists from tons of websites in different resolutions and formats in one click. It also allows you to convert videos from one format to another and is much faster than some other downloaders out there.
Note: The above paragraph contains an affiliate link.
Actually, you can also use Python libraries like this one to convert videos from one format to another. You can also try to do that if you are interested. Thank you very much for reading!
More stories to read after finishing this one are:- | [
{
"code": null,
"e": 410,
"s": 172,
"text": "Hello readers! Today, we will be building a YouTube downloader inPython3 using the PyTube3 library. The original pytube library no longer works and so we need to use the pytube3 library which only works with Python3 and not with Python2."
},
{
"code": null,
"e": 554,
"s": 410,
"text": "We will see various things we can do with our Youtube Downloader and the various functionalities it offers to us. So, let’s do it step by step."
},
{
"code": null,
"e": 696,
"s": 554,
"text": "First things first, before doing anything else, you need to download the pytube3 library in your system. To do this we will be using python3."
},
{
"code": null,
"e": 785,
"s": 696,
"text": "Type in the following command in the CLI to download and install pytube3 in your system."
},
{
"code": null,
"e": 805,
"s": 785,
"text": "pip install pytube3"
},
{
"code": null,
"e": 868,
"s": 805,
"text": "This command will download and install pytube3 in your system."
},
{
"code": null,
"e": 998,
"s": 868,
"text": "Now we can start building our YouTube Downloader. Now we need to import the library in our program for using its functionalities."
},
{
"code": null,
"e": 1051,
"s": 998,
"text": "So, we start our program with the following command:"
},
{
"code": null,
"e": 1078,
"s": 1051,
"text": "from pytube import YouTube"
},
{
"code": null,
"e": 1201,
"s": 1078,
"text": "You will notice that while we downloaded and installed pytube3 in our system but we are here importing pytube in the code."
},
{
"code": null,
"e": 1323,
"s": 1201,
"text": "To clear up the confusion, pytube3 is also imported by writing pytube only. We do not import it by writing it as pytube3."
},
{
"code": null,
"e": 1519,
"s": 1323,
"text": "Our next step would be to ask the user to provide us with the link to the youtube video which we need to download. The user will then provide us with the link to the video he intends to download."
},
{
"code": null,
"e": 1570,
"s": 1519,
"text": "link = input(“Enter the link: “)yt = YouTube(link)"
},
{
"code": null,
"e": 1749,
"s": 1570,
"text": "So, we have accepted input from the user and passed on the link to our YouTube class. It will help us reveal all the information about the video and also will let us download it."
},
{
"code": null,
"e": 1998,
"s": 1749,
"text": "Now, we have the link, we have passed it into the YouTube class. Now, we can play with the link and reveal all sorts of information about the video like its title, number of views, ratings, description, length of the video and various other things."
},
{
"code": null,
"e": 2258,
"s": 1998,
"text": "#Title of videoprint(“Title: “,yt.title)#Number of views of videoprint(“Number of views: “,yt.views)#Length of the videoprint(“Length of video: “,yt.length,”seconds”)#Description of videoprint(\"Description: \",yt.description)#Ratingprint(\"Ratings: \",yt.rating)"
},
{
"code": null,
"e": 2508,
"s": 2258,
"text": "Now, when we will run this code, we will get to see various details about the video whose link we have fed into the program. Also, there are many more such operations that can be performed which you can find in the official documentation of pytube3."
},
{
"code": null,
"e": 2621,
"s": 2508,
"text": "So, for output purposes, we are not printing descriptions (it’s large), so we are printing the rest four things."
},
{
"code": null,
"e": 2732,
"s": 2621,
"text": "We have used the link for the official trailer of Dark Season 3 here. You can use any link as per your choice."
},
{
"code": null,
"e": 2806,
"s": 2732,
"text": "So, as you can see above, we have printed various details about the show."
},
{
"code": null,
"e": 2974,
"s": 2806,
"text": "You must have seen there are various qualities available for viewing on youtube. So, while downloading using pytube, we also get the options for all streams available."
},
{
"code": null,
"e": 3153,
"s": 2974,
"text": "pytube offers a very easy way to see all the available streams for the link user has provided. So, let’s run the code to view all the streams available for that particular video."
},
{
"code": null,
"e": 3206,
"s": 3153,
"text": "#printing all the available streamsprint(yt.streams)"
},
{
"code": null,
"e": 3313,
"s": 3206,
"text": "On running the above code, we get all the available streams for that video. Below is the output generated:"
},
{
"code": null,
"e": 3579,
"s": 3313,
"text": "Now, you may be seeing both video and audio streams available. So, you can also filter out only audio or video streams. You can also filter out streams based on the file format. We can also filter out progressive and Dash streams (will talk about them in a second)."
},
{
"code": null,
"e": 3661,
"s": 3579,
"text": "So, let’s filter out audio-only streams. To do so, we need to write code as such:"
},
{
"code": null,
"e": 3703,
"s": 3661,
"text": "print(yt.streams.filter(only_audio=True))"
},
{
"code": null,
"e": 3738,
"s": 3703,
"text": "The output we will get is as such:"
},
{
"code": null,
"e": 3937,
"s": 3738,
"text": "Now, let’s filter out video-only streams. It will show us only the streams which contain video but no audio. So, it will also filter out all the progressive streams. For that, we will write as such:"
},
{
"code": null,
"e": 3979,
"s": 3937,
"text": "print(yt.streams.filter(only_video=True))"
},
{
"code": null,
"e": 4014,
"s": 3979,
"text": "The output we will get is as such:"
},
{
"code": null,
"e": 4122,
"s": 4014,
"text": "Now, let’s talk about Progressive v/s Dash streams. YouTube uses Dash streams for higher-quality rendering."
},
{
"code": null,
"e": 4274,
"s": 4122,
"text": "Progressive streams are limited to 720p and contain both audio and video codec files while Dash streams have higher quality but only have video codecs."
},
{
"code": null,
"e": 4388,
"s": 4274,
"text": "So, if we want to download a progressive stream, we will get a ready to play video which also has built-in audio."
},
{
"code": null,
"e": 4544,
"s": 4388,
"text": "But, for the higher quality, we should use Dash streams for video and should also download an audio stream and then later merge them using any mixing tool."
},
{
"code": null,
"e": 4710,
"s": 4544,
"text": "So, for this article, we will be using progressive stream download to get ready to play videos. You are free to choose your quality of download and choice of stream."
},
{
"code": null,
"e": 4792,
"s": 4710,
"text": "So, let’s filter out progressive streams first. The code below will do it for us:"
},
{
"code": null,
"e": 4835,
"s": 4792,
"text": "print(yt.streams.filter(progressive=True))"
},
{
"code": null,
"e": 4992,
"s": 4835,
"text": "It will list the progressive streams available for download to us. It will have limited options but it does the work for us. The output will look like this:"
},
{
"code": null,
"e": 5086,
"s": 4992,
"text": "To get the highest resolution progressive stream available, we can just write the code below:"
},
{
"code": null,
"e": 5127,
"s": 5086,
"text": "ys = yt.streams.get_highest_resolution()"
},
{
"code": null,
"e": 5200,
"s": 5127,
"text": "This will create store the highest resolution stream in the ys variable."
},
{
"code": null,
"e": 5257,
"s": 5200,
"text": "We can also choose any stream with the help of its itag."
},
{
"code": null,
"e": 5291,
"s": 5257,
"text": "ys = yt.streams.get_by_itag('22')"
},
{
"code": null,
"e": 5388,
"s": 5291,
"text": "So, now we have stored our preferred stream in a variable. Now, let’s download it to our system."
},
{
"code": null,
"e": 5402,
"s": 5388,
"text": "ys.download()"
},
{
"code": null,
"e": 5498,
"s": 5402,
"text": "The above code will download our preferred stream and save it in the current working directory."
},
{
"code": null,
"e": 5670,
"s": 5498,
"text": "We can also specify the location in our system where we want to download the youtube video. We can do so by specifying the absolute path in between the braces of download."
},
{
"code": null,
"e": 5738,
"s": 5670,
"text": "The code below helps you to download it in your preferred location."
},
{
"code": null,
"e": 5762,
"s": 5738,
"text": "ys.download('location')"
},
{
"code": null,
"e": 5935,
"s": 5762,
"text": "That’s all! Congrats, you have just built your first simple YouTube downloader using Python. Use it for testing and educational purposes only. Do not misuse this knowledge."
},
{
"code": null,
"e": 6049,
"s": 5935,
"text": "Here’s the complete code for downloading a youtube video using the highest quality progressive streams available:"
},
{
"code": null,
"e": 6324,
"s": 6049,
"text": "Do visit my Github Repository for more details and updates. I encourage you all to try something new out of this code and then please do share your thoughts and experience in the comments. I would love to hear what you learned and what more you built. All the best everyone!"
},
{
"code": null,
"e": 6736,
"s": 6324,
"text": "See, what we built here is a very simple version. We can also try to convert the same concept into an application or a website that would perform the same functions in a user-friendly way. You can also add support for different websites by using their respective APIs. There are many such feature-rich video downloaders out there that use similar concepts and gives the user an option to download videos easily."
},
{
"code": null,
"e": 7031,
"s": 6736,
"text": "One of my favourites is YTSaver which is a feature-rich application to download videos or playlists from tons of websites in different resolutions and formats in one click. It also allows you to convert videos from one format to another and is much faster than some other downloaders out there."
},
{
"code": null,
"e": 7085,
"s": 7031,
"text": "Note: The above paragraph contains an affiliate link."
},
{
"code": null,
"e": 7273,
"s": 7085,
"text": "Actually, you can also use Python libraries like this one to convert videos from one format to another. You can also try to do that if you are interested. Thank you very much for reading!"
}
] |
Count of subsets having maximum possible XOR value - GeeksforGeeks | 17 Jan, 2022
Given an array arr[] consisting of N positive integers. The task is to count the number of different non-empty subsets of arr[] having maximum bitwise XOR.
Examples:
Input: arr[] = {3, 1}Output: 1Explanation: The maximum possible bitwise XOR of a subset is 3. In arr[] there is only one subset with bitwise XOR as 3 which is {3}.Therefore, 1 is the answer.
Input: arr[] = {3, 2, 1, 5}Output: 2
Approach: This problem can be solved by using Bit Masking. Follow the steps below to solve the given problem.
Initialize a variable say maxXorVal = 0, to store the maximum possible bitwise XOR of a subset in arr[].
Traverse the array arr[] to find the value of maxXorVal.
Initialize a variable say countSubsets = 0, to count the number of subsets with maximum bitwise XOR.
After that count the number of subsets with the value maxXorVal.
Return countSubsets as the final answer.
Below is the implementation of the above approach.
C++
Java
Python3
C#
Javascript
// C++ program for above approach#include <bits/stdc++.h>using namespace std; // Function to find subsets having maximum XORint countMaxOrSubsets(vector<int>& nums){ // Store the size of arr[] long long n = nums.size(); // To store maximum possible // bitwise XOR subset in arr[] long long maxXorVal = 0; // Find the maximum bitwise xor value for (int i = 0; i < (1 << n); i++) { long long xorVal = 0; for (int j = 0; j < n; j++) { if (i & (1 << j)) { xorVal = (xorVal ^ nums[j]); } } // Take maximum of each value maxXorVal = max(maxXorVal, xorVal); } // Count the number // of subsets having bitwise // XOR value as maxXorVal long long count = 0; for (int i = 0; i < (1 << n); i++) { long long val = 0; for (int j = 0; j < n; j++) { if (i & (1 << j)) { val = (val ^ nums[j]); } } if (val == maxXorVal) { count++; } } return count;} // Driver Codeint main(){ int N = 4; vector<int> arr = { 3, 2, 1, 5 }; // Print the answer cout << countMaxOrSubsets(arr); return 0;}
// Java program for above approachimport java.util.*; public class GFG{ // Function to find subsets having maximum XORstatic int countMaxOrSubsets(int []nums){ // Store the size of arr[] long n = nums.length; // To store maximum possible // bitwise XOR subset in arr[] long maxXorVal = 0; // Find the maximum bitwise xor value for (int i = 0; i < (1 << n); i++) { long xorVal = 0; for (int j = 0; j < n; j++) { if ((i & (1 << j)) == 0) { xorVal = (xorVal ^ nums[j]); } } // Take maximum of each value maxXorVal = Math.max(maxXorVal, xorVal); } // Count the number // of subsets having bitwise // XOR value as maxXorVal long count = 0; for (int i = 0; i < (1 << n); i++) { long val = 0; for (int j = 0; j < n; j++) { if ((i & (1 << j)) == 0) { val = (val ^ nums[j]); } } if (val == maxXorVal) { count++; } } return (int)count;} // Driver Codepublic static void main(String args[]){ int N = 4; int []arr = { 3, 2, 1, 5 }; // Print the answer System.out.print(countMaxOrSubsets(arr));}} // This code is contributed by Samim Hossain Mondal.
# Python program for above approach # Function to find subsets having maximum XORdef countMaxOrSubsets(nums): # Store the size of arr[] n = len(nums) # To store maximum possible # bitwise XOR subset in arr[] maxXorVal = 0 # Find the maximum bitwise xor value for i in range(0, (1 << n)): xorVal = 0 for j in range(0, n): if (i & (1 << j)): xorVal = (xorVal ^ nums[j]) # Take maximum of each value maxXorVal = max(maxXorVal, xorVal) # Count the number # of subsets having bitwise # XOR value as maxXorVal count = 0 for i in range(0, (1 << n)): val = 0 for j in range(0, n): if (i & (1 << j)): val = (val ^ nums[j]) if (val == maxXorVal): count += 1 return count # Driver Codeif __name__ == "__main__": N = 4 arr = [3, 2, 1, 5] # Print the answer print(countMaxOrSubsets(arr)) # This code is contributed by rakeshsahni
// C# program for above approachusing System; public class GFG{ // Function to find subsets having maximum XORstatic int countMaxOrSubsets(int []nums){ // Store the size of []arr int n = nums.Length; // To store maximum possible // bitwise XOR subset in []arr int maxXorVal = 0; // Find the maximum bitwise xor value for (int i = 0; i < (1 << n); i++) { long xorVal = 0; for (int j = 0; j < n; j++) { if ((i & (1 << j)) == 0) { xorVal = (xorVal ^ nums[j]); } } // Take maximum of each value maxXorVal = (int)Math.Max(maxXorVal, xorVal); } // Count the number // of subsets having bitwise // XOR value as maxXorVal long count = 0; for (int i = 0; i < (1 << n); i++) { long val = 0; for (int j = 0; j < n; j++) { if ((i & (1 << j)) == 0) { val = (val ^ nums[j]); } } if (val == maxXorVal) { count++; } } return (int)count;} // Driver Codepublic static void Main(String []args){ int []arr = { 3, 2, 1, 5 }; // Print the answer Console.Write(countMaxOrSubsets(arr));}} // This code is contributed by 29AjayKumar
<script> // JavaScript program for above approach // Function to find subsets having maximum XORfunction countMaxOrSubsets(nums){ // Store the size of arr[] let n = nums.length; // To store maximum possible // bitwise XOR subset in arr[] let maxXorVal = 0; // Find the maximum bitwise xor value for(let i = 0; i < (1 << n); i++) { let xorVal = 0; for(let j = 0; j < n; j++) { if (i & (1 << j)) { xorVal = (xorVal ^ nums[j]); } } // Take maximum of each value maxXorVal = Math.max(maxXorVal, xorVal); } // Count the number // of subsets having bitwise // XOR value as maxXorVal let count = 0; for(let i = 0; i < (1 << n); i++) { let val = 0; for (let j = 0; j < n; j++) { if (i & (1 << j)) { val = (val ^ nums[j]); } } if (val == maxXorVal) { count++; } } return count;} // Driver Codelet N = 4;let arr = [ 3, 2, 1, 5 ]; // Print the answerdocument.write(countMaxOrSubsets(arr)); // This code is contributed by Potta Lokesh </script>
2
Time Complexity: O(216) Auxiliary Space: O(1)
lokeshpotta20
rakeshsahni
samim2000
29AjayKumar
simmytarika5
Bit Algorithms
Bitwise-XOR
subset
Arrays
Bit Magic
Mathematical
Arrays
Mathematical
Bit Magic
subset
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Window Sliding Technique
Program to find sum of elements in a given array
Move all negative numbers to beginning and positive to end with constant extra space
Reversal algorithm for array rotation
Find duplicates in O(n) time and O(1) extra space | Set 1
Bitwise Operators in C/C++
Left Shift and Right Shift Operators in C/C++
Travelling Salesman Problem | Set 1 (Naive and Dynamic Programming)
Cyclic Redundancy Check and Modulo-2 Division
Count set bits in an integer | [
{
"code": null,
"e": 24796,
"s": 24768,
"text": "\n17 Jan, 2022"
},
{
"code": null,
"e": 24953,
"s": 24796,
"text": "Given an array arr[] consisting of N positive integers. The task is to count the number of different non-empty subsets of arr[] having maximum bitwise XOR. "
},
{
"code": null,
"e": 24964,
"s": 24953,
"text": "Examples: "
},
{
"code": null,
"e": 25156,
"s": 24964,
"text": "Input: arr[] = {3, 1}Output: 1Explanation: The maximum possible bitwise XOR of a subset is 3. In arr[] there is only one subset with bitwise XOR as 3 which is {3}.Therefore, 1 is the answer. "
},
{
"code": null,
"e": 25193,
"s": 25156,
"text": "Input: arr[] = {3, 2, 1, 5}Output: 2"
},
{
"code": null,
"e": 25304,
"s": 25193,
"text": "Approach: This problem can be solved by using Bit Masking. Follow the steps below to solve the given problem. "
},
{
"code": null,
"e": 25409,
"s": 25304,
"text": "Initialize a variable say maxXorVal = 0, to store the maximum possible bitwise XOR of a subset in arr[]."
},
{
"code": null,
"e": 25466,
"s": 25409,
"text": "Traverse the array arr[] to find the value of maxXorVal."
},
{
"code": null,
"e": 25567,
"s": 25466,
"text": "Initialize a variable say countSubsets = 0, to count the number of subsets with maximum bitwise XOR."
},
{
"code": null,
"e": 25632,
"s": 25567,
"text": "After that count the number of subsets with the value maxXorVal."
},
{
"code": null,
"e": 25673,
"s": 25632,
"text": "Return countSubsets as the final answer."
},
{
"code": null,
"e": 25725,
"s": 25673,
"text": "Below is the implementation of the above approach. "
},
{
"code": null,
"e": 25729,
"s": 25725,
"text": "C++"
},
{
"code": null,
"e": 25734,
"s": 25729,
"text": "Java"
},
{
"code": null,
"e": 25742,
"s": 25734,
"text": "Python3"
},
{
"code": null,
"e": 25745,
"s": 25742,
"text": "C#"
},
{
"code": null,
"e": 25756,
"s": 25745,
"text": "Javascript"
},
{
"code": "// C++ program for above approach#include <bits/stdc++.h>using namespace std; // Function to find subsets having maximum XORint countMaxOrSubsets(vector<int>& nums){ // Store the size of arr[] long long n = nums.size(); // To store maximum possible // bitwise XOR subset in arr[] long long maxXorVal = 0; // Find the maximum bitwise xor value for (int i = 0; i < (1 << n); i++) { long long xorVal = 0; for (int j = 0; j < n; j++) { if (i & (1 << j)) { xorVal = (xorVal ^ nums[j]); } } // Take maximum of each value maxXorVal = max(maxXorVal, xorVal); } // Count the number // of subsets having bitwise // XOR value as maxXorVal long long count = 0; for (int i = 0; i < (1 << n); i++) { long long val = 0; for (int j = 0; j < n; j++) { if (i & (1 << j)) { val = (val ^ nums[j]); } } if (val == maxXorVal) { count++; } } return count;} // Driver Codeint main(){ int N = 4; vector<int> arr = { 3, 2, 1, 5 }; // Print the answer cout << countMaxOrSubsets(arr); return 0;}",
"e": 26949,
"s": 25756,
"text": null
},
{
"code": "// Java program for above approachimport java.util.*; public class GFG{ // Function to find subsets having maximum XORstatic int countMaxOrSubsets(int []nums){ // Store the size of arr[] long n = nums.length; // To store maximum possible // bitwise XOR subset in arr[] long maxXorVal = 0; // Find the maximum bitwise xor value for (int i = 0; i < (1 << n); i++) { long xorVal = 0; for (int j = 0; j < n; j++) { if ((i & (1 << j)) == 0) { xorVal = (xorVal ^ nums[j]); } } // Take maximum of each value maxXorVal = Math.max(maxXorVal, xorVal); } // Count the number // of subsets having bitwise // XOR value as maxXorVal long count = 0; for (int i = 0; i < (1 << n); i++) { long val = 0; for (int j = 0; j < n; j++) { if ((i & (1 << j)) == 0) { val = (val ^ nums[j]); } } if (val == maxXorVal) { count++; } } return (int)count;} // Driver Codepublic static void main(String args[]){ int N = 4; int []arr = { 3, 2, 1, 5 }; // Print the answer System.out.print(countMaxOrSubsets(arr));}} // This code is contributed by Samim Hossain Mondal.",
"e": 28209,
"s": 26949,
"text": null
},
{
"code": "# Python program for above approach # Function to find subsets having maximum XORdef countMaxOrSubsets(nums): # Store the size of arr[] n = len(nums) # To store maximum possible # bitwise XOR subset in arr[] maxXorVal = 0 # Find the maximum bitwise xor value for i in range(0, (1 << n)): xorVal = 0 for j in range(0, n): if (i & (1 << j)): xorVal = (xorVal ^ nums[j]) # Take maximum of each value maxXorVal = max(maxXorVal, xorVal) # Count the number # of subsets having bitwise # XOR value as maxXorVal count = 0 for i in range(0, (1 << n)): val = 0 for j in range(0, n): if (i & (1 << j)): val = (val ^ nums[j]) if (val == maxXorVal): count += 1 return count # Driver Codeif __name__ == \"__main__\": N = 4 arr = [3, 2, 1, 5] # Print the answer print(countMaxOrSubsets(arr)) # This code is contributed by rakeshsahni",
"e": 29200,
"s": 28209,
"text": null
},
{
"code": "// C# program for above approachusing System; public class GFG{ // Function to find subsets having maximum XORstatic int countMaxOrSubsets(int []nums){ // Store the size of []arr int n = nums.Length; // To store maximum possible // bitwise XOR subset in []arr int maxXorVal = 0; // Find the maximum bitwise xor value for (int i = 0; i < (1 << n); i++) { long xorVal = 0; for (int j = 0; j < n; j++) { if ((i & (1 << j)) == 0) { xorVal = (xorVal ^ nums[j]); } } // Take maximum of each value maxXorVal = (int)Math.Max(maxXorVal, xorVal); } // Count the number // of subsets having bitwise // XOR value as maxXorVal long count = 0; for (int i = 0; i < (1 << n); i++) { long val = 0; for (int j = 0; j < n; j++) { if ((i & (1 << j)) == 0) { val = (val ^ nums[j]); } } if (val == maxXorVal) { count++; } } return (int)count;} // Driver Codepublic static void Main(String []args){ int []arr = { 3, 2, 1, 5 }; // Print the answer Console.Write(countMaxOrSubsets(arr));}} // This code is contributed by 29AjayKumar",
"e": 30431,
"s": 29200,
"text": null
},
{
"code": "<script> // JavaScript program for above approach // Function to find subsets having maximum XORfunction countMaxOrSubsets(nums){ // Store the size of arr[] let n = nums.length; // To store maximum possible // bitwise XOR subset in arr[] let maxXorVal = 0; // Find the maximum bitwise xor value for(let i = 0; i < (1 << n); i++) { let xorVal = 0; for(let j = 0; j < n; j++) { if (i & (1 << j)) { xorVal = (xorVal ^ nums[j]); } } // Take maximum of each value maxXorVal = Math.max(maxXorVal, xorVal); } // Count the number // of subsets having bitwise // XOR value as maxXorVal let count = 0; for(let i = 0; i < (1 << n); i++) { let val = 0; for (let j = 0; j < n; j++) { if (i & (1 << j)) { val = (val ^ nums[j]); } } if (val == maxXorVal) { count++; } } return count;} // Driver Codelet N = 4;let arr = [ 3, 2, 1, 5 ]; // Print the answerdocument.write(countMaxOrSubsets(arr)); // This code is contributed by Potta Lokesh </script>",
"e": 31624,
"s": 30431,
"text": null
},
{
"code": null,
"e": 31626,
"s": 31624,
"text": "2"
},
{
"code": null,
"e": 31672,
"s": 31626,
"text": "Time Complexity: O(216) Auxiliary Space: O(1)"
},
{
"code": null,
"e": 31686,
"s": 31672,
"text": "lokeshpotta20"
},
{
"code": null,
"e": 31698,
"s": 31686,
"text": "rakeshsahni"
},
{
"code": null,
"e": 31708,
"s": 31698,
"text": "samim2000"
},
{
"code": null,
"e": 31720,
"s": 31708,
"text": "29AjayKumar"
},
{
"code": null,
"e": 31733,
"s": 31720,
"text": "simmytarika5"
},
{
"code": null,
"e": 31748,
"s": 31733,
"text": "Bit Algorithms"
},
{
"code": null,
"e": 31760,
"s": 31748,
"text": "Bitwise-XOR"
},
{
"code": null,
"e": 31767,
"s": 31760,
"text": "subset"
},
{
"code": null,
"e": 31774,
"s": 31767,
"text": "Arrays"
},
{
"code": null,
"e": 31784,
"s": 31774,
"text": "Bit Magic"
},
{
"code": null,
"e": 31797,
"s": 31784,
"text": "Mathematical"
},
{
"code": null,
"e": 31804,
"s": 31797,
"text": "Arrays"
},
{
"code": null,
"e": 31817,
"s": 31804,
"text": "Mathematical"
},
{
"code": null,
"e": 31827,
"s": 31817,
"text": "Bit Magic"
},
{
"code": null,
"e": 31834,
"s": 31827,
"text": "subset"
},
{
"code": null,
"e": 31932,
"s": 31834,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 31941,
"s": 31932,
"text": "Comments"
},
{
"code": null,
"e": 31954,
"s": 31941,
"text": "Old Comments"
},
{
"code": null,
"e": 31979,
"s": 31954,
"text": "Window Sliding Technique"
},
{
"code": null,
"e": 32028,
"s": 31979,
"text": "Program to find sum of elements in a given array"
},
{
"code": null,
"e": 32113,
"s": 32028,
"text": "Move all negative numbers to beginning and positive to end with constant extra space"
},
{
"code": null,
"e": 32151,
"s": 32113,
"text": "Reversal algorithm for array rotation"
},
{
"code": null,
"e": 32209,
"s": 32151,
"text": "Find duplicates in O(n) time and O(1) extra space | Set 1"
},
{
"code": null,
"e": 32236,
"s": 32209,
"text": "Bitwise Operators in C/C++"
},
{
"code": null,
"e": 32282,
"s": 32236,
"text": "Left Shift and Right Shift Operators in C/C++"
},
{
"code": null,
"e": 32350,
"s": 32282,
"text": "Travelling Salesman Problem | Set 1 (Naive and Dynamic Programming)"
},
{
"code": null,
"e": 32396,
"s": 32350,
"text": "Cyclic Redundancy Check and Modulo-2 Division"
}
] |
Find the values of X and Y in the Given Equations - GeeksforGeeks | 15 Apr, 2021
Given two numbers and . Find the values of X and Y in the equations.
A = X + YB = X xor Y
A = X + Y
B = X xor Y
The task is to make X as minimum as possible. If it is not possible to find any valid values for X and Y then print -1.Examples:
Input : A = 12, B = 8
Output : X = 2, Y = 10
Input : A = 12, B = 9
Output : -1
Let’s take a look at some bit in X, which is equal to 1. If the respective bit in Y is equal to 0, then one can swap these two bits, thus reducing X and increasing Y without changing their sum and xor. We can conclude that if some bit in X is equal to 1 then the respective bit in Y is also equal to 1. Thus, Y = X + B. Taking into account that X + Y = X + X + B = A, one can obtain the following formulas for finding X and Y:
X = (A – B) / 2
Y = X + B = (A + B) / 2
One should also notice that if A < B or A and B have different parity, then the answer doesn’t exist and output is -1. If X and (A – X) not equal to X then the answer is also -1.Below is the implementation of the above approach :
C++
Java
Python3
C#
PHP
Javascript
// CPP program to find the values of// X and Y using the given equations #include <bits/stdc++.h>using namespace std; // Function to find the// values of X and Yvoid findValues(int a, int b){ // base condition if ((a - b) % 2 == 1) { cout << "-1"; return; } // required answer cout << (a - b) / 2 << " " << (a + b) / 2;} // Driver Codeint main(){ int a = 12, b = 8; findValues(a, b); return 0;}
// Java program to find the values of// X and Y using the given equationsimport java.io.*; class GFG{ // Function to find the// values of X and Ystatic void findValues(int a, int b){ // base condition if ((a - b) % 2 == 1) { System.out.println ("-1"); return; } // required answer System.out.println (((a - b) / 2)+ " " + ((a + b) / 2));} // Driver Code public static void main (String[] args) { int a = 12, b = 8; findValues(a, b); }} // This code is contributed by ajit...
# Python3 program to find the values of# X and Y using the given equations # Function to find the values of X and Ydef findValues(a, b): # base condition if ((a - b) % 2 == 1): print("-1"); return; # required answer print((a - b) // 2, (a + b) // 2); # Driver Codea = 12; b = 8; findValues(a, b); # This code is contributed# by Akanksha Rai
// C# program to find the values of// X and Y using the given equationsusing System; class GFG{ // Function to find the// values of X and Ystatic void findValues(int a, int b){ // base condition if ((a - b) % 2 == 1) { Console.Write ("-1"); return; } // required answer Console.WriteLine(((a - b) / 2)+ " " + ((a + b) / 2));} // Driver Codestatic public void Main (){ int a = 12, b = 8; findValues(a, b);}} // This code is contributed by @Tushil..
<?php// PHP program to find the values of// X and Y using the given equations // Function to find the values// of X and Yfunction findValues($a, $b){ // base condition if (($a - $b) % 2 == 1) { echo "-1"; return; } // required answer echo ($a - $b) / 2, " " , ($a + $b) / 2;} // Driver Code$a = 12;$b = 8;findValues($a, $b); // This code is contributed by jit_t?>
<script> // Javascript program to find the values of// X and Y using the given equations // Function to find the values// of X and Yfunction findValues(a, b){ // base condition if ((a - b) % 2 == 1) { document.write( "-1"); return; } // required answer document.write( (a - b) / 2+ " " + (a + b) / 2);} // Driver Codelet a = 12;let b = 8;findValues(a, b); // This code is contributed// by bobby </script>
2 10
jit_t
Akanksha_Rai
gottumukkalabobby
math
Bit Magic
Competitive Programming
Mathematical
Mathematical
Bit Magic
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Set, Clear and Toggle a given bit of a number in C
Highest power of 2 less than or equal to given number
Swap bits in a given number
Write an Efficient Method to Check if a Number is Multiple of 3
Check for Integer Overflow
Competitive Programming - A Complete Guide
Practice for cracking any coding interview
Arrow operator -> in C/C++ with Examples
Prefix Sum Array - Implementation and Applications in Competitive Programming
Top 10 Algorithms and Data Structures for Competitive Programming | [
{
"code": null,
"e": 26253,
"s": 26225,
"text": "\n15 Apr, 2021"
},
{
"code": null,
"e": 26324,
"s": 26253,
"text": "Given two numbers and . Find the values of X and Y in the equations. "
},
{
"code": null,
"e": 26345,
"s": 26324,
"text": "A = X + YB = X xor Y"
},
{
"code": null,
"e": 26355,
"s": 26345,
"text": "A = X + Y"
},
{
"code": null,
"e": 26367,
"s": 26355,
"text": "B = X xor Y"
},
{
"code": null,
"e": 26498,
"s": 26367,
"text": "The task is to make X as minimum as possible. If it is not possible to find any valid values for X and Y then print -1.Examples: "
},
{
"code": null,
"e": 26578,
"s": 26498,
"text": "Input : A = 12, B = 8\nOutput : X = 2, Y = 10\n\nInput : A = 12, B = 9\nOutput : -1"
},
{
"code": null,
"e": 27008,
"s": 26580,
"text": "Let’s take a look at some bit in X, which is equal to 1. If the respective bit in Y is equal to 0, then one can swap these two bits, thus reducing X and increasing Y without changing their sum and xor. We can conclude that if some bit in X is equal to 1 then the respective bit in Y is also equal to 1. Thus, Y = X + B. Taking into account that X + Y = X + X + B = A, one can obtain the following formulas for finding X and Y: "
},
{
"code": null,
"e": 27024,
"s": 27008,
"text": "X = (A – B) / 2"
},
{
"code": null,
"e": 27048,
"s": 27024,
"text": "Y = X + B = (A + B) / 2"
},
{
"code": null,
"e": 27279,
"s": 27048,
"text": "One should also notice that if A < B or A and B have different parity, then the answer doesn’t exist and output is -1. If X and (A – X) not equal to X then the answer is also -1.Below is the implementation of the above approach : "
},
{
"code": null,
"e": 27283,
"s": 27279,
"text": "C++"
},
{
"code": null,
"e": 27288,
"s": 27283,
"text": "Java"
},
{
"code": null,
"e": 27296,
"s": 27288,
"text": "Python3"
},
{
"code": null,
"e": 27299,
"s": 27296,
"text": "C#"
},
{
"code": null,
"e": 27303,
"s": 27299,
"text": "PHP"
},
{
"code": null,
"e": 27314,
"s": 27303,
"text": "Javascript"
},
{
"code": "// CPP program to find the values of// X and Y using the given equations #include <bits/stdc++.h>using namespace std; // Function to find the// values of X and Yvoid findValues(int a, int b){ // base condition if ((a - b) % 2 == 1) { cout << \"-1\"; return; } // required answer cout << (a - b) / 2 << \" \" << (a + b) / 2;} // Driver Codeint main(){ int a = 12, b = 8; findValues(a, b); return 0;}",
"e": 27750,
"s": 27314,
"text": null
},
{
"code": "// Java program to find the values of// X and Y using the given equationsimport java.io.*; class GFG{ // Function to find the// values of X and Ystatic void findValues(int a, int b){ // base condition if ((a - b) % 2 == 1) { System.out.println (\"-1\"); return; } // required answer System.out.println (((a - b) / 2)+ \" \" + ((a + b) / 2));} // Driver Code public static void main (String[] args) { int a = 12, b = 8; findValues(a, b); }} // This code is contributed by ajit...",
"e": 28320,
"s": 27750,
"text": null
},
{
"code": "# Python3 program to find the values of# X and Y using the given equations # Function to find the values of X and Ydef findValues(a, b): # base condition if ((a - b) % 2 == 1): print(\"-1\"); return; # required answer print((a - b) // 2, (a + b) // 2); # Driver Codea = 12; b = 8; findValues(a, b); # This code is contributed# by Akanksha Rai",
"e": 28689,
"s": 28320,
"text": null
},
{
"code": "// C# program to find the values of// X and Y using the given equationsusing System; class GFG{ // Function to find the// values of X and Ystatic void findValues(int a, int b){ // base condition if ((a - b) % 2 == 1) { Console.Write (\"-1\"); return; } // required answer Console.WriteLine(((a - b) / 2)+ \" \" + ((a + b) / 2));} // Driver Codestatic public void Main (){ int a = 12, b = 8; findValues(a, b);}} // This code is contributed by @Tushil..",
"e": 29211,
"s": 28689,
"text": null
},
{
"code": "<?php// PHP program to find the values of// X and Y using the given equations // Function to find the values// of X and Yfunction findValues($a, $b){ // base condition if (($a - $b) % 2 == 1) { echo \"-1\"; return; } // required answer echo ($a - $b) / 2, \" \" , ($a + $b) / 2;} // Driver Code$a = 12;$b = 8;findValues($a, $b); // This code is contributed by jit_t?>",
"e": 29616,
"s": 29211,
"text": null
},
{
"code": "<script> // Javascript program to find the values of// X and Y using the given equations // Function to find the values// of X and Yfunction findValues(a, b){ // base condition if ((a - b) % 2 == 1) { document.write( \"-1\"); return; } // required answer document.write( (a - b) / 2+ \" \" + (a + b) / 2);} // Driver Codelet a = 12;let b = 8;findValues(a, b); // This code is contributed// by bobby </script>",
"e": 30061,
"s": 29616,
"text": null
},
{
"code": null,
"e": 30066,
"s": 30061,
"text": "2 10"
},
{
"code": null,
"e": 30074,
"s": 30068,
"text": "jit_t"
},
{
"code": null,
"e": 30087,
"s": 30074,
"text": "Akanksha_Rai"
},
{
"code": null,
"e": 30105,
"s": 30087,
"text": "gottumukkalabobby"
},
{
"code": null,
"e": 30110,
"s": 30105,
"text": "math"
},
{
"code": null,
"e": 30120,
"s": 30110,
"text": "Bit Magic"
},
{
"code": null,
"e": 30144,
"s": 30120,
"text": "Competitive Programming"
},
{
"code": null,
"e": 30157,
"s": 30144,
"text": "Mathematical"
},
{
"code": null,
"e": 30170,
"s": 30157,
"text": "Mathematical"
},
{
"code": null,
"e": 30180,
"s": 30170,
"text": "Bit Magic"
},
{
"code": null,
"e": 30278,
"s": 30180,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 30329,
"s": 30278,
"text": "Set, Clear and Toggle a given bit of a number in C"
},
{
"code": null,
"e": 30383,
"s": 30329,
"text": "Highest power of 2 less than or equal to given number"
},
{
"code": null,
"e": 30411,
"s": 30383,
"text": "Swap bits in a given number"
},
{
"code": null,
"e": 30475,
"s": 30411,
"text": "Write an Efficient Method to Check if a Number is Multiple of 3"
},
{
"code": null,
"e": 30502,
"s": 30475,
"text": "Check for Integer Overflow"
},
{
"code": null,
"e": 30545,
"s": 30502,
"text": "Competitive Programming - A Complete Guide"
},
{
"code": null,
"e": 30588,
"s": 30545,
"text": "Practice for cracking any coding interview"
},
{
"code": null,
"e": 30629,
"s": 30588,
"text": "Arrow operator -> in C/C++ with Examples"
},
{
"code": null,
"e": 30707,
"s": 30629,
"text": "Prefix Sum Array - Implementation and Applications in Competitive Programming"
}
] |
Forecasting COVID-19 cases in India | by Ishan Choudhary | Towards Data Science | COVID-19 has taken the world by storm after first being reported in Wuhan, China in December-2019. Since then, there has been an exponential growth in the number of such cases around the globe. As of 28th March 2020, the total reported cases reached 668,352 out of which 31,027 have died. The below figure shows the outbreak of the virus in various countries
It can very well be observed that most countries have reported cases of new Coronavirus. As of now, it has affected 192 countries and 1 international conveyance (the Diamond Princess cruise ship harbored in Yokohama, Japan).
Considering India, the cases emerged towards the end of January in the state of Kerala, when three students returned from Wuhan, China. However, things escalated in March, after several cases were reported all over the country, most of whom had a travel history to other countries. The below figure shows the number of cases detected between 30th January and 28th March.
After first emerging in late January, the number remained constant until the beginning of March, post which, it grew exponentially. As of 28nd March, the number of total cases has reached 987 cases with 24 deaths. Given the current rate of growth, where can the cases expect to reach in the next 10 days, if no specific precaution is taken?
We can do a time series analysis to create a model that helps in the forecast. The dataset is available on Kaggle. We use R-Programming for our analysis.
We load the necessary packages and attach the dataset
#COVID India — Analyzing/Forecasting Total Cases#Packageslibrary(dplyr)library(ggplot2)library(hrbrthemes)library(tseries)library(forecast)attach(Data)> head(Data)# A tibble: 6 x 4 Date `Total Confirmed Cases` Cured Deaths <dttm> <dbl> <dbl> <dbl>1 2020-01-30 00:00:00 1 0 02 2020-01-31 00:00:00 1 0 03 2020-02-01 00:00:00 2 0 04 2020-02-02 00:00:00 3 0 05 2020-02-03 00:00:00 3 0 06 2020-02-04 00:00:00 3 0 0
Let’s have a look at the first 6 observations. The columns include:
Date: The date on the observations are recorded.
Total Confirmed Cases: Number of confirmed cases as of the given date.
Cured: Patients recovered as of the given date
Deaths: Patients died as of the given date
Since, we are to analyze only the Total Confirmed Cases, we create a new data frame including only that.
#Creating a new data frame with Confirmed Casesdf <- Data[2]
The next step is to convert the data frame to a time series object.
#Converting it to Time Series Objecttsdata <- ts(df$`Total Confirmed Cases`)ts.plot(tsdata)
We get the time series plot with each observation recorded on a daily basis. The next step is to check if the time series is stationary. Putting it simply, a stationary time series is one whose statistical properties such as mean, variance, auto-correlation are constant over time. It is important for a time series observation to be stationary as it then becomes easy to get accurate predictions. We use the Augmented Dickey Fuller Test to test the stationarity of the time series observations. The null hypothesis (Ho) for the test is that the data is not stationary whereas the alternate hypothesis is that the data is stationary. The Level of Significance (LOS) is taken to be 0.05.
> adf.test(tsdata)Augmented Dickey-Fuller Testdata: tsdataDickey-Fuller = 2.2994, Lag order = 3, p-value = 0.99alternative hypothesis: stationaryWarning message:In adf.test(tsdata) : p-value greater than printed p-value
The p-value turns out be 0.99. We thus fail to reject our Ho and conclude that the data is not stationary. We now have to work on the stationarity of the data. There are various methods to make our time series stationary depending on its behavior. The most popular is the method of Differencing. Differencing helps stabilize the mean of a time series by removing changes in the level of a time series, and therefore eliminating (or reducing) trend and seasonality. Mathematically it is given as:
In the above expression, B is the Backshift operator and d represents the differencing order. The code used in R is as follows
> tsdata1 <- diff(tsdata, differences = 2)> adf.test(tsdata1)Augmented Dickey-Fuller Testdata: tsdata1Dickey-Fuller = -4.3764, Lag order = 3, p-value = 0.01alternative hypothesis: stationaryWarning message:In adf.test(tsdata1) : p-value smaller than printed p-value
After two rounds of differencing, we again perform the Augmented Dickey Fuller Test (ADF Test). The p-value is smaller than 0.01. We can thus reject our null hypothesis and conclude that the data is stationary. Since the order of differencing is 2, d is 2.
The next step is to plot the ACF and PACF graphs.
Complete Auto-Correlation Function (ACF) gives us the auto correlation of any series with its lagged values. In other words, ACF is a chart of coefficients of correlation between a time-series and its lagged values.
Partial Auto-Correlation Function (PACF) gives us the amount of correlation between two variables which is not explained by their mutual correlations, but with the residuals. Hence, we observe if the residuals can help us generate more information. A more comprehensive guide on the topic can be found here.
#Plotting the ACF plot and PACFacf(data1)pacf(data1)
The ACF plot above shows a significant correlation at lag 3(q) while the PACF plot below shows significant correlation till lag 1(p).
Based on the ACF and PACF, we choose an ARIMA (1,2,3) model. We take d as 2 since it took two differencing to make our time series stationary. We will now fit the model based on the above chosen parameters
#Fitting ARIMA (1,2,3) modelfit1 <- arima(df$`Total Confirmed Cases`, c(1,2,3))fit1#Forecastingforecast1 <- forecast(fit1, h = 10)forecast1plot(forecast1)
We get the following results
We forecast the Confirmed Cases for the next 10 days, that is, until 7th April 2020. The Point Forecast reaches 2278 on the 69th day, that is, by 7th April 2020, total confirmed cases is likely to reach 2278. Also, it is important to note that the cases double almost every 10 days. The figure plot shows the predicted cases. The blue line represents the forecast and the silver shade around it represents the confidence interval.
R also has at auto.arima() function that automatically selects the optimum (p,d,q) values for ARIMA model. Let us fit using that.
#Fitting auto.arima ()fit2 <- auto.arima(df$`Total Confirmed Cases`, seasonal = FALSE)fit2#Forecastingforecast2 <- forecast(fit2, h = 9)forecast2plot(forecast2)
We get the following results
The model using auto.arima(1,2,0) is pretty similar to our previous model, however, the q value is 0. We get an Akaike Information Criterion (AIC) of 486.42 which is less than the AIC for the previous model (491.62). From the point estimates, we can see that the Total Number of Cases reach 2264 on the 10th day, that is, by 7th April 2020, marginally less than 2278 predicted by the previous model. Cases more of less double every 10 days. Plotting the predictions, we get:
To estimate Model Adequacy, we do Residual Analysis. For a model to be adequate, the residuals should be Independent and Identically Distributed (I.I.D.) and should be uncorrelated. To test for correlation, we use the ACF plot and look for significant correlations.
There is no significant correlation observed at any lag except 0. We can deduce that the residuals are not correlated. To test if the residuals are normally distributed, we use Shapiro-Wilk Test of Normality. The results show that the residuals are normally distributed.
We come to the end our Time Series modelling on the Total Number of Cases in India. The number is increasing every passing day, however, the rate at which it grows will slow down in the next few days. The lock down in India implemented on 24th March will prevent community spread of the virus if the steps are taken seriously by the general public. Right now, it’s a major issue troubling every one in every corner of the world. We as a community have the potential to stop it and we can stop it by preventing the transmission of virus.
Thank you for the read. I sincerely hope you found it helpful and as always I am open to constructive feedback.
Drop me a mail at: [email protected]
You can find me on LinkedIn.
Note from the editors: Towards Data Science is a Medium publication primarily based on the study of data science and machine learning. We are not health professionals or epidemiologists, and the opinions of this article should not be interpreted as professional advice. To learn more about the coronavirus pandemic, you can click here. | [
{
"code": null,
"e": 531,
"s": 172,
"text": "COVID-19 has taken the world by storm after first being reported in Wuhan, China in December-2019. Since then, there has been an exponential growth in the number of such cases around the globe. As of 28th March 2020, the total reported cases reached 668,352 out of which 31,027 have died. The below figure shows the outbreak of the virus in various countries"
},
{
"code": null,
"e": 756,
"s": 531,
"text": "It can very well be observed that most countries have reported cases of new Coronavirus. As of now, it has affected 192 countries and 1 international conveyance (the Diamond Princess cruise ship harbored in Yokohama, Japan)."
},
{
"code": null,
"e": 1127,
"s": 756,
"text": "Considering India, the cases emerged towards the end of January in the state of Kerala, when three students returned from Wuhan, China. However, things escalated in March, after several cases were reported all over the country, most of whom had a travel history to other countries. The below figure shows the number of cases detected between 30th January and 28th March."
},
{
"code": null,
"e": 1468,
"s": 1127,
"text": "After first emerging in late January, the number remained constant until the beginning of March, post which, it grew exponentially. As of 28nd March, the number of total cases has reached 987 cases with 24 deaths. Given the current rate of growth, where can the cases expect to reach in the next 10 days, if no specific precaution is taken?"
},
{
"code": null,
"e": 1622,
"s": 1468,
"text": "We can do a time series analysis to create a model that helps in the forecast. The dataset is available on Kaggle. We use R-Programming for our analysis."
},
{
"code": null,
"e": 1676,
"s": 1622,
"text": "We load the necessary packages and attach the dataset"
},
{
"code": null,
"e": 2321,
"s": 1676,
"text": "#COVID India — Analyzing/Forecasting Total Cases#Packageslibrary(dplyr)library(ggplot2)library(hrbrthemes)library(tseries)library(forecast)attach(Data)> head(Data)# A tibble: 6 x 4 Date `Total Confirmed Cases` Cured Deaths <dttm> <dbl> <dbl> <dbl>1 2020-01-30 00:00:00 1 0 02 2020-01-31 00:00:00 1 0 03 2020-02-01 00:00:00 2 0 04 2020-02-02 00:00:00 3 0 05 2020-02-03 00:00:00 3 0 06 2020-02-04 00:00:00 3 0 0"
},
{
"code": null,
"e": 2389,
"s": 2321,
"text": "Let’s have a look at the first 6 observations. The columns include:"
},
{
"code": null,
"e": 2438,
"s": 2389,
"text": "Date: The date on the observations are recorded."
},
{
"code": null,
"e": 2509,
"s": 2438,
"text": "Total Confirmed Cases: Number of confirmed cases as of the given date."
},
{
"code": null,
"e": 2556,
"s": 2509,
"text": "Cured: Patients recovered as of the given date"
},
{
"code": null,
"e": 2599,
"s": 2556,
"text": "Deaths: Patients died as of the given date"
},
{
"code": null,
"e": 2704,
"s": 2599,
"text": "Since, we are to analyze only the Total Confirmed Cases, we create a new data frame including only that."
},
{
"code": null,
"e": 2765,
"s": 2704,
"text": "#Creating a new data frame with Confirmed Casesdf <- Data[2]"
},
{
"code": null,
"e": 2833,
"s": 2765,
"text": "The next step is to convert the data frame to a time series object."
},
{
"code": null,
"e": 2925,
"s": 2833,
"text": "#Converting it to Time Series Objecttsdata <- ts(df$`Total Confirmed Cases`)ts.plot(tsdata)"
},
{
"code": null,
"e": 3612,
"s": 2925,
"text": "We get the time series plot with each observation recorded on a daily basis. The next step is to check if the time series is stationary. Putting it simply, a stationary time series is one whose statistical properties such as mean, variance, auto-correlation are constant over time. It is important for a time series observation to be stationary as it then becomes easy to get accurate predictions. We use the Augmented Dickey Fuller Test to test the stationarity of the time series observations. The null hypothesis (Ho) for the test is that the data is not stationary whereas the alternate hypothesis is that the data is stationary. The Level of Significance (LOS) is taken to be 0.05."
},
{
"code": null,
"e": 3832,
"s": 3612,
"text": "> adf.test(tsdata)Augmented Dickey-Fuller Testdata: tsdataDickey-Fuller = 2.2994, Lag order = 3, p-value = 0.99alternative hypothesis: stationaryWarning message:In adf.test(tsdata) : p-value greater than printed p-value"
},
{
"code": null,
"e": 4328,
"s": 3832,
"text": "The p-value turns out be 0.99. We thus fail to reject our Ho and conclude that the data is not stationary. We now have to work on the stationarity of the data. There are various methods to make our time series stationary depending on its behavior. The most popular is the method of Differencing. Differencing helps stabilize the mean of a time series by removing changes in the level of a time series, and therefore eliminating (or reducing) trend and seasonality. Mathematically it is given as:"
},
{
"code": null,
"e": 4455,
"s": 4328,
"text": "In the above expression, B is the Backshift operator and d represents the differencing order. The code used in R is as follows"
},
{
"code": null,
"e": 4722,
"s": 4455,
"text": "> tsdata1 <- diff(tsdata, differences = 2)> adf.test(tsdata1)Augmented Dickey-Fuller Testdata: tsdata1Dickey-Fuller = -4.3764, Lag order = 3, p-value = 0.01alternative hypothesis: stationaryWarning message:In adf.test(tsdata1) : p-value smaller than printed p-value"
},
{
"code": null,
"e": 4979,
"s": 4722,
"text": "After two rounds of differencing, we again perform the Augmented Dickey Fuller Test (ADF Test). The p-value is smaller than 0.01. We can thus reject our null hypothesis and conclude that the data is stationary. Since the order of differencing is 2, d is 2."
},
{
"code": null,
"e": 5029,
"s": 4979,
"text": "The next step is to plot the ACF and PACF graphs."
},
{
"code": null,
"e": 5245,
"s": 5029,
"text": "Complete Auto-Correlation Function (ACF) gives us the auto correlation of any series with its lagged values. In other words, ACF is a chart of coefficients of correlation between a time-series and its lagged values."
},
{
"code": null,
"e": 5553,
"s": 5245,
"text": "Partial Auto-Correlation Function (PACF) gives us the amount of correlation between two variables which is not explained by their mutual correlations, but with the residuals. Hence, we observe if the residuals can help us generate more information. A more comprehensive guide on the topic can be found here."
},
{
"code": null,
"e": 5606,
"s": 5553,
"text": "#Plotting the ACF plot and PACFacf(data1)pacf(data1)"
},
{
"code": null,
"e": 5740,
"s": 5606,
"text": "The ACF plot above shows a significant correlation at lag 3(q) while the PACF plot below shows significant correlation till lag 1(p)."
},
{
"code": null,
"e": 5946,
"s": 5740,
"text": "Based on the ACF and PACF, we choose an ARIMA (1,2,3) model. We take d as 2 since it took two differencing to make our time series stationary. We will now fit the model based on the above chosen parameters"
},
{
"code": null,
"e": 6101,
"s": 5946,
"text": "#Fitting ARIMA (1,2,3) modelfit1 <- arima(df$`Total Confirmed Cases`, c(1,2,3))fit1#Forecastingforecast1 <- forecast(fit1, h = 10)forecast1plot(forecast1)"
},
{
"code": null,
"e": 6130,
"s": 6101,
"text": "We get the following results"
},
{
"code": null,
"e": 6561,
"s": 6130,
"text": "We forecast the Confirmed Cases for the next 10 days, that is, until 7th April 2020. The Point Forecast reaches 2278 on the 69th day, that is, by 7th April 2020, total confirmed cases is likely to reach 2278. Also, it is important to note that the cases double almost every 10 days. The figure plot shows the predicted cases. The blue line represents the forecast and the silver shade around it represents the confidence interval."
},
{
"code": null,
"e": 6691,
"s": 6561,
"text": "R also has at auto.arima() function that automatically selects the optimum (p,d,q) values for ARIMA model. Let us fit using that."
},
{
"code": null,
"e": 6852,
"s": 6691,
"text": "#Fitting auto.arima ()fit2 <- auto.arima(df$`Total Confirmed Cases`, seasonal = FALSE)fit2#Forecastingforecast2 <- forecast(fit2, h = 9)forecast2plot(forecast2)"
},
{
"code": null,
"e": 6881,
"s": 6852,
"text": "We get the following results"
},
{
"code": null,
"e": 7356,
"s": 6881,
"text": "The model using auto.arima(1,2,0) is pretty similar to our previous model, however, the q value is 0. We get an Akaike Information Criterion (AIC) of 486.42 which is less than the AIC for the previous model (491.62). From the point estimates, we can see that the Total Number of Cases reach 2264 on the 10th day, that is, by 7th April 2020, marginally less than 2278 predicted by the previous model. Cases more of less double every 10 days. Plotting the predictions, we get:"
},
{
"code": null,
"e": 7622,
"s": 7356,
"text": "To estimate Model Adequacy, we do Residual Analysis. For a model to be adequate, the residuals should be Independent and Identically Distributed (I.I.D.) and should be uncorrelated. To test for correlation, we use the ACF plot and look for significant correlations."
},
{
"code": null,
"e": 7893,
"s": 7622,
"text": "There is no significant correlation observed at any lag except 0. We can deduce that the residuals are not correlated. To test if the residuals are normally distributed, we use Shapiro-Wilk Test of Normality. The results show that the residuals are normally distributed."
},
{
"code": null,
"e": 8430,
"s": 7893,
"text": "We come to the end our Time Series modelling on the Total Number of Cases in India. The number is increasing every passing day, however, the rate at which it grows will slow down in the next few days. The lock down in India implemented on 24th March will prevent community spread of the virus if the steps are taken seriously by the general public. Right now, it’s a major issue troubling every one in every corner of the world. We as a community have the potential to stop it and we can stop it by preventing the transmission of virus."
},
{
"code": null,
"e": 8542,
"s": 8430,
"text": "Thank you for the read. I sincerely hope you found it helpful and as always I am open to constructive feedback."
},
{
"code": null,
"e": 8586,
"s": 8542,
"text": "Drop me a mail at: [email protected]"
},
{
"code": null,
"e": 8615,
"s": 8586,
"text": "You can find me on LinkedIn."
}
] |
GZIPOutputStream Class in Java - GeeksforGeeks | 20 Jul, 2021
The java.util.zip package provides classes to compress and decompress the file contents. FileInputStream, FileOutputStream, and GZIPOutputStream classes are provided in Java to compress and decompress the files. The GZIPOutputStream class is useful for writing compressed data in GZIP file format. However, GZIP is not a zip tool, it only use to compress a file into a “.gz” format, not compress several files into a single archive.
The constructors and the corresponding action performed is as follows:
GZIPOutputStream(OutputStream out): Creates a new output stream with a default buffer size
GZIPOutputStream(OutputStream out, boolean syncFlush): Creates a new output stream with a default buffer size and the specified flush mode.
GZIPOutputStream(OutputStream out, int size): Creates a new output stream with the specified buffer size
GZIPOutputStream(OutputStream out, int size, boolean syncFlush): Creates a new output stream with the specified buffer size and flush mode
Let us discuss the important methods involved, which are as follows:
void write(byte[] buf, int off, int len): Writes an array of bytes to the compressed output stream.
Parameters: It takes 3 parameters, namely as follows:
buf: Data to be written
off: Start offset of the data
len: Length of the data
Exception: IOException: If an I/O error has occurred
Note: finish() method finishes writing compressed data to the output stream without closing the underlying stream.
Implementation: We have a text file in D:/Myfolder/New.txt, and ” Hello World ” is written in this text file. We are compressing this text file (New.txt) and generating the GZip file in the same folder. It is also pictorially depicted below as follows:
Example
Java
// Java Program to Illustrate GZIPOutputStream class // Importing required classesimport java.io.*;import java.io.FileInputStream;import java.io.FileOutputStream;import java.io.IOException;import java.util.zip.GZIPInputStream;import java.util.zip.GZIPOutputStream; // Main classclass GFG { // Main driver method public static void main(String[] args) throws Exception { // Existing file path String file = "D:/Myfolder/New.txt"; // Path where we want the compression of the file String gzipFile = "D:/Myfolder/compress.gz"; // Reading the text file FileInputStream fis = new FileInputStream(file); // Creating the compressed file FileOutputStream fos = new FileOutputStream(gzipFile); // Object of Fileoutstream passed GZIPOutputStream gzipOS = new GZIPOutputStream(fos); byte[] buffer = new byte[1024]; int len; // Writing the data to file until -1 reached(End of // file) while ((len = fis.read(buffer)) != -1) { gzipOS.write(buffer, 0, len); } // Closing the resources // using standard close() method gzipOS.close(); fos.close(); fis.close(); // Display message on the console in order to // illustrate successful execution of the program System.out.println("File successfully compressed"); }}
Output:
File successfully compressed
After running the above program, it will compress the file generated that can be depicted from snapsh below by comparing it with the above sampling snapshot.
Java-Classes
Java-util-zip package
Picked
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
PriorityQueue in Java
How to remove an element from ArrayList in Java? | [
{
"code": null,
"e": 25237,
"s": 25209,
"text": "\n20 Jul, 2021"
},
{
"code": null,
"e": 25670,
"s": 25237,
"text": "The java.util.zip package provides classes to compress and decompress the file contents. FileInputStream, FileOutputStream, and GZIPOutputStream classes are provided in Java to compress and decompress the files. The GZIPOutputStream class is useful for writing compressed data in GZIP file format. However, GZIP is not a zip tool, it only use to compress a file into a “.gz” format, not compress several files into a single archive."
},
{
"code": null,
"e": 25742,
"s": 25670,
"text": "The constructors and the corresponding action performed is as follows: "
},
{
"code": null,
"e": 25833,
"s": 25742,
"text": "GZIPOutputStream(OutputStream out): Creates a new output stream with a default buffer size"
},
{
"code": null,
"e": 25973,
"s": 25833,
"text": "GZIPOutputStream(OutputStream out, boolean syncFlush): Creates a new output stream with a default buffer size and the specified flush mode."
},
{
"code": null,
"e": 26078,
"s": 25973,
"text": "GZIPOutputStream(OutputStream out, int size): Creates a new output stream with the specified buffer size"
},
{
"code": null,
"e": 26217,
"s": 26078,
"text": "GZIPOutputStream(OutputStream out, int size, boolean syncFlush): Creates a new output stream with the specified buffer size and flush mode"
},
{
"code": null,
"e": 26286,
"s": 26217,
"text": "Let us discuss the important methods involved, which are as follows:"
},
{
"code": null,
"e": 26386,
"s": 26286,
"text": "void write(byte[] buf, int off, int len): Writes an array of bytes to the compressed output stream."
},
{
"code": null,
"e": 26441,
"s": 26386,
"text": "Parameters: It takes 3 parameters, namely as follows:"
},
{
"code": null,
"e": 26465,
"s": 26441,
"text": "buf: Data to be written"
},
{
"code": null,
"e": 26495,
"s": 26465,
"text": "off: Start offset of the data"
},
{
"code": null,
"e": 26519,
"s": 26495,
"text": "len: Length of the data"
},
{
"code": null,
"e": 26572,
"s": 26519,
"text": "Exception: IOException: If an I/O error has occurred"
},
{
"code": null,
"e": 26687,
"s": 26572,
"text": "Note: finish() method finishes writing compressed data to the output stream without closing the underlying stream."
},
{
"code": null,
"e": 26941,
"s": 26687,
"text": "Implementation: We have a text file in D:/Myfolder/New.txt, and ” Hello World ” is written in this text file. We are compressing this text file (New.txt) and generating the GZip file in the same folder. It is also pictorially depicted below as follows:"
},
{
"code": null,
"e": 26950,
"s": 26941,
"text": "Example "
},
{
"code": null,
"e": 26955,
"s": 26950,
"text": "Java"
},
{
"code": "// Java Program to Illustrate GZIPOutputStream class // Importing required classesimport java.io.*;import java.io.FileInputStream;import java.io.FileOutputStream;import java.io.IOException;import java.util.zip.GZIPInputStream;import java.util.zip.GZIPOutputStream; // Main classclass GFG { // Main driver method public static void main(String[] args) throws Exception { // Existing file path String file = \"D:/Myfolder/New.txt\"; // Path where we want the compression of the file String gzipFile = \"D:/Myfolder/compress.gz\"; // Reading the text file FileInputStream fis = new FileInputStream(file); // Creating the compressed file FileOutputStream fos = new FileOutputStream(gzipFile); // Object of Fileoutstream passed GZIPOutputStream gzipOS = new GZIPOutputStream(fos); byte[] buffer = new byte[1024]; int len; // Writing the data to file until -1 reached(End of // file) while ((len = fis.read(buffer)) != -1) { gzipOS.write(buffer, 0, len); } // Closing the resources // using standard close() method gzipOS.close(); fos.close(); fis.close(); // Display message on the console in order to // illustrate successful execution of the program System.out.println(\"File successfully compressed\"); }}",
"e": 28397,
"s": 26955,
"text": null
},
{
"code": null,
"e": 28405,
"s": 28397,
"text": "Output:"
},
{
"code": null,
"e": 28434,
"s": 28405,
"text": "File successfully compressed"
},
{
"code": null,
"e": 28592,
"s": 28434,
"text": "After running the above program, it will compress the file generated that can be depicted from snapsh below by comparing it with the above sampling snapshot."
},
{
"code": null,
"e": 28605,
"s": 28592,
"text": "Java-Classes"
},
{
"code": null,
"e": 28627,
"s": 28605,
"text": "Java-util-zip package"
},
{
"code": null,
"e": 28634,
"s": 28627,
"text": "Picked"
},
{
"code": null,
"e": 28639,
"s": 28634,
"text": "Java"
},
{
"code": null,
"e": 28644,
"s": 28639,
"text": "Java"
},
{
"code": null,
"e": 28742,
"s": 28644,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 28757,
"s": 28742,
"text": "Stream In Java"
},
{
"code": null,
"e": 28778,
"s": 28757,
"text": "Constructors in Java"
},
{
"code": null,
"e": 28797,
"s": 28778,
"text": "Exceptions in Java"
},
{
"code": null,
"e": 28827,
"s": 28797,
"text": "Functional Interfaces in Java"
},
{
"code": null,
"e": 28873,
"s": 28827,
"text": "Different ways of Reading a text file in Java"
},
{
"code": null,
"e": 28890,
"s": 28873,
"text": "Generics in Java"
},
{
"code": null,
"e": 28911,
"s": 28890,
"text": "Introduction to Java"
},
{
"code": null,
"e": 28954,
"s": 28911,
"text": "Comparator Interface in Java with Examples"
},
{
"code": null,
"e": 28976,
"s": 28954,
"text": "PriorityQueue in Java"
}
] |
Check if a given string is a valid number (Integer or Floating Point) in Java - GeeksforGeeks | 11 Dec, 2018
In the article Check if a given string is a valid number, we have discussed general approach to check whether a string is a valid number or not. In Java we can use Wrapper classes parse() methods along with try-catch blocks to check for a number.
For integer number
Integer class provides a static method parseInt() which will throw NumberFormatException if the String does not contain a parsable int. We will catch this exception using catch block and thus confirm that given string is not a valid integer number.Below is the java program to demonstrate the same.
//Java program to check whether given string// is a valid integer number class GFG { public static void main (String[] args) { String input1 = "abc"; String input2 = "1234"; try { // checking valid integer using parseInt() method Integer.parseInt(input1); System.out.println(input1 + " is a valid integer number"); } catch (NumberFormatException e) { System.out.println(input1 + " is not a valid integer number"); } try { // checking valid integer using parseInt() method Integer.parseInt(input2); System.out.println(input2 + " is a valid integer number"); } catch (NumberFormatException e) { System.out.println(input2 + " is not a valid integer number"); } }}
Output:
abc is not a valid integer number
1234 is a valid integer number
For float number
Float class provides a static method parseFloat() which will throw NumberFormatException if the String does not contain a parsable float. We will catch this exception using catch block and thus confirm that given string is not a valid float number.If string is null, this method will throw NullPointerException.Below is the java program to demonstrate the same.
// Java program to check whether given string// is a valid float number. class GFG { public static void main (String[] args) { String input1 = "10e5.4"; String input2 = "2e10"; try { // checking valid float using parseInt() method Float.parseFloat(input1); System.out.println(input1 + " is a valid float number"); } catch (NumberFormatException e) { System.out.println(input1 + " is not a valid float number"); } try { // checking valid float using parseInt() method Float.parseFloat(input2); System.out.println(input2 + " is a valid float number"); } catch (NumberFormatException e) { System.out.println(input2 + " is not a valid float number"); } }}
Output:
10e5.4 is not a valid float number
2e10 is a valid float number
For big numbers
We can use BigInteger and BigDecimal class constructors for large numbers.Below is the java program to demonstrate the same.
// Java program to check whether given string// is a valid number. import java.math.BigInteger;import java.math.BigDecimal; class GFG { public static void main (String[] args) { String input1 = "1231456416541214651356151564651954156"; String input2 = "105612656501606510651e655.4"; String input3 = "2e102225"; try { // checking valid integer number using BigInteger constructor new BigInteger(input1); System.out.println(input1 + " is a valid integer number"); } catch (NumberFormatException e) { System.out.println(input1 + " is not a valid integer number"); } try { // checking valid float number using BigDecimal constructor new BigDecimal(input2); System.out.println(input2 + " is a valid float number"); } catch (NumberFormatException e) { System.out.println(input2 + " is not a valid float number"); } try { // checking valid float number using BigDecimal constructor new BigDecimal(input3); System.out.println(input3 + " is a valid float number"); } catch (NumberFormatException e) { System.out.println(input3 + " is not a valid float number"); } }}
Output:
1231456416541214651356151564651954156 is a valid integer number
105612656501606510651e655.4 is not a valid float number
2e102225 is a valid float number
This article is contributed by Gaurav Miglani. 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.
Java-String-Programs
Java-Strings
Java
Strings
Java-Strings
Strings
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
Object Oriented Programming (OOPs) Concept in Java
ArrayList in Java
Write a program to reverse an array or string
Longest Common Subsequence | DP-4
Write a program to print all permutations of a given string
C++ Data Types
Different methods to reverse a string in C/C++ | [
{
"code": null,
"e": 24866,
"s": 24838,
"text": "\n11 Dec, 2018"
},
{
"code": null,
"e": 25113,
"s": 24866,
"text": "In the article Check if a given string is a valid number, we have discussed general approach to check whether a string is a valid number or not. In Java we can use Wrapper classes parse() methods along with try-catch blocks to check for a number."
},
{
"code": null,
"e": 25132,
"s": 25113,
"text": "For integer number"
},
{
"code": null,
"e": 25431,
"s": 25132,
"text": "Integer class provides a static method parseInt() which will throw NumberFormatException if the String does not contain a parsable int. We will catch this exception using catch block and thus confirm that given string is not a valid integer number.Below is the java program to demonstrate the same."
},
{
"code": "//Java program to check whether given string// is a valid integer number class GFG { public static void main (String[] args) { String input1 = \"abc\"; String input2 = \"1234\"; try { // checking valid integer using parseInt() method Integer.parseInt(input1); System.out.println(input1 + \" is a valid integer number\"); } catch (NumberFormatException e) { System.out.println(input1 + \" is not a valid integer number\"); } try { // checking valid integer using parseInt() method Integer.parseInt(input2); System.out.println(input2 + \" is a valid integer number\"); } catch (NumberFormatException e) { System.out.println(input2 + \" is not a valid integer number\"); } }}",
"e": 26313,
"s": 25431,
"text": null
},
{
"code": null,
"e": 26321,
"s": 26313,
"text": "Output:"
},
{
"code": null,
"e": 26387,
"s": 26321,
"text": "abc is not a valid integer number\n1234 is a valid integer number\n"
},
{
"code": null,
"e": 26404,
"s": 26387,
"text": "For float number"
},
{
"code": null,
"e": 26766,
"s": 26404,
"text": "Float class provides a static method parseFloat() which will throw NumberFormatException if the String does not contain a parsable float. We will catch this exception using catch block and thus confirm that given string is not a valid float number.If string is null, this method will throw NullPointerException.Below is the java program to demonstrate the same."
},
{
"code": "// Java program to check whether given string// is a valid float number. class GFG { public static void main (String[] args) { String input1 = \"10e5.4\"; String input2 = \"2e10\"; try { // checking valid float using parseInt() method Float.parseFloat(input1); System.out.println(input1 + \" is a valid float number\"); } catch (NumberFormatException e) { System.out.println(input1 + \" is not a valid float number\"); } try { // checking valid float using parseInt() method Float.parseFloat(input2); System.out.println(input2 + \" is a valid float number\"); } catch (NumberFormatException e) { System.out.println(input2 + \" is not a valid float number\"); } }}",
"e": 27637,
"s": 26766,
"text": null
},
{
"code": null,
"e": 27645,
"s": 27637,
"text": "Output:"
},
{
"code": null,
"e": 27710,
"s": 27645,
"text": "10e5.4 is not a valid float number\n2e10 is a valid float number\n"
},
{
"code": null,
"e": 27726,
"s": 27710,
"text": "For big numbers"
},
{
"code": null,
"e": 27851,
"s": 27726,
"text": "We can use BigInteger and BigDecimal class constructors for large numbers.Below is the java program to demonstrate the same."
},
{
"code": "// Java program to check whether given string// is a valid number. import java.math.BigInteger;import java.math.BigDecimal; class GFG { public static void main (String[] args) { String input1 = \"1231456416541214651356151564651954156\"; String input2 = \"105612656501606510651e655.4\"; String input3 = \"2e102225\"; try { // checking valid integer number using BigInteger constructor new BigInteger(input1); System.out.println(input1 + \" is a valid integer number\"); } catch (NumberFormatException e) { System.out.println(input1 + \" is not a valid integer number\"); } try { // checking valid float number using BigDecimal constructor new BigDecimal(input2); System.out.println(input2 + \" is a valid float number\"); } catch (NumberFormatException e) { System.out.println(input2 + \" is not a valid float number\"); } try { // checking valid float number using BigDecimal constructor new BigDecimal(input3); System.out.println(input3 + \" is a valid float number\"); } catch (NumberFormatException e) { System.out.println(input3 + \" is not a valid float number\"); } }}",
"e": 29245,
"s": 27851,
"text": null
},
{
"code": null,
"e": 29253,
"s": 29245,
"text": "Output:"
},
{
"code": null,
"e": 29407,
"s": 29253,
"text": "1231456416541214651356151564651954156 is a valid integer number\n105612656501606510651e655.4 is not a valid float number\n2e102225 is a valid float number\n"
},
{
"code": null,
"e": 29709,
"s": 29407,
"text": "This article is contributed by Gaurav Miglani. 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": 29834,
"s": 29709,
"text": "Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above."
},
{
"code": null,
"e": 29855,
"s": 29834,
"text": "Java-String-Programs"
},
{
"code": null,
"e": 29868,
"s": 29855,
"text": "Java-Strings"
},
{
"code": null,
"e": 29873,
"s": 29868,
"text": "Java"
},
{
"code": null,
"e": 29881,
"s": 29873,
"text": "Strings"
},
{
"code": null,
"e": 29894,
"s": 29881,
"text": "Java-Strings"
},
{
"code": null,
"e": 29902,
"s": 29894,
"text": "Strings"
},
{
"code": null,
"e": 29907,
"s": 29902,
"text": "Java"
},
{
"code": null,
"e": 30005,
"s": 29907,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 30014,
"s": 30005,
"text": "Comments"
},
{
"code": null,
"e": 30027,
"s": 30014,
"text": "Old Comments"
},
{
"code": null,
"e": 30059,
"s": 30027,
"text": "Initialize an ArrayList in Java"
},
{
"code": null,
"e": 30089,
"s": 30059,
"text": "HashMap in Java with Examples"
},
{
"code": null,
"e": 30108,
"s": 30089,
"text": "Interfaces in Java"
},
{
"code": null,
"e": 30159,
"s": 30108,
"text": "Object Oriented Programming (OOPs) Concept in Java"
},
{
"code": null,
"e": 30177,
"s": 30159,
"text": "ArrayList in Java"
},
{
"code": null,
"e": 30223,
"s": 30177,
"text": "Write a program to reverse an array or string"
},
{
"code": null,
"e": 30257,
"s": 30223,
"text": "Longest Common Subsequence | DP-4"
},
{
"code": null,
"e": 30317,
"s": 30257,
"text": "Write a program to print all permutations of a given string"
},
{
"code": null,
"e": 30332,
"s": 30317,
"text": "C++ Data Types"
}
] |
Working with Flux.jl Models on the Hugging Face Hub 🤗 | by Logan Kilpatrick | Towards Data Science | This article will go over the details of how to save a model in Flux.jl (the 100% Julia Deep Learning package) and then upload or retrieve it from the Hugging Face Hub. For those who don’t know what Hugging Face (HF) is, it’s like GitHub, but for Machine Learning models. Traditionally, machine learning models would often be locked away and only accessible to the team which created them. HF is taking the machine learning ecosystem by storm so understanding how to use the platfrom in your machine learning workflow is critical. Let’s dive into how you can use your favorite Julia ML package to work with HF 🤗!
If you have never used Flux.jl before, you can find the installation instructions here: https://fluxml.ai/Flux.jl/stable/#Installation and a quick video on why you might want to use it below:
Okay, now that we have Flux installed and you know why we might want to use it, let’s create a simple model:
julia> using Fluxjulia> model = Chain(Dense(10,5,relu),Dense(5,2),softmax)Chain(Dense(10, 5, relu), Dense(5, 2), softmax)
We can then import the BSON package (which is how we will save our models so they can be consumed by others on Hugging Face)
julia> using BSON: @save
Lastly, we can actually save the model by doing:
julia> @save "mymodel.bson" model
Next, we are going to upload the model to the Hugging Face Hub and then try downloading it in a new session. If you want to learn more about model building in Flux, check out the below video:
Head to: https://huggingface.co and create an account. I won’t go through all of those steps since it is rather straightforward but post on the Hugging Face Discourse instance if you run into any issues: https://discuss.huggingface.co
Now that you are up and running on the HF Hub, we are going to select your profile icon in the top right and then select “New Model”.
From there, fill out the relevant details and then create the model. You can find the basic model I created here: https://huggingface.co/LoganKilpatrick/BasicFluxjlModel
After you create the basic model card, the next step is to actually upload the model in BSON format. If you navigate back to the Julia REPL, you can type ; and then pwd to find where you saved your model locally. Mine is saved on my Desktop to make it easy to find. On HF, go to “Filed and versions” and “Add File” on the right side. You should now have a README and a model in BSON format saved to the Hugging Face Hub! Next up, how to get the model back to your computer or anyone else’s?
So now we have a model saved to the HF Hub, the next thing you probably want to do is download someone else’s Flux model (like mine: https://huggingface.co/LoganKilpatrick/BasicFluxjlModel).
HF provides a Python library to interact with the Hub. Since I did not have time (yet) to re-write the whole package in pure Julia, we are going to bust out the trusty PyCall.jl package which allows us to run Python code directly in a Julia REPL session or script.
Take some time to follow the PyCall installation guide: https://github.com/JuliaPy/PyCall.jl#installation and please do open issues if anything is not clear.
Okay, now that you have it up and running, let’s use it!
julia> using PyCalljulia> hf = pyimport("huggingface_hub")PyObject <module 'huggingface_hub' from '/Users/logankilpatrick/.julia/conda/3/lib/python3.8/site-packages/huggingface_hub/__init__.py'>
Note that this assumes you have huggingface_hub Python package installed in the same Python environment we are using through PyCall.
So what do we really have here? We used PyCall to import a Python package into Julia? Yes! Now that we have it imported, we can use it the same way we would normally use a Python package:
julia> hf.snapshot_download(repo_id="LoganKilpatrick/BasicFluxjlModel", revision="main")Downloading: 100%|██████████████████████████| 1.18k/1.18k [00:00<00:00, 345kB/s]Downloading: 100%|██████████████████████████████| 711/711 [00:00<00:00, 130kB/s]Downloading: 100%|█████████████████████████| 10.3k/10.3k [00:00<00:00, 2.07MB/s]"/Users/logankilpatrick/.cache/huggingface/hub/LoganKilpatrick__BasicFluxjlModel.077a4b77d6175a09c156a20cf5bed0eac35c97ee"
Now we have the models repo saved locally, let’s again switch the Julia REPL to command line mode by typing in ; and then changing directories to the location of the model file.
shell> cd "/Users/logankilpatrick/.cache/huggingface/hub/LoganKilpatrick__BasicFluxjlModel.077a4b77d6175a09c156a20cf5bed0eac35c97ee"
Just to double check we did everything right, I am going to run a list command:
shell> ls -ltotal 32-rw - - - - 1 logankilpatrick staff 711 Oct 13 08:37 README.md-rw - - - - 1 logankilpatrick staff 10260 Oct 13 08:37 mymodel.bson
Great! We see the model there. Let’s load it back into Flux now.
julia> using BSON: @loadjulia> @load "mymodel.bson" modeljulia> modelChain(Dense(10, 5, relu), Dense(5, 2), softmax)
Boom! We did it 🎊! We successfully created a model with Flux, uploaded it to the Hub, and then downloaded a new model (or the same one you created) and loaded it back into Flux / Julia.
The next step is to keep training models and uploading / sharing them. The Hugging Face hub is a really snazzy way of collaborating with other ML researches and practitioners so I will see you there!
P.S. I also created a Julia Language organization on HF so if you have some impressive models you want to share, ping me and I can add you to the organization (https://huggingface.co/JuliaLanguage).
~ Logan Kilpatrick (https://twitter.com/OfficialLoganK) | [
{
"code": null,
"e": 785,
"s": 172,
"text": "This article will go over the details of how to save a model in Flux.jl (the 100% Julia Deep Learning package) and then upload or retrieve it from the Hugging Face Hub. For those who don’t know what Hugging Face (HF) is, it’s like GitHub, but for Machine Learning models. Traditionally, machine learning models would often be locked away and only accessible to the team which created them. HF is taking the machine learning ecosystem by storm so understanding how to use the platfrom in your machine learning workflow is critical. Let’s dive into how you can use your favorite Julia ML package to work with HF 🤗!"
},
{
"code": null,
"e": 977,
"s": 785,
"text": "If you have never used Flux.jl before, you can find the installation instructions here: https://fluxml.ai/Flux.jl/stable/#Installation and a quick video on why you might want to use it below:"
},
{
"code": null,
"e": 1086,
"s": 977,
"text": "Okay, now that we have Flux installed and you know why we might want to use it, let’s create a simple model:"
},
{
"code": null,
"e": 1208,
"s": 1086,
"text": "julia> using Fluxjulia> model = Chain(Dense(10,5,relu),Dense(5,2),softmax)Chain(Dense(10, 5, relu), Dense(5, 2), softmax)"
},
{
"code": null,
"e": 1333,
"s": 1208,
"text": "We can then import the BSON package (which is how we will save our models so they can be consumed by others on Hugging Face)"
},
{
"code": null,
"e": 1358,
"s": 1333,
"text": "julia> using BSON: @save"
},
{
"code": null,
"e": 1407,
"s": 1358,
"text": "Lastly, we can actually save the model by doing:"
},
{
"code": null,
"e": 1441,
"s": 1407,
"text": "julia> @save \"mymodel.bson\" model"
},
{
"code": null,
"e": 1633,
"s": 1441,
"text": "Next, we are going to upload the model to the Hugging Face Hub and then try downloading it in a new session. If you want to learn more about model building in Flux, check out the below video:"
},
{
"code": null,
"e": 1868,
"s": 1633,
"text": "Head to: https://huggingface.co and create an account. I won’t go through all of those steps since it is rather straightforward but post on the Hugging Face Discourse instance if you run into any issues: https://discuss.huggingface.co"
},
{
"code": null,
"e": 2002,
"s": 1868,
"text": "Now that you are up and running on the HF Hub, we are going to select your profile icon in the top right and then select “New Model”."
},
{
"code": null,
"e": 2172,
"s": 2002,
"text": "From there, fill out the relevant details and then create the model. You can find the basic model I created here: https://huggingface.co/LoganKilpatrick/BasicFluxjlModel"
},
{
"code": null,
"e": 2663,
"s": 2172,
"text": "After you create the basic model card, the next step is to actually upload the model in BSON format. If you navigate back to the Julia REPL, you can type ; and then pwd to find where you saved your model locally. Mine is saved on my Desktop to make it easy to find. On HF, go to “Filed and versions” and “Add File” on the right side. You should now have a README and a model in BSON format saved to the Hugging Face Hub! Next up, how to get the model back to your computer or anyone else’s?"
},
{
"code": null,
"e": 2854,
"s": 2663,
"text": "So now we have a model saved to the HF Hub, the next thing you probably want to do is download someone else’s Flux model (like mine: https://huggingface.co/LoganKilpatrick/BasicFluxjlModel)."
},
{
"code": null,
"e": 3119,
"s": 2854,
"text": "HF provides a Python library to interact with the Hub. Since I did not have time (yet) to re-write the whole package in pure Julia, we are going to bust out the trusty PyCall.jl package which allows us to run Python code directly in a Julia REPL session or script."
},
{
"code": null,
"e": 3277,
"s": 3119,
"text": "Take some time to follow the PyCall installation guide: https://github.com/JuliaPy/PyCall.jl#installation and please do open issues if anything is not clear."
},
{
"code": null,
"e": 3334,
"s": 3277,
"text": "Okay, now that you have it up and running, let’s use it!"
},
{
"code": null,
"e": 3529,
"s": 3334,
"text": "julia> using PyCalljulia> hf = pyimport(\"huggingface_hub\")PyObject <module 'huggingface_hub' from '/Users/logankilpatrick/.julia/conda/3/lib/python3.8/site-packages/huggingface_hub/__init__.py'>"
},
{
"code": null,
"e": 3662,
"s": 3529,
"text": "Note that this assumes you have huggingface_hub Python package installed in the same Python environment we are using through PyCall."
},
{
"code": null,
"e": 3850,
"s": 3662,
"text": "So what do we really have here? We used PyCall to import a Python package into Julia? Yes! Now that we have it imported, we can use it the same way we would normally use a Python package:"
},
{
"code": null,
"e": 4301,
"s": 3850,
"text": "julia> hf.snapshot_download(repo_id=\"LoganKilpatrick/BasicFluxjlModel\", revision=\"main\")Downloading: 100%|██████████████████████████| 1.18k/1.18k [00:00<00:00, 345kB/s]Downloading: 100%|██████████████████████████████| 711/711 [00:00<00:00, 130kB/s]Downloading: 100%|█████████████████████████| 10.3k/10.3k [00:00<00:00, 2.07MB/s]\"/Users/logankilpatrick/.cache/huggingface/hub/LoganKilpatrick__BasicFluxjlModel.077a4b77d6175a09c156a20cf5bed0eac35c97ee\""
},
{
"code": null,
"e": 4479,
"s": 4301,
"text": "Now we have the models repo saved locally, let’s again switch the Julia REPL to command line mode by typing in ; and then changing directories to the location of the model file."
},
{
"code": null,
"e": 4612,
"s": 4479,
"text": "shell> cd \"/Users/logankilpatrick/.cache/huggingface/hub/LoganKilpatrick__BasicFluxjlModel.077a4b77d6175a09c156a20cf5bed0eac35c97ee\""
},
{
"code": null,
"e": 4692,
"s": 4612,
"text": "Just to double check we did everything right, I am going to run a list command:"
},
{
"code": null,
"e": 4842,
"s": 4692,
"text": "shell> ls -ltotal 32-rw - - - - 1 logankilpatrick staff 711 Oct 13 08:37 README.md-rw - - - - 1 logankilpatrick staff 10260 Oct 13 08:37 mymodel.bson"
},
{
"code": null,
"e": 4907,
"s": 4842,
"text": "Great! We see the model there. Let’s load it back into Flux now."
},
{
"code": null,
"e": 5024,
"s": 4907,
"text": "julia> using BSON: @loadjulia> @load \"mymodel.bson\" modeljulia> modelChain(Dense(10, 5, relu), Dense(5, 2), softmax)"
},
{
"code": null,
"e": 5210,
"s": 5024,
"text": "Boom! We did it 🎊! We successfully created a model with Flux, uploaded it to the Hub, and then downloaded a new model (or the same one you created) and loaded it back into Flux / Julia."
},
{
"code": null,
"e": 5410,
"s": 5210,
"text": "The next step is to keep training models and uploading / sharing them. The Hugging Face hub is a really snazzy way of collaborating with other ML researches and practitioners so I will see you there!"
},
{
"code": null,
"e": 5609,
"s": 5410,
"text": "P.S. I also created a Julia Language organization on HF so if you have some impressive models you want to share, ping me and I can add you to the organization (https://huggingface.co/JuliaLanguage)."
}
] |
C# | Check if a SortedList object contains a specific value - GeeksforGeeks | 06 Sep, 2021
SortedList class is a collection of (key, value) pairs which are sorted according to keys. Those pairs can be accessible by key and as well as by index(zero-based indexing). This comes under System.Collections namespace. SortedList.ContainsValue(Object) method is used to check whether a SortedList object contains a specific value or not.
Properties:
A SortedList element can be accessed by its key or by its index.
A SortedList object internally maintains two arrays to store the elements of the list, i.e, one array for the keys and another array for the associated values.
A key cannot be null, but a value can be.
The capacity of a SortedList object is the number of elements the SortedList can hold.
A SortedList does not allow duplicate keys.
Operations on a SortedList object tend to be slower than operations on a Hashtable object because of the sorting.
Elements in this collection can be accessed using an integer index. Indexes in this collection are zero-based.
Syntax :
public virtual bool ContainsValue (object value);
Here, value is the value to locate in the SortedList object and it can be null.Return Value: This method returns True if the SortedList object contains an element with the specified value, otherwise it returns False.Below programs illustrate the use of SortedList.ContainsValue(Object) Method:Example 1:
CSHARP
// C# code to check if a SortedList// object contains a specific valueusing System;using System.Collections; class GFG { // Driver code public static void Main() { // Creating an SortedList SortedList mySortedList = new SortedList(); // Adding elements to SortedList mySortedList.Add("1", "1st"); mySortedList.Add("2", "2nd"); mySortedList.Add("3", "3rd"); mySortedList.Add("4", "4th"); // Checking if a SortedList object // contains a specific value Console.WriteLine(mySortedList.ContainsValue(null)); }}
False
Example 2:
CSHARP
// C# code to check if a SortedList// object contains a specific valueusing System;using System.Collections; class GFG { // Driver code public static void Main() { // Creating an SortedList SortedList mySortedList = new SortedList(); // Adding elements to SortedList mySortedList.Add("h", "Hello"); mySortedList.Add("g", "Geeks"); mySortedList.Add("f", "For"); mySortedList.Add("n", "Noida"); // Checking if a SortedList object // contains a specific value Console.WriteLine(mySortedList.ContainsValue("Geeks")); }}
True
Note:
The values of the elements of the SortedList object are compared to the specified value using the Equals method.
This method performs a linear search, therefore, the average execution time is proportional to Count, i.e, this method is an O(n) operation, where n is Count.
Reference:
https://docs.microsoft.com/en-us/dotnet/api/system.collections.sortedlist.containsvalue?view=netframework-4.7.2
sweetyty
CSharp-Collections-Namespace
CSharp-Collections-SortedList
CSharp-method
C#
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
C# | Delegates
C# | Abstract Classes
Difference between Ref and Out keywords in C#
Extension Method in C#
C# | Class and Object
C# | Replace() Method
C# | String.IndexOf( ) Method | Set - 1
C# | Constructors
Introduction to .NET Framework
C# | Data Types | [
{
"code": null,
"e": 25941,
"s": 25913,
"text": "\n06 Sep, 2021"
},
{
"code": null,
"e": 26282,
"s": 25941,
"text": "SortedList class is a collection of (key, value) pairs which are sorted according to keys. Those pairs can be accessible by key and as well as by index(zero-based indexing). This comes under System.Collections namespace. SortedList.ContainsValue(Object) method is used to check whether a SortedList object contains a specific value or not. "
},
{
"code": null,
"e": 26295,
"s": 26282,
"text": "Properties: "
},
{
"code": null,
"e": 26360,
"s": 26295,
"text": "A SortedList element can be accessed by its key or by its index."
},
{
"code": null,
"e": 26520,
"s": 26360,
"text": "A SortedList object internally maintains two arrays to store the elements of the list, i.e, one array for the keys and another array for the associated values."
},
{
"code": null,
"e": 26562,
"s": 26520,
"text": "A key cannot be null, but a value can be."
},
{
"code": null,
"e": 26649,
"s": 26562,
"text": "The capacity of a SortedList object is the number of elements the SortedList can hold."
},
{
"code": null,
"e": 26693,
"s": 26649,
"text": "A SortedList does not allow duplicate keys."
},
{
"code": null,
"e": 26807,
"s": 26693,
"text": "Operations on a SortedList object tend to be slower than operations on a Hashtable object because of the sorting."
},
{
"code": null,
"e": 26918,
"s": 26807,
"text": "Elements in this collection can be accessed using an integer index. Indexes in this collection are zero-based."
},
{
"code": null,
"e": 26928,
"s": 26918,
"text": "Syntax : "
},
{
"code": null,
"e": 26978,
"s": 26928,
"text": "public virtual bool ContainsValue (object value);"
},
{
"code": null,
"e": 27282,
"s": 26978,
"text": "Here, value is the value to locate in the SortedList object and it can be null.Return Value: This method returns True if the SortedList object contains an element with the specified value, otherwise it returns False.Below programs illustrate the use of SortedList.ContainsValue(Object) Method:Example 1:"
},
{
"code": null,
"e": 27289,
"s": 27282,
"text": "CSHARP"
},
{
"code": "// C# code to check if a SortedList// object contains a specific valueusing System;using System.Collections; class GFG { // Driver code public static void Main() { // Creating an SortedList SortedList mySortedList = new SortedList(); // Adding elements to SortedList mySortedList.Add(\"1\", \"1st\"); mySortedList.Add(\"2\", \"2nd\"); mySortedList.Add(\"3\", \"3rd\"); mySortedList.Add(\"4\", \"4th\"); // Checking if a SortedList object // contains a specific value Console.WriteLine(mySortedList.ContainsValue(null)); }}",
"e": 27882,
"s": 27289,
"text": null
},
{
"code": null,
"e": 27888,
"s": 27882,
"text": "False"
},
{
"code": null,
"e": 27901,
"s": 27890,
"text": "Example 2:"
},
{
"code": null,
"e": 27908,
"s": 27901,
"text": "CSHARP"
},
{
"code": "// C# code to check if a SortedList// object contains a specific valueusing System;using System.Collections; class GFG { // Driver code public static void Main() { // Creating an SortedList SortedList mySortedList = new SortedList(); // Adding elements to SortedList mySortedList.Add(\"h\", \"Hello\"); mySortedList.Add(\"g\", \"Geeks\"); mySortedList.Add(\"f\", \"For\"); mySortedList.Add(\"n\", \"Noida\"); // Checking if a SortedList object // contains a specific value Console.WriteLine(mySortedList.ContainsValue(\"Geeks\")); }}",
"e": 28510,
"s": 27908,
"text": null
},
{
"code": null,
"e": 28515,
"s": 28510,
"text": "True"
},
{
"code": null,
"e": 28525,
"s": 28517,
"text": "Note: "
},
{
"code": null,
"e": 28638,
"s": 28525,
"text": "The values of the elements of the SortedList object are compared to the specified value using the Equals method."
},
{
"code": null,
"e": 28797,
"s": 28638,
"text": "This method performs a linear search, therefore, the average execution time is proportional to Count, i.e, this method is an O(n) operation, where n is Count."
},
{
"code": null,
"e": 28808,
"s": 28797,
"text": "Reference:"
},
{
"code": null,
"e": 28920,
"s": 28808,
"text": "https://docs.microsoft.com/en-us/dotnet/api/system.collections.sortedlist.containsvalue?view=netframework-4.7.2"
},
{
"code": null,
"e": 28929,
"s": 28920,
"text": "sweetyty"
},
{
"code": null,
"e": 28958,
"s": 28929,
"text": "CSharp-Collections-Namespace"
},
{
"code": null,
"e": 28988,
"s": 28958,
"text": "CSharp-Collections-SortedList"
},
{
"code": null,
"e": 29002,
"s": 28988,
"text": "CSharp-method"
},
{
"code": null,
"e": 29005,
"s": 29002,
"text": "C#"
},
{
"code": null,
"e": 29103,
"s": 29005,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 29118,
"s": 29103,
"text": "C# | Delegates"
},
{
"code": null,
"e": 29140,
"s": 29118,
"text": "C# | Abstract Classes"
},
{
"code": null,
"e": 29186,
"s": 29140,
"text": "Difference between Ref and Out keywords in C#"
},
{
"code": null,
"e": 29209,
"s": 29186,
"text": "Extension Method in C#"
},
{
"code": null,
"e": 29231,
"s": 29209,
"text": "C# | Class and Object"
},
{
"code": null,
"e": 29253,
"s": 29231,
"text": "C# | Replace() Method"
},
{
"code": null,
"e": 29293,
"s": 29253,
"text": "C# | String.IndexOf( ) Method | Set - 1"
},
{
"code": null,
"e": 29311,
"s": 29293,
"text": "C# | Constructors"
},
{
"code": null,
"e": 29342,
"s": 29311,
"text": "Introduction to .NET Framework"
}
] |
Find Prime numbers in a 2D Array (Matrix) - GeeksforGeeks | 29 Nov, 2021
Given a 2d array mat[][], the task is to find and print the prime numbers along with their position (1-based indexing) in this 2d array.
Examples:
Input: mat[][] = {{1, 2}, {2, 1}}
Output:
1 2 2
2 1 2
Explanation: First prime is at position row 1 and column 2 and the value is 2
Second prime is at position row 2 and column 1 and the value is 2
Input: mat[][] = {{1, 1}, {1, 1}}
Output: -1
Explanation: There is no prime number in this 2d array
Naive Approach: The basic idea is to traverse the 2d array and for each number, check whether it is prime or not. If it is prime, print the position and the value for each found prime number.Time Complexity: O(NM*sqrt(X)), where N*M is the size of the matrix and X is the largest element in the matrixAuxiliary Space: O(1)
Efficient Approach: We can efficiently check if the number is prime or not using sieve. Then traverse the 2d array and simply check if the number is prime or not in O(1).
Follow the below steps for implementing this approach:
Find the maximum element from the matrix and store it in a variable maxNum.
Now find the prime numbers from 1 to maxNum using sieve of eratosthenes and store the result in array prime[].
Now traverse the matrix and for each number check if it is a prime or not using the prime[] array.
For each prime number in matrix print its position (row, column) and value.
Below is the implementation of the above approach:
C++
Java
Python3
C#
Javascript
// C++ code to implement the above approach
#include <bits/stdc++.h>
using namespace std;
#define MAXN 100001
bool prime[MAXN];
// Function to find prime numbers using sieve
void SieveOfEratosthenes()
{
int n = MAXN - 1;
// Create a boolean array
// "prime[0..n]" and initialize
// all entries it as true.
// A value in prime[i] will
// finally be false if i is
// Not a prime, else true.
memset(prime, true, sizeof(prime));
prime[0] = false;
prime[1] = false;
for (int p = 2; p * p <= n; p++) {
// If prime[p] is not changed,
// then it is a prime
if (prime[p] == true) {
// Update all multiples
// of p greater than or
// equal to the square of it
// numbers which are multiple
// of p and are less than p^2
// are already been marked.
for (int i = p * p; i <= n; i += p)
prime[i] = false;
}
}
}
// Function to print the position and
// value of the primes in given matrix
void printPrimes(vector<vector<int> >& arr, int n)
{
// Traverse the matrix
for (int i = 0; i < n; i++) {
for (int j = 0; j < n; j++) {
// Check if the element is prime
// or not in O(1)
if (prime[arr[i][j]] == true) {
// Print the position and value
// if found true
cout << i + 1 << " " << j + 1 << " "
<< arr[i][j] << endl;
}
}
}
}
// Driver Code
int main()
{
int N = 2;
vector<vector<int> > arr;
vector<int> temp(N, 2);
temp[0] = 1;
temp[1] = 2;
arr.push_back(temp);
temp[0] = 2;
temp[1] = 1;
arr.push_back(temp);
// Precomputing prime numbers using sieve
SieveOfEratosthenes();
// Find and print prime numbers
// present in the matrix
printPrimes(arr, N);
return 0;
}
// Java program for the above approach
import java.util.*;
class GFG {
static int MAXN = 100001;
static boolean prime[] = new boolean[MAXN];
// Function to find prime numbers using sieve
static void SieveOfEratosthenes()
{
int n = MAXN - 1;
Arrays.fill(prime, true);
// Create a boolean array
// "prime[0..n]" and initialize
// all entries it as true.
// A value in prime[i] will
// finally be false if i is
// Not a prime, else true.
prime[0] = false;
prime[1] = false;
for (int p = 2; p * p <= n; p++) {
// If prime[p] is not changed,
// then it is a prime
if (prime[p] == true) {
// Update all multiples
// of p greater than or
// equal to the square of it
// numbers which are multiple
// of p and are less than p^2
// are already been marked.
for (int i = p * p; i <= n; i = i + p)
prime[i] = false;
}
}
}
// Function to print the position and
// value of the primes in given matrix
static void printPrimes(int[][] arr, int n)
{
// Traverse the matrix
for (int i = 0; i < n; i++) {
for (int j = 0; j < n; j++) {
// Check if the element is prime
// or not in O(1)
if (prime[arr[i][j]] == true) {
// Print the position and value
// if found true
System.out.print((i + 1));
System.out.print(" ");
System.out.print(j + 1);
System.out.print(" ");
System.out.print(arr[i][j]);
System.out.println();
}
}
}
}
// Driver Code
public static void main(String[] args)
{
int N = 2;
int arr[][] = new int[N][N];
arr[0][0] = 1;
arr[0][1] = 2;
arr[1][0] = 2;
arr[1][1] = 1;
// Precomputing prime numbers using sieve
SieveOfEratosthenes();
// Find and print prime numbers
// present in the matrix
printPrimes(arr, N);
}
}
// This code is contributed by Potta Lokesh
# python code to implement the above approach
import math
MAXN = 100001
prime = [True for _ in range(MAXN)]
# Function to find prime numbers using sieve
def SieveOfEratosthenes():
global prime
n = MAXN - 1
# Create a boolean array
# "prime[0..n]" and initialize
# all entries it as true.
# A value in prime[i] will
# finally be false if i is
# Not a prime, else true.
prime[0] = False
prime[1] = False
for p in range(2, int(math.sqrt(n)) + 1):
# If prime[p] is not changed,
# then it is a prime
if (prime[p] == True):
# Update all multiples
# of p greater than or
# equal to the square of it
# numbers which are multiple
# of p and are less than p^2
# are already been marked.
for i in range(p*p, n+1, p):
prime[i] = False
# Function to print the position and
# value of the primes in given matrix
def printPrimes(arr, n):
# Traverse the matrix
for i in range(0, n):
for j in range(0, n):
# Check if the element is prime
# or not in O(1)
if (prime[arr[i][j]] == True):
# Print the position and value
# if found true
print(f"{i + 1} {j + 1} {arr[i][j]}")
# Driver Code
if __name__ == "__main__":
N = 2
arr = []
temp = [2 for _ in range(N)]
temp[0] = 1
temp[1] = 2
arr.append(temp.copy())
temp[0] = 2
temp[1] = 1
arr.append(temp.copy())
# Precomputing prime numbers using sieve
SieveOfEratosthenes()
# Find and print prime numbers
# present in the matrix
printPrimes(arr, N)
# This code is contributed by rakeshsahni
// C# program for the above approach
using System;
using System.Collections.Generic;
class GFG {
static int MAXN = 100001;
static bool[] prime = new bool[MAXN];
// Function to find prime numbers using sieve
static void SieveOfEratosthenes()
{
int n = MAXN - 1;
Array.Fill(prime, true);
// Create a boolean array
// "prime[0..n]" and initialize
// all entries it as true.
// A value in prime[i] will
// finally be false if i is
// Not a prime, else true.
prime[0] = false;
prime[1] = false;
for (int p = 2; p * p <= n; p++) {
// If prime[p] is not changed,
// then it is a prime
if (prime[p] == true) {
// Update all multiples
// of p greater than or
// equal to the square of it
// numbers which are multiple
// of p and are less than p^2
// are already been marked.
for (int i = p * p; i <= n; i = i + p)
prime[i] = false;
}
}
}
// Function to print the position and
// value of the primes in given matrix
static void printPrimes(int[,] arr, int n)
{
// Traverse the matrix
for (int i = 0; i < n; i++) {
for (int j = 0; j < n; j++) {
// Check if the element is prime
// or not in O(1)
if (prime[arr[i,j]] == true) {
// Print the position and value
// if found true
Console.Write((i + 1));
Console.Write(" ");
Console.Write(j + 1);
Console.Write(" ");
Console.Write(arr[i,j]);
Console.WriteLine();
}
}
}
}
// Driver Code
public static void Main(String[] args)
{
int N = 2;
int[,] arr = new int[N,N];
arr[0,0] = 1;
arr[0,1] = 2;
arr[1,0] = 2;
arr[1,1] = 1;
// Precomputing prime numbers using sieve
SieveOfEratosthenes();
// Find and print prime numbers
// present in the matrix
printPrimes(arr, N);
}
}
// This code is contributed by Saurabh Jaiswal
<script>
// JavaScript Program to implement
// the above approach
let MAXN = 100001
let prime = new Array(MAXN).fill(true);
// Function to find prime numbers using sieve
function SieveOfEratosthenes() {
let n = MAXN - 1;
// Create a boolean array
// "prime[0..n]" and initialize
// all entries it as true.
// A value in prime[i] will
// finally be false if i is
// Not a prime, else true.
prime[0] = false;
prime[1] = false;
for (let p = 2; p * p <= n; p++) {
// If prime[p] is not changed,
// then it is a prime
if (prime[p] == true) {
// Update all multiples
// of p greater than or
// equal to the square of it
// numbers which are multiple
// of p and are less than p^2
// are already been marked.
for (let i = p * p; i <= n; i = i + p)
prime[i] = false;
}
}
}
// Function to print the position and
// value of the primes in given matrix
function printPrimes(arr, n) {
// Traverse the matrix
for (let i = 0; i < n; i++) {
for (let j = 0; j < n; j++) {
// Check if the element is prime
// or not in O(1)
if (prime[arr[i][j]] == true) {
// Print the position and value
// if found true
document.write((i + 1) + " " + (j + 1) + " "
+ (arr[i][j]) + "<br>");
}
}
}
}
// Driver Code
let N = 2;
let arr = new Array(N);
let temp = [1, 2]
arr[0] = temp;
let temp1 = [2, 1]
arr[1] = temp1;
// Precomputing prime numbers using sieve
SieveOfEratosthenes();
// Find and print prime numbers
// present in the matrix
printPrimes(arr, N);
// This code is contributed by Potta Lokesh
</script>
1 2 2
2 1 2
Time Complexity: O(N*M) where N*M is the size of matrix.Auxiliary Space: O(maxNum) where maxNum is the largest element in the matrix.
rakeshsahni
lokeshpotta20
_saurabh_jaiswal
Prime Number
sieve
Arrays
Mathematical
Matrix
Searching
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Chocolate Distribution Problem
Window Sliding Technique
Reversal algorithm for array rotation
Next Greater Element
Find duplicates in O(n) time and O(1) extra space | Set 1
Program for Fibonacci numbers
Write a program to print all permutations of a given string
C++ Data Types
Set in C++ Standard Template Library (STL)
Coin Change | DP-7 | [
{
"code": null,
"e": 26115,
"s": 26084,
"text": " \n29 Nov, 2021\n"
},
{
"code": null,
"e": 26252,
"s": 26115,
"text": "Given a 2d array mat[][], the task is to find and print the prime numbers along with their position (1-based indexing) in this 2d array."
},
{
"code": null,
"e": 26262,
"s": 26252,
"text": "Examples:"
},
{
"code": null,
"e": 26298,
"s": 26262,
"text": "Input: mat[][] = {{1, 2}, {2, 1}} "
},
{
"code": null,
"e": 26307,
"s": 26298,
"text": "Output: "
},
{
"code": null,
"e": 26313,
"s": 26307,
"text": "1 2 2"
},
{
"code": null,
"e": 26319,
"s": 26313,
"text": "2 1 2"
},
{
"code": null,
"e": 26398,
"s": 26319,
"text": "Explanation: First prime is at position row 1 and column 2 and the value is 2"
},
{
"code": null,
"e": 26464,
"s": 26398,
"text": "Second prime is at position row 2 and column 1 and the value is 2"
},
{
"code": null,
"e": 26500,
"s": 26464,
"text": "Input: mat[][] = {{1, 1}, {1, 1}} "
},
{
"code": null,
"e": 26511,
"s": 26500,
"text": "Output: -1"
},
{
"code": null,
"e": 26567,
"s": 26511,
"text": "Explanation: There is no prime number in this 2d array"
},
{
"code": null,
"e": 26891,
"s": 26567,
"text": "Naive Approach: The basic idea is to traverse the 2d array and for each number, check whether it is prime or not. If it is prime, print the position and the value for each found prime number.Time Complexity: O(NM*sqrt(X)), where N*M is the size of the matrix and X is the largest element in the matrixAuxiliary Space: O(1) "
},
{
"code": null,
"e": 27063,
"s": 26891,
"text": "Efficient Approach: We can efficiently check if the number is prime or not using sieve. Then traverse the 2d array and simply check if the number is prime or not in O(1). "
},
{
"code": null,
"e": 27118,
"s": 27063,
"text": "Follow the below steps for implementing this approach:"
},
{
"code": null,
"e": 27194,
"s": 27118,
"text": "Find the maximum element from the matrix and store it in a variable maxNum."
},
{
"code": null,
"e": 27305,
"s": 27194,
"text": "Now find the prime numbers from 1 to maxNum using sieve of eratosthenes and store the result in array prime[]."
},
{
"code": null,
"e": 27404,
"s": 27305,
"text": "Now traverse the matrix and for each number check if it is a prime or not using the prime[] array."
},
{
"code": null,
"e": 27480,
"s": 27404,
"text": "For each prime number in matrix print its position (row, column) and value."
},
{
"code": null,
"e": 27531,
"s": 27480,
"text": "Below is the implementation of the above approach:"
},
{
"code": null,
"e": 27535,
"s": 27531,
"text": "C++"
},
{
"code": null,
"e": 27540,
"s": 27535,
"text": "Java"
},
{
"code": null,
"e": 27548,
"s": 27540,
"text": "Python3"
},
{
"code": null,
"e": 27551,
"s": 27548,
"text": "C#"
},
{
"code": null,
"e": 27562,
"s": 27551,
"text": "Javascript"
},
{
"code": "\n\n\n\n\n\n\n// C++ code to implement the above approach\n#include <bits/stdc++.h>\nusing namespace std;\n \n#define MAXN 100001\nbool prime[MAXN];\n \n// Function to find prime numbers using sieve\nvoid SieveOfEratosthenes()\n{\n int n = MAXN - 1;\n \n // Create a boolean array\n // \"prime[0..n]\" and initialize\n // all entries it as true.\n // A value in prime[i] will\n // finally be false if i is\n // Not a prime, else true.\n memset(prime, true, sizeof(prime));\n prime[0] = false;\n prime[1] = false;\n \n for (int p = 2; p * p <= n; p++) {\n // If prime[p] is not changed,\n // then it is a prime\n if (prime[p] == true) {\n // Update all multiples\n // of p greater than or\n // equal to the square of it\n // numbers which are multiple\n // of p and are less than p^2\n // are already been marked.\n for (int i = p * p; i <= n; i += p)\n prime[i] = false;\n }\n }\n}\n \n// Function to print the position and\n// value of the primes in given matrix\nvoid printPrimes(vector<vector<int> >& arr, int n)\n{\n // Traverse the matrix\n for (int i = 0; i < n; i++) {\n for (int j = 0; j < n; j++) {\n \n // Check if the element is prime\n // or not in O(1)\n if (prime[arr[i][j]] == true) {\n // Print the position and value\n // if found true\n cout << i + 1 << \" \" << j + 1 << \" \"\n << arr[i][j] << endl;\n }\n }\n }\n}\n \n// Driver Code\nint main()\n{\n int N = 2;\n vector<vector<int> > arr;\n vector<int> temp(N, 2);\n temp[0] = 1;\n temp[1] = 2;\n arr.push_back(temp);\n temp[0] = 2;\n temp[1] = 1;\n arr.push_back(temp);\n \n // Precomputing prime numbers using sieve\n SieveOfEratosthenes();\n \n // Find and print prime numbers\n // present in the matrix\n printPrimes(arr, N);\n return 0;\n}\n\n\n\n\n\n",
"e": 29536,
"s": 27572,
"text": null
},
{
"code": "\n\n\n\n\n\n\n// Java program for the above approach\nimport java.util.*;\n \nclass GFG {\n \n static int MAXN = 100001;\n static boolean prime[] = new boolean[MAXN];\n \n // Function to find prime numbers using sieve\n static void SieveOfEratosthenes()\n {\n int n = MAXN - 1;\n Arrays.fill(prime, true);\n \n // Create a boolean array\n // \"prime[0..n]\" and initialize\n // all entries it as true.\n // A value in prime[i] will\n // finally be false if i is\n // Not a prime, else true.\n prime[0] = false;\n prime[1] = false;\n \n for (int p = 2; p * p <= n; p++) {\n // If prime[p] is not changed,\n // then it is a prime\n if (prime[p] == true) {\n // Update all multiples\n // of p greater than or\n // equal to the square of it\n // numbers which are multiple\n // of p and are less than p^2\n // are already been marked.\n for (int i = p * p; i <= n; i = i + p)\n prime[i] = false;\n }\n }\n }\n \n // Function to print the position and\n // value of the primes in given matrix\n static void printPrimes(int[][] arr, int n)\n {\n // Traverse the matrix\n for (int i = 0; i < n; i++) {\n for (int j = 0; j < n; j++) {\n \n // Check if the element is prime\n // or not in O(1)\n if (prime[arr[i][j]] == true) {\n // Print the position and value\n // if found true\n System.out.print((i + 1));\n System.out.print(\" \");\n System.out.print(j + 1);\n System.out.print(\" \");\n System.out.print(arr[i][j]);\n System.out.println();\n }\n }\n }\n }\n \n // Driver Code\n public static void main(String[] args)\n {\n int N = 2;\n int arr[][] = new int[N][N];\n \n arr[0][0] = 1;\n arr[0][1] = 2;\n arr[1][0] = 2;\n arr[1][1] = 1;\n \n // Precomputing prime numbers using sieve\n SieveOfEratosthenes();\n \n // Find and print prime numbers\n // present in the matrix\n printPrimes(arr, N);\n }\n}\n \n// This code is contributed by Potta Lokesh\n\n\n\n\n\n",
"e": 31938,
"s": 29546,
"text": null
},
{
"code": "\n\n\n\n\n\n\n# python code to implement the above approach\nimport math\nMAXN = 100001\nprime = [True for _ in range(MAXN)]\n \n# Function to find prime numbers using sieve\ndef SieveOfEratosthenes():\n global prime\n \n n = MAXN - 1\n \n # Create a boolean array\n # \"prime[0..n]\" and initialize\n # all entries it as true.\n # A value in prime[i] will\n # finally be false if i is\n # Not a prime, else true.\n prime[0] = False\n prime[1] = False\n \n for p in range(2, int(math.sqrt(n)) + 1):\n \n # If prime[p] is not changed,\n # then it is a prime\n if (prime[p] == True):\n \n # Update all multiples\n # of p greater than or\n # equal to the square of it\n # numbers which are multiple\n # of p and are less than p^2\n # are already been marked.\n for i in range(p*p, n+1, p):\n prime[i] = False\n \n# Function to print the position and\n# value of the primes in given matrix\ndef printPrimes(arr, n):\n \n # Traverse the matrix\n for i in range(0, n):\n for j in range(0, n):\n \n # Check if the element is prime\n # or not in O(1)\n if (prime[arr[i][j]] == True):\n \n # Print the position and value\n # if found true\n print(f\"{i + 1} {j + 1} {arr[i][j]}\")\n \n# Driver Code\nif __name__ == \"__main__\":\n \n N = 2\n arr = []\n temp = [2 for _ in range(N)]\n \n temp[0] = 1\n temp[1] = 2\n arr.append(temp.copy())\n temp[0] = 2\n temp[1] = 1\n arr.append(temp.copy())\n \n # Precomputing prime numbers using sieve\n SieveOfEratosthenes()\n \n # Find and print prime numbers\n # present in the matrix\n printPrimes(arr, N)\n \n # This code is contributed by rakeshsahni\n\n\n\n\n\n",
"e": 33808,
"s": 31948,
"text": null
},
{
"code": "\n\n\n\n\n\n\n// C# program for the above approach\nusing System;\nusing System.Collections.Generic;\nclass GFG {\n \n static int MAXN = 100001;\n static bool[] prime = new bool[MAXN];\n \n // Function to find prime numbers using sieve\n static void SieveOfEratosthenes()\n {\n int n = MAXN - 1;\n Array.Fill(prime, true);\n \n // Create a boolean array\n // \"prime[0..n]\" and initialize\n // all entries it as true.\n // A value in prime[i] will\n // finally be false if i is\n // Not a prime, else true.\n prime[0] = false;\n prime[1] = false;\n \n for (int p = 2; p * p <= n; p++) {\n // If prime[p] is not changed,\n // then it is a prime\n if (prime[p] == true) {\n // Update all multiples\n // of p greater than or\n // equal to the square of it\n // numbers which are multiple\n // of p and are less than p^2\n // are already been marked.\n for (int i = p * p; i <= n; i = i + p)\n prime[i] = false;\n }\n }\n }\n \n // Function to print the position and\n // value of the primes in given matrix\n static void printPrimes(int[,] arr, int n)\n {\n // Traverse the matrix\n for (int i = 0; i < n; i++) {\n for (int j = 0; j < n; j++) {\n \n // Check if the element is prime\n // or not in O(1)\n if (prime[arr[i,j]] == true) {\n // Print the position and value\n // if found true\n Console.Write((i + 1));\n Console.Write(\" \");\n Console.Write(j + 1);\n Console.Write(\" \");\n Console.Write(arr[i,j]);\n Console.WriteLine();\n }\n }\n }\n }\n \n // Driver Code\n public static void Main(String[] args)\n {\n int N = 2;\n int[,] arr = new int[N,N];\n \n arr[0,0] = 1;\n arr[0,1] = 2;\n arr[1,0] = 2;\n arr[1,1] = 1;\n \n // Precomputing prime numbers using sieve\n SieveOfEratosthenes();\n \n // Find and print prime numbers\n // present in the matrix\n printPrimes(arr, N);\n }\n}\n \n// This code is contributed by Saurabh Jaiswal\n\n\n\n\n\n",
"e": 36205,
"s": 33818,
"text": null
},
{
"code": "\n\n\n\n\n\n\n<script>\n \n // JavaScript Program to implement\n // the above approach \n \n \n let MAXN = 100001\n let prime = new Array(MAXN).fill(true);\n \n // Function to find prime numbers using sieve\n function SieveOfEratosthenes() {\n let n = MAXN - 1;\n \n // Create a boolean array\n // \"prime[0..n]\" and initialize\n // all entries it as true.\n // A value in prime[i] will\n // finally be false if i is\n // Not a prime, else true.\n \n prime[0] = false;\n prime[1] = false;\n \n for (let p = 2; p * p <= n; p++) {\n // If prime[p] is not changed,\n // then it is a prime\n if (prime[p] == true) {\n // Update all multiples\n // of p greater than or\n // equal to the square of it\n // numbers which are multiple\n // of p and are less than p^2\n // are already been marked.\n for (let i = p * p; i <= n; i = i + p)\n prime[i] = false;\n }\n }\n }\n \n // Function to print the position and\n // value of the primes in given matrix\n function printPrimes(arr, n) {\n // Traverse the matrix\n for (let i = 0; i < n; i++) {\n for (let j = 0; j < n; j++) {\n \n // Check if the element is prime\n // or not in O(1)\n if (prime[arr[i][j]] == true) {\n // Print the position and value\n // if found true\n document.write((i + 1) + \" \" + (j + 1) + \" \"\n + (arr[i][j]) + \"<br>\");\n }\n }\n }\n }\n \n // Driver Code\n \n let N = 2;\n let arr = new Array(N);\n let temp = [1, 2]\n arr[0] = temp;\n let temp1 = [2, 1]\n arr[1] = temp1;\n \n // Precomputing prime numbers using sieve\n SieveOfEratosthenes();\n \n // Find and print prime numbers\n // present in the matrix\n printPrimes(arr, N);\n \n \n // This code is contributed by Potta Lokesh\n </script>\n\n\n\n\n\n",
"e": 38479,
"s": 36215,
"text": null
},
{
"code": null,
"e": 38494,
"s": 38482,
"text": "1 2 2\n2 1 2"
},
{
"code": null,
"e": 38631,
"s": 38496,
"text": "Time Complexity: O(N*M) where N*M is the size of matrix.Auxiliary Space: O(maxNum) where maxNum is the largest element in the matrix. "
},
{
"code": null,
"e": 38645,
"s": 38633,
"text": "rakeshsahni"
},
{
"code": null,
"e": 38659,
"s": 38645,
"text": "lokeshpotta20"
},
{
"code": null,
"e": 38676,
"s": 38659,
"text": "_saurabh_jaiswal"
},
{
"code": null,
"e": 38691,
"s": 38676,
"text": "\nPrime Number\n"
},
{
"code": null,
"e": 38699,
"s": 38691,
"text": "\nsieve\n"
},
{
"code": null,
"e": 38708,
"s": 38699,
"text": "\nArrays\n"
},
{
"code": null,
"e": 38723,
"s": 38708,
"text": "\nMathematical\n"
},
{
"code": null,
"e": 38732,
"s": 38723,
"text": "\nMatrix\n"
},
{
"code": null,
"e": 38744,
"s": 38732,
"text": "\nSearching\n"
},
{
"code": null,
"e": 38949,
"s": 38744,
"text": "Writing code in comment? \n Please use ide.geeksforgeeks.org, \n generate link and share the link here.\n "
},
{
"code": null,
"e": 38980,
"s": 38949,
"text": "Chocolate Distribution Problem"
},
{
"code": null,
"e": 39005,
"s": 38980,
"text": "Window Sliding Technique"
},
{
"code": null,
"e": 39043,
"s": 39005,
"text": "Reversal algorithm for array rotation"
},
{
"code": null,
"e": 39064,
"s": 39043,
"text": "Next Greater Element"
},
{
"code": null,
"e": 39122,
"s": 39064,
"text": "Find duplicates in O(n) time and O(1) extra space | Set 1"
},
{
"code": null,
"e": 39152,
"s": 39122,
"text": "Program for Fibonacci numbers"
},
{
"code": null,
"e": 39213,
"s": 39152,
"text": "Write a program to print all permutations of a given string"
},
{
"code": null,
"e": 39228,
"s": 39213,
"text": "C++ Data Types"
},
{
"code": null,
"e": 39271,
"s": 39228,
"text": "Set in C++ Standard Template Library (STL)"
}
] |
C++ Program to Implement Queue in STL | A queue is a linear structure which follows First In First Out (FIFO) order in which the operations are performed on the elements of the queue.
Functions used here:
q.size() = Returns the size of queue.
q.push() = It is used to insert elements to the queue.
q.pop() = To pop out the value from the queue.
q.front() = Returns the front element of the array.
q.back() = Returns the back element of the array.
#include<iostream>
#include <queue>
#include <string>
#include <cstdlib>
using namespace std;
int main() {
queue<int> q;
int c, i;
while (1) {
cout<<"1.Size of the Queue"<<endl;
cout<<"2.Insert Element into the Queue"<<endl;
cout<<"3.Delete Element from the Queue"<<endl;
cout<<"4.Front Element of the Queue"<<endl;
cout<<"5.Last Element of the Queue"<<endl;
cout<<"6.Exit"<<endl;
cout<<"Enter your Choice: ";
cin>>c;
switch(c) {
case 1:
cout<<"Size of the Queue: ";
cout<<q.size()<<endl;
break;
case 2:
cout<<"Enter value to be inserted: ";
cin>>i;
q.push(i);
break;
case 3:
i = q.front();
q.pop();
cout<<"Element "<<i<<" Deleted"<<endl;
break;
case 4:
cout<<"Front Element of the Queue: ";
cout<<q.front()<<endl;
break;
case 5:
cout<<"Back Element of the Queue: ";
cout<<q.back()<<endl;
break;
case 6:
exit(1);
break;
default:
cout<<"Wrong Choice"<<endl;
}
}
return 0;
}
1.Size of the Queue
2.Insert Element into the Queue
3.Delete Element from the Queue
4.Front Element of the Queue
5.Last Element of the Queue
6.Exit
Enter your Choice: 1
Size of the Queue: 0
1.Size of the Queue
2.Insert Element into the Queue
3.Delete Element from the Queue
4.Front Element of the Queue
5.Last Element of the Queue
6.Exit
Enter your Choice: 2
Enter value to be inserted: 1
1.Size of the Queue
2.Insert Element into the Queue
3.Delete Element from the Queue
4.Front Element of the Queue
5.Last Element of the Queue
6.Exit
Enter your Choice: 2
Enter value to be inserted: 2
1.Size of the Queue
2.Insert Element into the Queue
3.Delete Element from the Queue
4.Front Element of the Queue
5.Last Element of the Queue
6.Exit
Enter your Choice: 3
Element 1 Deleted
1.Size of the Queue
2.Insert Element into the Queue
3.Delete Element from the Queue
4.Front Element of the Queue
5.Last Element of the Queue
6.Exit
Enter your Choice: 2
Enter value to be inserted: 4
1.Size of the Queue
2.Insert Element into the Queue
3.Delete Element from the Queue
4.Front Element of the Queue
5.Last Element of the Queue
6.Exit
Enter your Choice: 2
Enter value to be inserted: 7
1.Size of the Queue
2.Insert Element into the Queue
3.Delete Element from the Queue
4.Front Element of the Queue
5.Last Element of the Queue
6.Exit
Enter your Choice: 2
Enter value to be inserted: 6
1.Size of the Queue
2.Insert Element into the Queue
3.Delete Element from the Queue
4.Front Element of the Queue
5.Last Element of the Queue
6.Exit
Enter your Choice: 4
Front Element of the Queue: 2
1.Size of the Queue
2.Insert Element into the Queue
3.Delete Element from the Queue
4.Front Element of the Queue
5.Last Element of the Queue
6.Exit
Enter your Choice: 5
Back Element of the Queue: 6
1.Size of the Queue
2.Insert Element into the Queue
3.Delete Element from the Queue
4.Front Element of the Queue
5.Last Element of the Queue
6.Exit
Enter your Choice: 6
Exit code: 1 | [
{
"code": null,
"e": 1206,
"s": 1062,
"text": "A queue is a linear structure which follows First In First Out (FIFO) order in which the operations are performed on the elements of the queue."
},
{
"code": null,
"e": 1484,
"s": 1206,
"text": "Functions used here:\n q.size() = Returns the size of queue.\n q.push() = It is used to insert elements to the queue.\n q.pop() = To pop out the value from the queue.\n q.front() = Returns the front element of the array.\n q.back() = Returns the back element of the array."
},
{
"code": null,
"e": 2717,
"s": 1484,
"text": "#include<iostream>\n#include <queue>\n#include <string>\n#include <cstdlib>\nusing namespace std;\nint main() {\n queue<int> q;\n int c, i;\n while (1) {\n cout<<\"1.Size of the Queue\"<<endl;\n cout<<\"2.Insert Element into the Queue\"<<endl;\n cout<<\"3.Delete Element from the Queue\"<<endl;\n cout<<\"4.Front Element of the Queue\"<<endl;\n cout<<\"5.Last Element of the Queue\"<<endl;\n cout<<\"6.Exit\"<<endl;\n cout<<\"Enter your Choice: \";\n cin>>c;\n switch(c) {\n case 1:\n cout<<\"Size of the Queue: \";\n cout<<q.size()<<endl;\n break;\n case 2:\n cout<<\"Enter value to be inserted: \";\n cin>>i;\n q.push(i);\n break;\n case 3:\n i = q.front();\n q.pop();\n cout<<\"Element \"<<i<<\" Deleted\"<<endl;\n break;\n case 4:\n cout<<\"Front Element of the Queue: \";\n cout<<q.front()<<endl;\n break;\n case 5:\n cout<<\"Back Element of the Queue: \";\n cout<<q.back()<<endl;\n break;\n case 6:\n exit(1);\n break;\n default:\n cout<<\"Wrong Choice\"<<endl;\n }\n }\n return 0;\n}"
},
{
"code": null,
"e": 4677,
"s": 2717,
"text": "1.Size of the Queue\n2.Insert Element into the Queue\n3.Delete Element from the Queue\n4.Front Element of the Queue\n5.Last Element of the Queue\n6.Exit\n\nEnter your Choice: 1\nSize of the Queue: 0\n1.Size of the Queue\n2.Insert Element into the Queue\n3.Delete Element from the Queue\n4.Front Element of the Queue\n5.Last Element of the Queue\n6.Exit\n\nEnter your Choice: 2\nEnter value to be inserted: 1\n1.Size of the Queue\n2.Insert Element into the Queue\n3.Delete Element from the Queue\n4.Front Element of the Queue\n5.Last Element of the Queue\n6.Exit\n\nEnter your Choice: 2\nEnter value to be inserted: 2\n1.Size of the Queue\n2.Insert Element into the Queue\n3.Delete Element from the Queue\n4.Front Element of the Queue\n5.Last Element of the Queue\n6.Exit\n\nEnter your Choice: 3\nElement 1 Deleted\n1.Size of the Queue\n2.Insert Element into the Queue\n3.Delete Element from the Queue\n4.Front Element of the Queue\n5.Last Element of the Queue\n6.Exit\n\nEnter your Choice: 2\nEnter value to be inserted: 4\n1.Size of the Queue\n2.Insert Element into the Queue\n3.Delete Element from the Queue\n4.Front Element of the Queue\n5.Last Element of the Queue\n6.Exit\n\nEnter your Choice: 2\nEnter value to be inserted: 7\n1.Size of the Queue\n2.Insert Element into the Queue\n3.Delete Element from the Queue\n4.Front Element of the Queue\n5.Last Element of the Queue\n6.Exit\n\nEnter your Choice: 2\nEnter value to be inserted: 6\n1.Size of the Queue\n2.Insert Element into the Queue\n3.Delete Element from the Queue\n4.Front Element of the Queue\n5.Last Element of the Queue\n6.Exit\n\nEnter your Choice: 4\nFront Element of the Queue: 2\n1.Size of the Queue\n2.Insert Element into the Queue\n3.Delete Element from the Queue\n4.Front Element of the Queue\n5.Last Element of the Queue\n6.Exit\n\nEnter your Choice: 5\nBack Element of the Queue: 6\n1.Size of the Queue\n2.Insert Element into the Queue\n3.Delete Element from the Queue\n4.Front Element of the Queue\n5.Last Element of the Queue\n6.Exit\nEnter your Choice: 6\nExit code: 1"
}
] |
Java Program to Segregate 0s on Left Side & 1s on Right Side of the Array - GeeksforGeeks | 30 Mar, 2022
You are given an array of 0s and 1s in random order. Segregate 0s on the left side and 1s on the right side of the array. The basic goal is to traverse array elements and sort in segregating 0s and 1s.
Illustration:
Input array = [0, 1, 0, 1, 0, 0, 1, 1, 1, 0]
Output array = [0, 0, 0, 0, 0, 1, 1, 1, 1, 1]
Approaches:
Using segregation by counting Using sorting of an arrayUsing pointers
Using segregation by counting
Using sorting of an array
Using pointers
Below all three approaches all discussed in detail:
Approach 1:
Count the number of 0s.
Traversing over the whole array for looking out indices where zeros are present
Maintaining a count and incrementing as 0 appears
Print all zeros to the front
The remaining number of 1s will be 1- (total number of 0s)
Print the remaining elements
Below is the implementation to segregate 0s and 1s using the above algorithm:
Java
// Java code to Segregate 0s and 1s in an array // Importing generic librariesimport java.util.*;// Importing Array librariesimport java.util.Arrays; public class GFG { // Function to segregate 0s and 1s static void segregate0and1(int arr[], int n) { // Counts the no of zeros in array int count = 0; // Iteration over array for (int i = 0; i < n; i++) { if (arr[i] == 0) // Incrementing the count count++; } // Loop fills the arr with 0 until count for (int i = 0; i < count; i++) arr[i] = 0; // Loop fills remaining arr space with 1 for (int i = count; i < n; i++) arr[i] = 1; } // Function to print segregated array static void print(int arr[], int n) { System.out.print("Array after segregation is "); // Iteration over array for (int i = 0; i < n; i++) System.out.print(arr[i] + " "); } // Main driver function public static void main(String[] args) { // Array taken for consideration int arr[] = new int[] { 0, 1, 0, 1, 1, 1 }; // Using inbuilt function to store array size int n = arr.length; // Calling function that segregates array segregate0and1(arr, n); // Printing the above segregated array print(arr, n); }}
Output:
Array after segregation is 0 0 1 1 1 1
Time Complexity: O(n)
Auxiliary Space: O(1)
Approach 2: Using sort() function
sort() Is a method is a java.util.Arrays class method.
Syntax:
public static void sort(int[] arr, int from_Index, int to_Index)
Parameters:
arr - the array to be sorted
from_Index - the index of the first element, inclusive, to be sorted
to_Index - the index of the last element, exclusive, to be sorted
Return Type:
This method doesn't return any value
Java
// Java code to Segregate 0s and 1s in an array // Importing generic librariesimport java.util.*; public class GFG { // Function to print segregated array // Taking arguments- array and array size static void print(int arr[], int n) { System.out.print("Array after segregation is "); // Iteration over array for (int i = 0; i < n; ++i) // Printing array elements System.out.print(arr[i] + " "); } // Main driver function public static void main(String[] args) { // Array taken for consideration int arr[] = new int[] { 0, 1, 0, 1, 1, 1 }; // Using length inbuilt function to int n = arr.length; // Using sort inbuilt function Arrays.sort(arr); // Printing elements after executing sorting print(arr, n); }}
Output:
Array after segregation is 0 0 1 1 1 1
Time Complexity: O(n*logn)
Auxiliary Space: O(1)
Approach 3: Maintain the left pointer and swap with the position of the left when zero found in the array and increment the left pointer.
Java
// Java code to Segregate 0s and 1s in an array // Importing generic librariesimport java.util.*;import java.io.*; class GFG { // Print function outside main to print elements static void print(int a[]) { System.out.print("Array after segregation is: "); // Iteration over array using array // class inbuilt function .length() for (int i = 0; i < a.length; ++i) { // Printing elements in array System.out.print(a[i] + " "); } } // Main driver method public static void main(String[] args) { // Random array taken for consideration int a[] = { 1, 1, 0, 0, 0, 0, 1, 1 }; // Maintaining left pointer int left = 0; // Iteration over array using length function for (int i = 0; i < a.length; ++i) { // If zeros are present if (a[i] == 0) { // Swap the elements using // temporary variable int temp = a[left]; a[left] = a[i]; a[i] = temp; // Pre incrementing left pointer ++left; } } // Calling above function to // print updated array print(a); }}
Output:
Array after segregation is: 0 0 0 0 1 1 1 1
Time Complexity: O(n)
Auxiliary Space: O(1)
kalrap615
rohan07
Java-Array-Programs
Picked
Technical Scripter 2020
Java
Java Programs
Technical Scripter
Java
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Stream In Java
Constructors in Java
Exceptions in Java
Functional Interfaces in Java
Different ways of Reading a text file in Java
Java Programming Examples
Convert Double to Integer in Java
Implementing a Linked List in Java using Class
How to Iterate HashMap in Java?
Iterate through List in Java | [
{
"code": null,
"e": 25237,
"s": 25209,
"text": "\n30 Mar, 2022"
},
{
"code": null,
"e": 25440,
"s": 25237,
"text": "You are given an array of 0s and 1s in random order. Segregate 0s on the left side and 1s on the right side of the array. The basic goal is to traverse array elements and sort in segregating 0s and 1s. "
},
{
"code": null,
"e": 25454,
"s": 25440,
"text": "Illustration:"
},
{
"code": null,
"e": 25505,
"s": 25454,
"text": "Input array = [0, 1, 0, 1, 0, 0, 1, 1, 1, 0] "
},
{
"code": null,
"e": 25553,
"s": 25505,
"text": "Output array = [0, 0, 0, 0, 0, 1, 1, 1, 1, 1] "
},
{
"code": null,
"e": 25565,
"s": 25553,
"text": "Approaches:"
},
{
"code": null,
"e": 25635,
"s": 25565,
"text": "Using segregation by counting Using sorting of an arrayUsing pointers"
},
{
"code": null,
"e": 25666,
"s": 25635,
"text": "Using segregation by counting "
},
{
"code": null,
"e": 25692,
"s": 25666,
"text": "Using sorting of an array"
},
{
"code": null,
"e": 25707,
"s": 25692,
"text": "Using pointers"
},
{
"code": null,
"e": 25759,
"s": 25707,
"text": "Below all three approaches all discussed in detail:"
},
{
"code": null,
"e": 25772,
"s": 25759,
"text": "Approach 1: "
},
{
"code": null,
"e": 25796,
"s": 25772,
"text": "Count the number of 0s."
},
{
"code": null,
"e": 25876,
"s": 25796,
"text": "Traversing over the whole array for looking out indices where zeros are present"
},
{
"code": null,
"e": 25926,
"s": 25876,
"text": "Maintaining a count and incrementing as 0 appears"
},
{
"code": null,
"e": 25955,
"s": 25926,
"text": "Print all zeros to the front"
},
{
"code": null,
"e": 26014,
"s": 25955,
"text": "The remaining number of 1s will be 1- (total number of 0s)"
},
{
"code": null,
"e": 26043,
"s": 26014,
"text": "Print the remaining elements"
},
{
"code": null,
"e": 26121,
"s": 26043,
"text": "Below is the implementation to segregate 0s and 1s using the above algorithm:"
},
{
"code": null,
"e": 26126,
"s": 26121,
"text": "Java"
},
{
"code": "// Java code to Segregate 0s and 1s in an array // Importing generic librariesimport java.util.*;// Importing Array librariesimport java.util.Arrays; public class GFG { // Function to segregate 0s and 1s static void segregate0and1(int arr[], int n) { // Counts the no of zeros in array int count = 0; // Iteration over array for (int i = 0; i < n; i++) { if (arr[i] == 0) // Incrementing the count count++; } // Loop fills the arr with 0 until count for (int i = 0; i < count; i++) arr[i] = 0; // Loop fills remaining arr space with 1 for (int i = count; i < n; i++) arr[i] = 1; } // Function to print segregated array static void print(int arr[], int n) { System.out.print(\"Array after segregation is \"); // Iteration over array for (int i = 0; i < n; i++) System.out.print(arr[i] + \" \"); } // Main driver function public static void main(String[] args) { // Array taken for consideration int arr[] = new int[] { 0, 1, 0, 1, 1, 1 }; // Using inbuilt function to store array size int n = arr.length; // Calling function that segregates array segregate0and1(arr, n); // Printing the above segregated array print(arr, n); }}",
"e": 27510,
"s": 26126,
"text": null
},
{
"code": null,
"e": 27518,
"s": 27510,
"text": "Output:"
},
{
"code": null,
"e": 27558,
"s": 27518,
"text": "Array after segregation is 0 0 1 1 1 1 "
},
{
"code": null,
"e": 27580,
"s": 27558,
"text": "Time Complexity: O(n)"
},
{
"code": null,
"e": 27602,
"s": 27580,
"text": "Auxiliary Space: O(1)"
},
{
"code": null,
"e": 27636,
"s": 27602,
"text": "Approach 2: Using sort() function"
},
{
"code": null,
"e": 27691,
"s": 27636,
"text": "sort() Is a method is a java.util.Arrays class method."
},
{
"code": null,
"e": 27699,
"s": 27691,
"text": "Syntax:"
},
{
"code": null,
"e": 27764,
"s": 27699,
"text": "public static void sort(int[] arr, int from_Index, int to_Index)"
},
{
"code": null,
"e": 27776,
"s": 27764,
"text": "Parameters:"
},
{
"code": null,
"e": 27949,
"s": 27776,
"text": "arr - the array to be sorted\nfrom_Index - the index of the first element, inclusive, to be sorted\nto_Index - the index of the last element, exclusive, to be sorted"
},
{
"code": null,
"e": 27962,
"s": 27949,
"text": "Return Type:"
},
{
"code": null,
"e": 27999,
"s": 27962,
"text": "This method doesn't return any value"
},
{
"code": null,
"e": 28004,
"s": 27999,
"text": "Java"
},
{
"code": "// Java code to Segregate 0s and 1s in an array // Importing generic librariesimport java.util.*; public class GFG { // Function to print segregated array // Taking arguments- array and array size static void print(int arr[], int n) { System.out.print(\"Array after segregation is \"); // Iteration over array for (int i = 0; i < n; ++i) // Printing array elements System.out.print(arr[i] + \" \"); } // Main driver function public static void main(String[] args) { // Array taken for consideration int arr[] = new int[] { 0, 1, 0, 1, 1, 1 }; // Using length inbuilt function to int n = arr.length; // Using sort inbuilt function Arrays.sort(arr); // Printing elements after executing sorting print(arr, n); }}",
"e": 28844,
"s": 28004,
"text": null
},
{
"code": null,
"e": 28852,
"s": 28844,
"text": "Output:"
},
{
"code": null,
"e": 28892,
"s": 28852,
"text": "Array after segregation is 0 0 1 1 1 1 "
},
{
"code": null,
"e": 28919,
"s": 28892,
"text": "Time Complexity: O(n*logn)"
},
{
"code": null,
"e": 28941,
"s": 28919,
"text": "Auxiliary Space: O(1)"
},
{
"code": null,
"e": 29079,
"s": 28941,
"text": "Approach 3: Maintain the left pointer and swap with the position of the left when zero found in the array and increment the left pointer."
},
{
"code": null,
"e": 29084,
"s": 29079,
"text": "Java"
},
{
"code": "// Java code to Segregate 0s and 1s in an array // Importing generic librariesimport java.util.*;import java.io.*; class GFG { // Print function outside main to print elements static void print(int a[]) { System.out.print(\"Array after segregation is: \"); // Iteration over array using array // class inbuilt function .length() for (int i = 0; i < a.length; ++i) { // Printing elements in array System.out.print(a[i] + \" \"); } } // Main driver method public static void main(String[] args) { // Random array taken for consideration int a[] = { 1, 1, 0, 0, 0, 0, 1, 1 }; // Maintaining left pointer int left = 0; // Iteration over array using length function for (int i = 0; i < a.length; ++i) { // If zeros are present if (a[i] == 0) { // Swap the elements using // temporary variable int temp = a[left]; a[left] = a[i]; a[i] = temp; // Pre incrementing left pointer ++left; } } // Calling above function to // print updated array print(a); }}",
"e": 30327,
"s": 29084,
"text": null
},
{
"code": null,
"e": 30335,
"s": 30327,
"text": "Output:"
},
{
"code": null,
"e": 30380,
"s": 30335,
"text": "Array after segregation is: 0 0 0 0 1 1 1 1 "
},
{
"code": null,
"e": 30402,
"s": 30380,
"text": "Time Complexity: O(n)"
},
{
"code": null,
"e": 30424,
"s": 30402,
"text": "Auxiliary Space: O(1)"
},
{
"code": null,
"e": 30434,
"s": 30424,
"text": "kalrap615"
},
{
"code": null,
"e": 30442,
"s": 30434,
"text": "rohan07"
},
{
"code": null,
"e": 30462,
"s": 30442,
"text": "Java-Array-Programs"
},
{
"code": null,
"e": 30469,
"s": 30462,
"text": "Picked"
},
{
"code": null,
"e": 30493,
"s": 30469,
"text": "Technical Scripter 2020"
},
{
"code": null,
"e": 30498,
"s": 30493,
"text": "Java"
},
{
"code": null,
"e": 30512,
"s": 30498,
"text": "Java Programs"
},
{
"code": null,
"e": 30531,
"s": 30512,
"text": "Technical Scripter"
},
{
"code": null,
"e": 30536,
"s": 30531,
"text": "Java"
},
{
"code": null,
"e": 30634,
"s": 30536,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 30649,
"s": 30634,
"text": "Stream In Java"
},
{
"code": null,
"e": 30670,
"s": 30649,
"text": "Constructors in Java"
},
{
"code": null,
"e": 30689,
"s": 30670,
"text": "Exceptions in Java"
},
{
"code": null,
"e": 30719,
"s": 30689,
"text": "Functional Interfaces in Java"
},
{
"code": null,
"e": 30765,
"s": 30719,
"text": "Different ways of Reading a text file in Java"
},
{
"code": null,
"e": 30791,
"s": 30765,
"text": "Java Programming Examples"
},
{
"code": null,
"e": 30825,
"s": 30791,
"text": "Convert Double to Integer in Java"
},
{
"code": null,
"e": 30872,
"s": 30825,
"text": "Implementing a Linked List in Java using Class"
},
{
"code": null,
"e": 30904,
"s": 30872,
"text": "How to Iterate HashMap in Java?"
}
] |
SQL | Aliases | 09 Jan, 2019
Aliases are the temporary names given to table or column for the purpose of a particular SQL query. It is used when name of column or table is used other than their original names, but the modified name is only temporary.
Aliases are created to make table or column names more readable.
The renaming is just a temporary change and table name does not change in the original database.
Aliases are useful when table or column names are big or not very readable.
These are preferred when there are more than one table involved in a query.
Basic Syntax:
For column alias:SELECT column as alias_name FROM table_name;
column: fields in the table
alias_name: temporary alias name to be used in replacement of original column name
table_name: name of table
SELECT column as alias_name FROM table_name;
column: fields in the table
alias_name: temporary alias name to be used in replacement of original column name
table_name: name of table
For table alias:SELECT column FROM table_name as alias_name;
column: fields in the table
table_name: name of table
alias_name: temporary alias name to be used in replacement of original table name
SELECT column FROM table_name as alias_name;
column: fields in the table
table_name: name of table
alias_name: temporary alias name to be used in replacement of original table name
Queries for illustrating column alias
To fetch ROLL_NO from Student table using CODE as alias name.SELECT ROLL_NO AS CODE FROM Student;
Output:CODE1234
To fetch ROLL_NO from Student table using CODE as alias name.SELECT ROLL_NO AS CODE FROM Student;
Output:CODE1234
To fetch ROLL_NO from Student table using CODE as alias name.SELECT ROLL_NO AS CODE FROM Student;
Output:CODE1234
To fetch ROLL_NO from Student table using CODE as alias name.SELECT ROLL_NO AS CODE FROM Student;
Output:CODE1234
SELECT ROLL_NO AS CODE FROM Student;
Output:
To fetch Branch using Stream as alias name and Grade as CGPA from table Student_Details.SELECT Branch AS Stream,Grade as CGPA FROM Student_Details;
Output:StreamCGPAInformation TechnologyOComputer ScienceEComputer ScienceOMechanical EngineeringA
To fetch Branch using Stream as alias name and Grade as CGPA from table Student_Details.SELECT Branch AS Stream,Grade as CGPA FROM Student_Details;
Output:StreamCGPAInformation TechnologyOComputer ScienceEComputer ScienceOMechanical EngineeringA
To fetch Branch using Stream as alias name and Grade as CGPA from table Student_Details.SELECT Branch AS Stream,Grade as CGPA FROM Student_Details;
Output:StreamCGPAInformation TechnologyOComputer ScienceEComputer ScienceOMechanical EngineeringA
SELECT Branch AS Stream,Grade as CGPA FROM Student_Details;
Output:
Queries for illustrating table alias
Generally table aliases are used to fetch the data from more than just single table and connect them through the field relations.
To fetch Grade and NAME of Student with Age = 20.SELECT s.NAME, d.Grade FROM Student AS s, Student_Details
AS d WHERE s.Age=20 AND s.ROLL_NO=d.ROLL_NO;
Output:NAMEGradeSUJITO
To fetch Grade and NAME of Student with Age = 20.SELECT s.NAME, d.Grade FROM Student AS s, Student_Details
AS d WHERE s.Age=20 AND s.ROLL_NO=d.ROLL_NO;
Output:NAMEGradeSUJITO
To fetch Grade and NAME of Student with Age = 20.SELECT s.NAME, d.Grade FROM Student AS s, Student_Details
AS d WHERE s.Age=20 AND s.ROLL_NO=d.ROLL_NO;
Output:NAMEGradeSUJITO
To fetch Grade and NAME of Student with Age = 20.SELECT s.NAME, d.Grade FROM Student AS s, Student_Details
AS d WHERE s.Age=20 AND s.ROLL_NO=d.ROLL_NO;
Output:NAMEGradeSUJITO
SELECT s.NAME, d.Grade FROM Student AS s, Student_Details
AS d WHERE s.Age=20 AND s.ROLL_NO=d.ROLL_NO;
Output:
This article is contributed by Pratik Agarwal. 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.
SQL-Clauses-Operators
Articles
DBMS
SQL
DBMS
SQL
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Time Complexity and Space Complexity
SQL Interview Questions
SQL | Views
Java Tutorial
Recursive Practice Problems with Solutions
ACID Properties in DBMS
SQL query to find second highest salary?
Normal Forms in DBMS
CTE in SQL
Introduction of DBMS (Database Management System) | Set 1 | [
{
"code": null,
"e": 54,
"s": 26,
"text": "\n09 Jan, 2019"
},
{
"code": null,
"e": 276,
"s": 54,
"text": "Aliases are the temporary names given to table or column for the purpose of a particular SQL query. It is used when name of column or table is used other than their original names, but the modified name is only temporary."
},
{
"code": null,
"e": 341,
"s": 276,
"text": "Aliases are created to make table or column names more readable."
},
{
"code": null,
"e": 438,
"s": 341,
"text": "The renaming is just a temporary change and table name does not change in the original database."
},
{
"code": null,
"e": 514,
"s": 438,
"text": "Aliases are useful when table or column names are big or not very readable."
},
{
"code": null,
"e": 590,
"s": 514,
"text": "These are preferred when there are more than one table involved in a query."
},
{
"code": null,
"e": 604,
"s": 590,
"text": "Basic Syntax:"
},
{
"code": null,
"e": 805,
"s": 604,
"text": "For column alias:SELECT column as alias_name FROM table_name;\ncolumn: fields in the table\nalias_name: temporary alias name to be used in replacement of original column name \ntable_name: name of table\n"
},
{
"code": null,
"e": 989,
"s": 805,
"text": "SELECT column as alias_name FROM table_name;\ncolumn: fields in the table\nalias_name: temporary alias name to be used in replacement of original column name \ntable_name: name of table\n"
},
{
"code": null,
"e": 1188,
"s": 989,
"text": "For table alias:SELECT column FROM table_name as alias_name;\ncolumn: fields in the table \ntable_name: name of table\nalias_name: temporary alias name to be used in replacement of original table name\n"
},
{
"code": null,
"e": 1371,
"s": 1188,
"text": "SELECT column FROM table_name as alias_name;\ncolumn: fields in the table \ntable_name: name of table\nalias_name: temporary alias name to be used in replacement of original table name\n"
},
{
"code": null,
"e": 1409,
"s": 1371,
"text": "Queries for illustrating column alias"
},
{
"code": null,
"e": 1524,
"s": 1409,
"text": "To fetch ROLL_NO from Student table using CODE as alias name.SELECT ROLL_NO AS CODE FROM Student; \nOutput:CODE1234"
},
{
"code": null,
"e": 1639,
"s": 1524,
"text": "To fetch ROLL_NO from Student table using CODE as alias name.SELECT ROLL_NO AS CODE FROM Student; \nOutput:CODE1234"
},
{
"code": null,
"e": 1754,
"s": 1639,
"text": "To fetch ROLL_NO from Student table using CODE as alias name.SELECT ROLL_NO AS CODE FROM Student; \nOutput:CODE1234"
},
{
"code": null,
"e": 1869,
"s": 1754,
"text": "To fetch ROLL_NO from Student table using CODE as alias name.SELECT ROLL_NO AS CODE FROM Student; \nOutput:CODE1234"
},
{
"code": null,
"e": 1908,
"s": 1869,
"text": "SELECT ROLL_NO AS CODE FROM Student; \n"
},
{
"code": null,
"e": 1916,
"s": 1908,
"text": "Output:"
},
{
"code": null,
"e": 2165,
"s": 1918,
"text": "To fetch Branch using Stream as alias name and Grade as CGPA from table Student_Details.SELECT Branch AS Stream,Grade as CGPA FROM Student_Details; \nOutput:StreamCGPAInformation TechnologyOComputer ScienceEComputer ScienceOMechanical EngineeringA"
},
{
"code": null,
"e": 2412,
"s": 2165,
"text": "To fetch Branch using Stream as alias name and Grade as CGPA from table Student_Details.SELECT Branch AS Stream,Grade as CGPA FROM Student_Details; \nOutput:StreamCGPAInformation TechnologyOComputer ScienceEComputer ScienceOMechanical EngineeringA"
},
{
"code": null,
"e": 2659,
"s": 2412,
"text": "To fetch Branch using Stream as alias name and Grade as CGPA from table Student_Details.SELECT Branch AS Stream,Grade as CGPA FROM Student_Details; \nOutput:StreamCGPAInformation TechnologyOComputer ScienceEComputer ScienceOMechanical EngineeringA"
},
{
"code": null,
"e": 2721,
"s": 2659,
"text": "SELECT Branch AS Stream,Grade as CGPA FROM Student_Details; \n"
},
{
"code": null,
"e": 2729,
"s": 2721,
"text": "Output:"
},
{
"code": null,
"e": 2766,
"s": 2729,
"text": "Queries for illustrating table alias"
},
{
"code": null,
"e": 2896,
"s": 2766,
"text": "Generally table aliases are used to fetch the data from more than just single table and connect them through the field relations."
},
{
"code": null,
"e": 3072,
"s": 2896,
"text": "To fetch Grade and NAME of Student with Age = 20.SELECT s.NAME, d.Grade FROM Student AS s, Student_Details\nAS d WHERE s.Age=20 AND s.ROLL_NO=d.ROLL_NO; \nOutput:NAMEGradeSUJITO"
},
{
"code": null,
"e": 3248,
"s": 3072,
"text": "To fetch Grade and NAME of Student with Age = 20.SELECT s.NAME, d.Grade FROM Student AS s, Student_Details\nAS d WHERE s.Age=20 AND s.ROLL_NO=d.ROLL_NO; \nOutput:NAMEGradeSUJITO"
},
{
"code": null,
"e": 3424,
"s": 3248,
"text": "To fetch Grade and NAME of Student with Age = 20.SELECT s.NAME, d.Grade FROM Student AS s, Student_Details\nAS d WHERE s.Age=20 AND s.ROLL_NO=d.ROLL_NO; \nOutput:NAMEGradeSUJITO"
},
{
"code": null,
"e": 3600,
"s": 3424,
"text": "To fetch Grade and NAME of Student with Age = 20.SELECT s.NAME, d.Grade FROM Student AS s, Student_Details\nAS d WHERE s.Age=20 AND s.ROLL_NO=d.ROLL_NO; \nOutput:NAMEGradeSUJITO"
},
{
"code": null,
"e": 3705,
"s": 3600,
"text": "SELECT s.NAME, d.Grade FROM Student AS s, Student_Details\nAS d WHERE s.Age=20 AND s.ROLL_NO=d.ROLL_NO; \n"
},
{
"code": null,
"e": 3713,
"s": 3705,
"text": "Output:"
},
{
"code": null,
"e": 4017,
"s": 3715,
"text": "This article is contributed by Pratik Agarwal. 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": 4142,
"s": 4017,
"text": "Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above."
},
{
"code": null,
"e": 4164,
"s": 4142,
"text": "SQL-Clauses-Operators"
},
{
"code": null,
"e": 4173,
"s": 4164,
"text": "Articles"
},
{
"code": null,
"e": 4178,
"s": 4173,
"text": "DBMS"
},
{
"code": null,
"e": 4182,
"s": 4178,
"text": "SQL"
},
{
"code": null,
"e": 4187,
"s": 4182,
"text": "DBMS"
},
{
"code": null,
"e": 4191,
"s": 4187,
"text": "SQL"
},
{
"code": null,
"e": 4289,
"s": 4191,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 4326,
"s": 4289,
"text": "Time Complexity and Space Complexity"
},
{
"code": null,
"e": 4350,
"s": 4326,
"text": "SQL Interview Questions"
},
{
"code": null,
"e": 4362,
"s": 4350,
"text": "SQL | Views"
},
{
"code": null,
"e": 4376,
"s": 4362,
"text": "Java Tutorial"
},
{
"code": null,
"e": 4419,
"s": 4376,
"text": "Recursive Practice Problems with Solutions"
},
{
"code": null,
"e": 4443,
"s": 4419,
"text": "ACID Properties in DBMS"
},
{
"code": null,
"e": 4484,
"s": 4443,
"text": "SQL query to find second highest salary?"
},
{
"code": null,
"e": 4505,
"s": 4484,
"text": "Normal Forms in DBMS"
},
{
"code": null,
"e": 4516,
"s": 4505,
"text": "CTE in SQL"
}
] |
Python – Case insensitive string replacement | 23 Jun, 2022
Given a string of words. The task is to write a Python program to replace the given word irrespective of the case with the given string.
Examples:
Input : test_str = “gfg is BeSt”, repl = “good”, subs = “best”
Output : gfg is good
Explanation : BeSt is replaced by “good” ignoring cases.
Input : test_str = “gfg is BeSt”, repl = “better”, subs = “best”
Output : gfg is better
Explanation : BeSt is replaced by “better” ignoring cases.
Method #1 : Using re.IGNORECASE + re.escape() + re.sub()
In this, sub() of regex is used to perform task of replacement and IGNORECASE, ignores the cases and performs case-insensitive replace.
Python3
# Python3 code to demonstrate working of# Case insensitive Replace# Using re.IGNORECASE + re.escape() + re.sub()import re # initializing stringtest_str = "gfg is BeSt" # printing original stringprint("The original string is : " + str(test_str)) # initializing replace stringrepl = "good" # initializing substring to be replacedsubs = "best" # re.IGNORECASE ignoring cases# compilation step to escape the word for all casescompiled = re.compile(re.escape(subs), re.IGNORECASE)res = compiled.sub(repl, test_str) # printing resultprint("Replaced String : " + str(res))
The original string is : gfg is BeSt
Replaced String : gfg is good
Method #2 : Using sub() + lambda + escape()
Using particular ignore case regex also this problem can be solved. Rest, a lambda function is used to handle escape characters if present in the string.
Python3
# Python3 code to demonstrate working of# Case insensitive Replace# Using sub() + lambda + escape()import re # initializing stringtest_str = "gfg is BeSt" # printing original stringprint("The original string is : " + str(test_str)) # initializing replace stringrepl = "good" # initializing substring to be replacedsubs = "best" # regex used for ignoring casesres = re.sub('(?i)'+re.escape(subs), lambda m: repl, test_str) # printing resultprint("Replaced String : " + str(res))
The original string is : gfg is BeSt
Replaced String : gfg is good
Method #3: Using split(),lower() and replace().You can also use upper() in place of lower().
Python3
# Python3 code to demonstrate working of# Case insensitive Replace # initializing stringtest_str = "gfg is BeSt" # printing original stringprint("The original string is : " + str(test_str)) # initializing replace stringrepl = "good" # initializing substring to be replacedsubs = "best" x = test_str.split()for i in x: if(i.lower()==subs.lower()): test_str=test_str.replace(i,repl)# printing resultprint("Replaced String : " + test_str) #contributed by Bhavya Koganti
The original string is : gfg is BeSt
Replaced String : gfg is good
kogantibhavya
Python string-programs
Python
Python Programs
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to Install PIP on Windows ?
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": "\n23 Jun, 2022"
},
{
"code": null,
"e": 165,
"s": 28,
"text": "Given a string of words. The task is to write a Python program to replace the given word irrespective of the case with the given string."
},
{
"code": null,
"e": 175,
"s": 165,
"text": "Examples:"
},
{
"code": null,
"e": 238,
"s": 175,
"text": "Input : test_str = “gfg is BeSt”, repl = “good”, subs = “best”"
},
{
"code": null,
"e": 259,
"s": 238,
"text": "Output : gfg is good"
},
{
"code": null,
"e": 316,
"s": 259,
"text": "Explanation : BeSt is replaced by “good” ignoring cases."
},
{
"code": null,
"e": 381,
"s": 316,
"text": "Input : test_str = “gfg is BeSt”, repl = “better”, subs = “best”"
},
{
"code": null,
"e": 404,
"s": 381,
"text": "Output : gfg is better"
},
{
"code": null,
"e": 463,
"s": 404,
"text": "Explanation : BeSt is replaced by “better” ignoring cases."
},
{
"code": null,
"e": 520,
"s": 463,
"text": "Method #1 : Using re.IGNORECASE + re.escape() + re.sub()"
},
{
"code": null,
"e": 656,
"s": 520,
"text": "In this, sub() of regex is used to perform task of replacement and IGNORECASE, ignores the cases and performs case-insensitive replace."
},
{
"code": null,
"e": 664,
"s": 656,
"text": "Python3"
},
{
"code": "# Python3 code to demonstrate working of# Case insensitive Replace# Using re.IGNORECASE + re.escape() + re.sub()import re # initializing stringtest_str = \"gfg is BeSt\" # printing original stringprint(\"The original string is : \" + str(test_str)) # initializing replace stringrepl = \"good\" # initializing substring to be replacedsubs = \"best\" # re.IGNORECASE ignoring cases# compilation step to escape the word for all casescompiled = re.compile(re.escape(subs), re.IGNORECASE)res = compiled.sub(repl, test_str) # printing resultprint(\"Replaced String : \" + str(res))",
"e": 1238,
"s": 664,
"text": null
},
{
"code": null,
"e": 1305,
"s": 1238,
"text": "The original string is : gfg is BeSt\nReplaced String : gfg is good"
},
{
"code": null,
"e": 1350,
"s": 1305,
"text": "Method #2 : Using sub() + lambda + escape() "
},
{
"code": null,
"e": 1505,
"s": 1350,
"text": "Using particular ignore case regex also this problem can be solved. Rest, a lambda function is used to handle escape characters if present in the string. "
},
{
"code": null,
"e": 1513,
"s": 1505,
"text": "Python3"
},
{
"code": "# Python3 code to demonstrate working of# Case insensitive Replace# Using sub() + lambda + escape()import re # initializing stringtest_str = \"gfg is BeSt\" # printing original stringprint(\"The original string is : \" + str(test_str)) # initializing replace stringrepl = \"good\" # initializing substring to be replacedsubs = \"best\" # regex used for ignoring casesres = re.sub('(?i)'+re.escape(subs), lambda m: repl, test_str) # printing resultprint(\"Replaced String : \" + str(res))",
"e": 1999,
"s": 1513,
"text": null
},
{
"code": null,
"e": 2066,
"s": 1999,
"text": "The original string is : gfg is BeSt\nReplaced String : gfg is good"
},
{
"code": null,
"e": 2159,
"s": 2066,
"text": "Method #3: Using split(),lower() and replace().You can also use upper() in place of lower()."
},
{
"code": null,
"e": 2167,
"s": 2159,
"text": "Python3"
},
{
"code": "# Python3 code to demonstrate working of# Case insensitive Replace # initializing stringtest_str = \"gfg is BeSt\" # printing original stringprint(\"The original string is : \" + str(test_str)) # initializing replace stringrepl = \"good\" # initializing substring to be replacedsubs = \"best\" x = test_str.split()for i in x: if(i.lower()==subs.lower()): test_str=test_str.replace(i,repl)# printing resultprint(\"Replaced String : \" + test_str) #contributed by Bhavya Koganti",
"e": 2644,
"s": 2167,
"text": null
},
{
"code": null,
"e": 2711,
"s": 2644,
"text": "The original string is : gfg is BeSt\nReplaced String : gfg is good"
},
{
"code": null,
"e": 2725,
"s": 2711,
"text": "kogantibhavya"
},
{
"code": null,
"e": 2748,
"s": 2725,
"text": "Python string-programs"
},
{
"code": null,
"e": 2755,
"s": 2748,
"text": "Python"
},
{
"code": null,
"e": 2771,
"s": 2755,
"text": "Python Programs"
},
{
"code": null,
"e": 2869,
"s": 2771,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 2901,
"s": 2869,
"text": "How to Install PIP on Windows ?"
},
{
"code": null,
"e": 2928,
"s": 2901,
"text": "Python Classes and Objects"
},
{
"code": null,
"e": 2949,
"s": 2928,
"text": "Python OOPs Concepts"
},
{
"code": null,
"e": 2972,
"s": 2949,
"text": "Introduction To PYTHON"
},
{
"code": null,
"e": 3003,
"s": 2972,
"text": "Python | os.path.join() method"
},
{
"code": null,
"e": 3025,
"s": 3003,
"text": "Defaultdict in Python"
},
{
"code": null,
"e": 3064,
"s": 3025,
"text": "Python | Get dictionary keys as a list"
},
{
"code": null,
"e": 3102,
"s": 3064,
"text": "Python | Convert a list to dictionary"
},
{
"code": null,
"e": 3151,
"s": 3102,
"text": "Python | Convert string dictionary to dictionary"
}
] |
Python | ARIMA Model for Time Series Forecasting | 19 Feb, 2020
A Time Series is defined as a series of data points indexed in time order. The time order can be daily, monthly, or even yearly. Given below is an example of a Time Series that illustrates the number of passengers of an airline per month from the year 1949 to 1960.
Time Series ForecastingTime Series forecasting is the process of using a statistical model to predict future values of a time series based on past results.
Some Use Cases
To predict the number of incoming or churning customers.
To explaining seasonal patterns in sales.
To detect unusual events and estimate the magnitude of their effect.
To Estimate the effect of a newly launched product on number of sold units.
Components of a Time Series:
Trend:The trend shows a general direction of the time series data over a long period of time. A trend can be increasing(upward), decreasing(downward), or horizontal(stationary).
Seasonality:The seasonality component exhibits a trend that repeats with respect to timing, direction, and magnitude. Some examples include an increase in water consumption in summer due to hot weather conditions, or an increase in the number of airline passengers during holidays each year.
Cyclical Component: These are the trends with no set repetition over a particular period of time. A cycle refers to the period of ups and downs, booms and slums of a time series, mostly observed in business cycles. These cycles do not exhibit a seasonal variation but generally occur over a time period of 3 to 12 years depending on the nature of the time series.
Irregular Variation: These are the fluctuations in the time series data which become evident when trend and cyclical variations are removed. These variations are unpredictable, erratic, and may or may not be random.
ETS DecompositionETS Decomposition is used to separate different components of a time series. The term ETS stands for Error, Trend, and Seasonality.
Code: ETS Decomposition of Airline Passengers Dataset:
# Importing required librariesimport numpy as npimport pandas as pdimport matplotlib.pylot as pltfrom statsmodels.tsa.seasonal import seasonal_decompose # Read the AirPassengers datasetairline = pd.read_csv('AirPassengers.csv', index_col ='Month', parse_dates = True) # Print the first five rows of the datasetairline.head() # ETS Decompositionresult = seasonal_decompose(airline['# Passengers'], model ='multiplicative') # ETS plot result.plot()
Output:
ARIMA Model for Time Series ForecastingARIMA stands for autoregressive integrated moving average model and is specified by three order parameters: (p, d, q).
AR(p) Autoregression – a regression model that utilizes the dependent relationship between a current observation and observations over a previous period.An auto regressive (AR(p)) component refers to the use of past values in the regression equation for the time series.
I(d) Integration – uses differencing of observations (subtracting an observation from observation at the previous time step) in order to make the time series stationary. Differencing involves the subtraction of the current values of a series with its previous values d number of times.
MA(q) Moving Average – a model that uses the dependency between an observation and a residual error from a moving average model applied to lagged observations. A moving average component depicts the error of the model as a combination of previous error terms. The order q represents the number of terms to be included in the model.
Types of ARIMA Model
ARIMA:Non-seasonal Autoregressive Integrated Moving Averages
SARIMA:Seasonal ARIMA
SARIMAX:Seasonal ARIMA with exogenous variables
Pyramid Auto-ARIMA
The ‘auto_arima’ function from the ‘pmdarima’ library helps us to identify the most optimal parameters for an ARIMA model and returns a fitted ARIMA model.
Code : Parameter Analysis for the ARIMA model
# To install the librarypip install pmdarima # Import the libraryfrom pmdarima import auto_arima # Ignore harmless warningsimport warningswarnings.filterwarnings("ignore") # Fit auto_arima function to AirPassengers datasetstepwise_fit = auto_arima(airline['# Passengers'], start_p = 1, start_q = 1, max_p = 3, max_q = 3, m = 12, start_P = 0, seasonal = True, d = None, D = 1, trace = True, error_action ='ignore', # we don't want to know if an order does not work suppress_warnings = True, # we don't want convergence warnings stepwise = True) # set to stepwise # To print the summarystepwise_fit.summary()
Output:
Code : Fit ARIMA Model to AirPassengers dataset
# Split data into train / test setstrain = airline.iloc[:len(airline)-12]test = airline.iloc[len(airline)-12:] # set one year(12 months) for testing # Fit a SARIMAX(0, 1, 1)x(2, 1, 1, 12) on the training setfrom statsmodels.tsa.statespace.sarimax import SARIMAX model = SARIMAX(train['# Passengers'], order = (0, 1, 1), seasonal_order =(2, 1, 1, 12)) result = model.fit()result.summary()
Output:
Code : Predictions of ARIMA Model against the test set
start = len(train)end = len(train) + len(test) - 1 # Predictions for one-year against the test setpredictions = result.predict(start, end, typ = 'levels').rename("Predictions") # plot predictions and actual valuespredictions.plot(legend = True)test['# Passengers'].plot(legend = True)
Output:
Code : Evaluate the model using MSE and RMSE
# Load specific evaluation toolsfrom sklearn.metrics import mean_squared_errorfrom statsmodels.tools.eval_measures import rmse # Calculate root mean squared errorrmse(test["# Passengers"], predictions) # Calculate mean squared errormean_squared_error(test["# Passengers"], predictions)
Output:
Code : Forecast using ARIMA Model
# Train the model on the full datasetmodel = model = SARIMAX(airline['# Passengers'], order = (0, 1, 1), seasonal_order =(2, 1, 1, 12))result = model.fit() # Forecast for the next 3 yearsforecast = result.predict(start = len(airline), end = (len(airline)-1) + 3 * 12, typ = 'levels').rename('Forecast') # Plot the forecast valuesairline['# Passengers'].plot(figsize = (12, 5), legend = True)forecast.plot(legend = True)
Output:
Machine Learning
Python
Machine Learning
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
ML | Linear Regression
Search Algorithms in AI
Getting started with Machine Learning
Introduction to Recurrent Neural Network
ML | Monte Carlo Tree Search (MCTS)
Read JSON file using Python
Python map() function
How to get column names in Pandas dataframe
Python Dictionary
Different ways to create Pandas Dataframe | [
{
"code": null,
"e": 54,
"s": 26,
"text": "\n19 Feb, 2020"
},
{
"code": null,
"e": 320,
"s": 54,
"text": "A Time Series is defined as a series of data points indexed in time order. The time order can be daily, monthly, or even yearly. Given below is an example of a Time Series that illustrates the number of passengers of an airline per month from the year 1949 to 1960."
},
{
"code": null,
"e": 476,
"s": 320,
"text": "Time Series ForecastingTime Series forecasting is the process of using a statistical model to predict future values of a time series based on past results."
},
{
"code": null,
"e": 491,
"s": 476,
"text": "Some Use Cases"
},
{
"code": null,
"e": 548,
"s": 491,
"text": "To predict the number of incoming or churning customers."
},
{
"code": null,
"e": 590,
"s": 548,
"text": "To explaining seasonal patterns in sales."
},
{
"code": null,
"e": 659,
"s": 590,
"text": "To detect unusual events and estimate the magnitude of their effect."
},
{
"code": null,
"e": 735,
"s": 659,
"text": "To Estimate the effect of a newly launched product on number of sold units."
},
{
"code": null,
"e": 764,
"s": 735,
"text": "Components of a Time Series:"
},
{
"code": null,
"e": 942,
"s": 764,
"text": "Trend:The trend shows a general direction of the time series data over a long period of time. A trend can be increasing(upward), decreasing(downward), or horizontal(stationary)."
},
{
"code": null,
"e": 1234,
"s": 942,
"text": "Seasonality:The seasonality component exhibits a trend that repeats with respect to timing, direction, and magnitude. Some examples include an increase in water consumption in summer due to hot weather conditions, or an increase in the number of airline passengers during holidays each year."
},
{
"code": null,
"e": 1598,
"s": 1234,
"text": "Cyclical Component: These are the trends with no set repetition over a particular period of time. A cycle refers to the period of ups and downs, booms and slums of a time series, mostly observed in business cycles. These cycles do not exhibit a seasonal variation but generally occur over a time period of 3 to 12 years depending on the nature of the time series."
},
{
"code": null,
"e": 1814,
"s": 1598,
"text": "Irregular Variation: These are the fluctuations in the time series data which become evident when trend and cyclical variations are removed. These variations are unpredictable, erratic, and may or may not be random."
},
{
"code": null,
"e": 1963,
"s": 1814,
"text": "ETS DecompositionETS Decomposition is used to separate different components of a time series. The term ETS stands for Error, Trend, and Seasonality."
},
{
"code": null,
"e": 2018,
"s": 1963,
"text": "Code: ETS Decomposition of Airline Passengers Dataset:"
},
{
"code": "# Importing required librariesimport numpy as npimport pandas as pdimport matplotlib.pylot as pltfrom statsmodels.tsa.seasonal import seasonal_decompose # Read the AirPassengers datasetairline = pd.read_csv('AirPassengers.csv', index_col ='Month', parse_dates = True) # Print the first five rows of the datasetairline.head() # ETS Decompositionresult = seasonal_decompose(airline['# Passengers'], model ='multiplicative') # ETS plot result.plot()",
"e": 2541,
"s": 2018,
"text": null
},
{
"code": null,
"e": 2549,
"s": 2541,
"text": "Output:"
},
{
"code": null,
"e": 2707,
"s": 2549,
"text": "ARIMA Model for Time Series ForecastingARIMA stands for autoregressive integrated moving average model and is specified by three order parameters: (p, d, q)."
},
{
"code": null,
"e": 2978,
"s": 2707,
"text": "AR(p) Autoregression – a regression model that utilizes the dependent relationship between a current observation and observations over a previous period.An auto regressive (AR(p)) component refers to the use of past values in the regression equation for the time series."
},
{
"code": null,
"e": 3264,
"s": 2978,
"text": "I(d) Integration – uses differencing of observations (subtracting an observation from observation at the previous time step) in order to make the time series stationary. Differencing involves the subtraction of the current values of a series with its previous values d number of times."
},
{
"code": null,
"e": 3596,
"s": 3264,
"text": "MA(q) Moving Average – a model that uses the dependency between an observation and a residual error from a moving average model applied to lagged observations. A moving average component depicts the error of the model as a combination of previous error terms. The order q represents the number of terms to be included in the model."
},
{
"code": null,
"e": 3617,
"s": 3596,
"text": "Types of ARIMA Model"
},
{
"code": null,
"e": 3678,
"s": 3617,
"text": "ARIMA:Non-seasonal Autoregressive Integrated Moving Averages"
},
{
"code": null,
"e": 3700,
"s": 3678,
"text": "SARIMA:Seasonal ARIMA"
},
{
"code": null,
"e": 3748,
"s": 3700,
"text": "SARIMAX:Seasonal ARIMA with exogenous variables"
},
{
"code": null,
"e": 3767,
"s": 3748,
"text": "Pyramid Auto-ARIMA"
},
{
"code": null,
"e": 3923,
"s": 3767,
"text": "The ‘auto_arima’ function from the ‘pmdarima’ library helps us to identify the most optimal parameters for an ARIMA model and returns a fitted ARIMA model."
},
{
"code": null,
"e": 3969,
"s": 3923,
"text": "Code : Parameter Analysis for the ARIMA model"
},
{
"code": "# To install the librarypip install pmdarima # Import the libraryfrom pmdarima import auto_arima # Ignore harmless warningsimport warningswarnings.filterwarnings(\"ignore\") # Fit auto_arima function to AirPassengers datasetstepwise_fit = auto_arima(airline['# Passengers'], start_p = 1, start_q = 1, max_p = 3, max_q = 3, m = 12, start_P = 0, seasonal = True, d = None, D = 1, trace = True, error_action ='ignore', # we don't want to know if an order does not work suppress_warnings = True, # we don't want convergence warnings stepwise = True) # set to stepwise # To print the summarystepwise_fit.summary()",
"e": 4743,
"s": 3969,
"text": null
},
{
"code": null,
"e": 4751,
"s": 4743,
"text": "Output:"
},
{
"code": null,
"e": 4799,
"s": 4751,
"text": "Code : Fit ARIMA Model to AirPassengers dataset"
},
{
"code": "# Split data into train / test setstrain = airline.iloc[:len(airline)-12]test = airline.iloc[len(airline)-12:] # set one year(12 months) for testing # Fit a SARIMAX(0, 1, 1)x(2, 1, 1, 12) on the training setfrom statsmodels.tsa.statespace.sarimax import SARIMAX model = SARIMAX(train['# Passengers'], order = (0, 1, 1), seasonal_order =(2, 1, 1, 12)) result = model.fit()result.summary()",
"e": 5222,
"s": 4799,
"text": null
},
{
"code": null,
"e": 5230,
"s": 5222,
"text": "Output:"
},
{
"code": null,
"e": 5285,
"s": 5230,
"text": "Code : Predictions of ARIMA Model against the test set"
},
{
"code": "start = len(train)end = len(train) + len(test) - 1 # Predictions for one-year against the test setpredictions = result.predict(start, end, typ = 'levels').rename(\"Predictions\") # plot predictions and actual valuespredictions.plot(legend = True)test['# Passengers'].plot(legend = True)",
"e": 5600,
"s": 5285,
"text": null
},
{
"code": null,
"e": 5608,
"s": 5600,
"text": "Output:"
},
{
"code": null,
"e": 5653,
"s": 5608,
"text": "Code : Evaluate the model using MSE and RMSE"
},
{
"code": "# Load specific evaluation toolsfrom sklearn.metrics import mean_squared_errorfrom statsmodels.tools.eval_measures import rmse # Calculate root mean squared errorrmse(test[\"# Passengers\"], predictions) # Calculate mean squared errormean_squared_error(test[\"# Passengers\"], predictions)",
"e": 5941,
"s": 5653,
"text": null
},
{
"code": null,
"e": 5949,
"s": 5941,
"text": "Output:"
},
{
"code": null,
"e": 5983,
"s": 5949,
"text": "Code : Forecast using ARIMA Model"
},
{
"code": "# Train the model on the full datasetmodel = model = SARIMAX(airline['# Passengers'], order = (0, 1, 1), seasonal_order =(2, 1, 1, 12))result = model.fit() # Forecast for the next 3 yearsforecast = result.predict(start = len(airline), end = (len(airline)-1) + 3 * 12, typ = 'levels').rename('Forecast') # Plot the forecast valuesairline['# Passengers'].plot(figsize = (12, 5), legend = True)forecast.plot(legend = True)",
"e": 6505,
"s": 5983,
"text": null
},
{
"code": null,
"e": 6513,
"s": 6505,
"text": "Output:"
},
{
"code": null,
"e": 6530,
"s": 6513,
"text": "Machine Learning"
},
{
"code": null,
"e": 6537,
"s": 6530,
"text": "Python"
},
{
"code": null,
"e": 6554,
"s": 6537,
"text": "Machine Learning"
},
{
"code": null,
"e": 6652,
"s": 6554,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 6675,
"s": 6652,
"text": "ML | Linear Regression"
},
{
"code": null,
"e": 6699,
"s": 6675,
"text": "Search Algorithms in AI"
},
{
"code": null,
"e": 6737,
"s": 6699,
"text": "Getting started with Machine Learning"
},
{
"code": null,
"e": 6778,
"s": 6737,
"text": "Introduction to Recurrent Neural Network"
},
{
"code": null,
"e": 6814,
"s": 6778,
"text": "ML | Monte Carlo Tree Search (MCTS)"
},
{
"code": null,
"e": 6842,
"s": 6814,
"text": "Read JSON file using Python"
},
{
"code": null,
"e": 6864,
"s": 6842,
"text": "Python map() function"
},
{
"code": null,
"e": 6908,
"s": 6864,
"text": "How to get column names in Pandas dataframe"
},
{
"code": null,
"e": 6926,
"s": 6908,
"text": "Python Dictionary"
}
] |
How to Completely Uninstall Android Studio on Mac? | 29 Jul, 2021
Maybe you messed up with your current installation of Android Studio or maybe some nasty error came in even after restarting it several times, well, and doing all the troubleshooting steps didn’t help you either...So...? Uninstalling seems the only way out, let’s have a look at how to uninstall Android Studio Completely from your system!
Method #1: On a Mac, Open Terminal then execute these commands in order
The terminal on the Mac
# Deletes the Android Studio application
rm -Rf /Applications/Android\ Studio.app
# Delete All Android Studio related preferences
# The asterisk here should target all folders/files beginning with the string before it
rm -Rf ~/Library/Preferences/AndroidStudio*
rm -Rf ~/Library/Preferences/Google/AndroidStudio*
# Deletes Studio's plist file
rm -Rf ~/Library/Preferences/com.google.android.*
# Deletes Emulator's plist file
rm -Rf ~/Library/Preferences/com.android.*
# Deletes main plugins
rm -Rf ~/Library/Application\ Support/AndroidStudio*
rm -Rf ~/Library/Application\ Support/Google/AndroidStudio*
# Deletes all logs that Android Studio outputs
rm -Rf ~/Library/Logs/AndroidStudio*
rm -Rf ~/Library/Logs/Google/AndroidStudio*
# Deletes Android Studio's caches
rm -Rf ~/Library/Caches/AndroidStudio*
# Deletes older versions of Android Studio (if any)
rm -Rf ~/.AndroidStudio*
The GUI Output
And Voila! Just as that Android Studio Got Uninstalled Completely!
Notes: The flags for rm are case-sensitive pay close attention to them!
Method #2: In the GUI Way
If using the terminal isn’t your piece of cake, then using the GUI is also an easy way to completely eradicate the current Android Studio
Press the “Cmd(Command)+option+Space Bar” key simultaneously on your machineSearch for “Android Studio”Click the ‘+’ button just below the search box.Then select “are included” from the drop-down menuThen you get a lot of system files that need to be deleted to complete the uninstall of the appPress “Cmd+A” to select all files then delete themEmpty your trash. Done
Press the “Cmd(Command)+option+Space Bar” key simultaneously on your machine
Search for “Android Studio”
Click the ‘+’ button just below the search box.
Then select “are included” from the drop-down menu
Then you get a lot of system files that need to be deleted to complete the uninstall of the app
Press “Cmd+A” to select all files then delete them
Empty your trash. Done
Use the Image below to assess better, if you need help
Uninstalling the GUI Way!
Method #3: A pretty easy one
Assuming here that you’re using OS X here. You can simply open the applications folder and move Android Studio to the trash. The same thing goes for the SDK.
GeekTip: ~/Library/Android is where your SDK is stored by default!
Method #4: The Launchpad Way
The fourth method in this tutorial is to uninstall Android Studio from Launchpad. This application has the icon of a black rocket on a grey background.Just open the launch-pad as you usually do, then press and hold on the Android Studio icon until it starts to jiggle, then tap the cross (x) mark then tap on it!Just like that, Android Studio got uninstalled!
The fourth method in this tutorial is to uninstall Android Studio from Launchpad. This application has the icon of a black rocket on a grey background.
Just open the launch-pad as you usually do, then press and hold on the Android Studio icon until it starts to jiggle, then tap the cross (x) mark then tap on it!
Just like that, Android Studio got uninstalled!
However: If you did “You may want to add android-studio/bin/ to your PATH environmental” too you will need to undo this alteration by deleting android-studio/bin/ from the file you added this PATH too.
Method #5: I installed Android Studio by the ‘umake android’ command, what shall I do?
Well, if you took the less traveled pathway and installed it using the umake command, you should simply run these commands in your shell:
1. umake android –remove
After that just delete Android Studio’s related folders in your /home folder using:
rm -r ~/.AndroidStudio
rm -r ~/.android
Uninstalling Android Studio could be a tedious task but yes this article had pretty much everything that was needed to uninstall Android Studio Completely from your Mac. And as you can see, dragging and dropping apps to Trash might not completely uninstall them. If you need to install it back again just visit here!
abhishek0719kadiyan
Android-Studio
Picked
Android
Android
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to Add Views Dynamically and Store Data in Arraylist in Android?
Android SDK and it's Components
How to Communicate Between Fragments in Android?
Flutter - Custom Bottom Navigation Bar
Retrofit with Kotlin Coroutine in Android
How to Post Data to API using Retrofit in Android?
Flutter - Stack Widget
Activity Lifecycle in Android with Demo App
Introduction to Android Development
Fragment Lifecycle in Android | [
{
"code": null,
"e": 53,
"s": 25,
"text": "\n29 Jul, 2021"
},
{
"code": null,
"e": 394,
"s": 53,
"text": "Maybe you messed up with your current installation of Android Studio or maybe some nasty error came in even after restarting it several times, well, and doing all the troubleshooting steps didn’t help you either...So...? Uninstalling seems the only way out, let’s have a look at how to uninstall Android Studio Completely from your system! "
},
{
"code": null,
"e": 466,
"s": 394,
"text": "Method #1: On a Mac, Open Terminal then execute these commands in order"
},
{
"code": null,
"e": 490,
"s": 466,
"text": "The terminal on the Mac"
},
{
"code": null,
"e": 1372,
"s": 490,
"text": "# Deletes the Android Studio application\nrm -Rf /Applications/Android\\ Studio.app\n# Delete All Android Studio related preferences\n# The asterisk here should target all folders/files beginning with the string before it\nrm -Rf ~/Library/Preferences/AndroidStudio*\nrm -Rf ~/Library/Preferences/Google/AndroidStudio*\n# Deletes Studio's plist file\nrm -Rf ~/Library/Preferences/com.google.android.*\n# Deletes Emulator's plist file\nrm -Rf ~/Library/Preferences/com.android.*\n# Deletes main plugins\nrm -Rf ~/Library/Application\\ Support/AndroidStudio*\nrm -Rf ~/Library/Application\\ Support/Google/AndroidStudio*\n# Deletes all logs that Android Studio outputs\nrm -Rf ~/Library/Logs/AndroidStudio*\nrm -Rf ~/Library/Logs/Google/AndroidStudio*\n# Deletes Android Studio's caches\nrm -Rf ~/Library/Caches/AndroidStudio*\n# Deletes older versions of Android Studio (if any)\nrm -Rf ~/.AndroidStudio*"
},
{
"code": null,
"e": 1387,
"s": 1372,
"text": "The GUI Output"
},
{
"code": null,
"e": 1454,
"s": 1387,
"text": "And Voila! Just as that Android Studio Got Uninstalled Completely!"
},
{
"code": null,
"e": 1526,
"s": 1454,
"text": "Notes: The flags for rm are case-sensitive pay close attention to them!"
},
{
"code": null,
"e": 1552,
"s": 1526,
"text": "Method #2: In the GUI Way"
},
{
"code": null,
"e": 1690,
"s": 1552,
"text": "If using the terminal isn’t your piece of cake, then using the GUI is also an easy way to completely eradicate the current Android Studio"
},
{
"code": null,
"e": 2058,
"s": 1690,
"text": "Press the “Cmd(Command)+option+Space Bar” key simultaneously on your machineSearch for “Android Studio”Click the ‘+’ button just below the search box.Then select “are included” from the drop-down menuThen you get a lot of system files that need to be deleted to complete the uninstall of the appPress “Cmd+A” to select all files then delete themEmpty your trash. Done"
},
{
"code": null,
"e": 2135,
"s": 2058,
"text": "Press the “Cmd(Command)+option+Space Bar” key simultaneously on your machine"
},
{
"code": null,
"e": 2163,
"s": 2135,
"text": "Search for “Android Studio”"
},
{
"code": null,
"e": 2211,
"s": 2163,
"text": "Click the ‘+’ button just below the search box."
},
{
"code": null,
"e": 2262,
"s": 2211,
"text": "Then select “are included” from the drop-down menu"
},
{
"code": null,
"e": 2358,
"s": 2262,
"text": "Then you get a lot of system files that need to be deleted to complete the uninstall of the app"
},
{
"code": null,
"e": 2409,
"s": 2358,
"text": "Press “Cmd+A” to select all files then delete them"
},
{
"code": null,
"e": 2432,
"s": 2409,
"text": "Empty your trash. Done"
},
{
"code": null,
"e": 2487,
"s": 2432,
"text": "Use the Image below to assess better, if you need help"
},
{
"code": null,
"e": 2513,
"s": 2487,
"text": "Uninstalling the GUI Way!"
},
{
"code": null,
"e": 2542,
"s": 2513,
"text": "Method #3: A pretty easy one"
},
{
"code": null,
"e": 2700,
"s": 2542,
"text": "Assuming here that you’re using OS X here. You can simply open the applications folder and move Android Studio to the trash. The same thing goes for the SDK."
},
{
"code": null,
"e": 2768,
"s": 2700,
"text": "GeekTip: ~/Library/Android is where your SDK is stored by default! "
},
{
"code": null,
"e": 2797,
"s": 2768,
"text": "Method #4: The Launchpad Way"
},
{
"code": null,
"e": 3157,
"s": 2797,
"text": "The fourth method in this tutorial is to uninstall Android Studio from Launchpad. This application has the icon of a black rocket on a grey background.Just open the launch-pad as you usually do, then press and hold on the Android Studio icon until it starts to jiggle, then tap the cross (x) mark then tap on it!Just like that, Android Studio got uninstalled!"
},
{
"code": null,
"e": 3309,
"s": 3157,
"text": "The fourth method in this tutorial is to uninstall Android Studio from Launchpad. This application has the icon of a black rocket on a grey background."
},
{
"code": null,
"e": 3471,
"s": 3309,
"text": "Just open the launch-pad as you usually do, then press and hold on the Android Studio icon until it starts to jiggle, then tap the cross (x) mark then tap on it!"
},
{
"code": null,
"e": 3519,
"s": 3471,
"text": "Just like that, Android Studio got uninstalled!"
},
{
"code": null,
"e": 3721,
"s": 3519,
"text": "However: If you did “You may want to add android-studio/bin/ to your PATH environmental” too you will need to undo this alteration by deleting android-studio/bin/ from the file you added this PATH too."
},
{
"code": null,
"e": 3808,
"s": 3721,
"text": "Method #5: I installed Android Studio by the ‘umake android’ command, what shall I do?"
},
{
"code": null,
"e": 3946,
"s": 3808,
"text": "Well, if you took the less traveled pathway and installed it using the umake command, you should simply run these commands in your shell:"
},
{
"code": null,
"e": 3971,
"s": 3946,
"text": "1. umake android –remove"
},
{
"code": null,
"e": 4055,
"s": 3971,
"text": "After that just delete Android Studio’s related folders in your /home folder using:"
},
{
"code": null,
"e": 4078,
"s": 4055,
"text": "rm -r ~/.AndroidStudio"
},
{
"code": null,
"e": 4095,
"s": 4078,
"text": "rm -r ~/.android"
},
{
"code": null,
"e": 4412,
"s": 4095,
"text": "Uninstalling Android Studio could be a tedious task but yes this article had pretty much everything that was needed to uninstall Android Studio Completely from your Mac. And as you can see, dragging and dropping apps to Trash might not completely uninstall them. If you need to install it back again just visit here!"
},
{
"code": null,
"e": 4432,
"s": 4412,
"text": "abhishek0719kadiyan"
},
{
"code": null,
"e": 4447,
"s": 4432,
"text": "Android-Studio"
},
{
"code": null,
"e": 4454,
"s": 4447,
"text": "Picked"
},
{
"code": null,
"e": 4462,
"s": 4454,
"text": "Android"
},
{
"code": null,
"e": 4470,
"s": 4462,
"text": "Android"
},
{
"code": null,
"e": 4568,
"s": 4470,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 4637,
"s": 4568,
"text": "How to Add Views Dynamically and Store Data in Arraylist in Android?"
},
{
"code": null,
"e": 4669,
"s": 4637,
"text": "Android SDK and it's Components"
},
{
"code": null,
"e": 4718,
"s": 4669,
"text": "How to Communicate Between Fragments in Android?"
},
{
"code": null,
"e": 4757,
"s": 4718,
"text": "Flutter - Custom Bottom Navigation Bar"
},
{
"code": null,
"e": 4799,
"s": 4757,
"text": "Retrofit with Kotlin Coroutine in Android"
},
{
"code": null,
"e": 4850,
"s": 4799,
"text": "How to Post Data to API using Retrofit in Android?"
},
{
"code": null,
"e": 4873,
"s": 4850,
"text": "Flutter - Stack Widget"
},
{
"code": null,
"e": 4917,
"s": 4873,
"text": "Activity Lifecycle in Android with Demo App"
},
{
"code": null,
"e": 4953,
"s": 4917,
"text": "Introduction to Android Development"
}
] |
Python – Reverse Row sort in Lists of List | 16 Jun, 2022
Sometimes, while working with data, we can have a problem in which we need to perform the sorting of rows of the matrix in descending order. This kind of problem has its application in the web development and Data Science domain. Let’s discuss certain ways in which this task can be performed.
Method #1: Using loop + sort() + reverse This problem can be solved using a loop to loop over each row. The sort and reverse can be used to perform the reverse sort of rows.
Python3
# Python3 code to demonstrate# Reverse Row sort in Lists of List# using loop # initializing listtest_list = [[4, 1, 6], [7, 8], [4, 10, 8]] # printing original listprint("The original list is : " + str(test_list)) # Reverse Row sort in Lists of List# using loopfor ele in test_list: ele.sort(reverse=True) # printing resultprint("The reverse sorted Matrix is : " + str(test_list))
The original list is : [[4, 1, 6], [7, 8], [4, 10, 8]]
The reverse sorted Matrix is : [[6, 4, 1], [8, 7], [10, 8, 4]]
Method #2: Using list comprehension + sorted() This is yet another way in which this task can be performed. In this, we perform in a similar way, just pack the logic in one line using list comprehension to provide a compact alternative.
Python3
# Python3 code to demonstrate# Reverse Row sort in Lists of List# using list comprehension + sorted() # initializing listtest_list = [[4, 1, 6], [7, 8], [4, 10, 8]] # printing original listprint("The original list is : " + str(test_list)) # Reverse Row sort in Lists of List# using list comprehension + sorted()res = [sorted(sub, reverse=True) for sub in test_list] # printing resultprint("The reverse sorted Matrix is : " + str(res))
The original list is : [[4, 1, 6], [7, 8], [4, 10, 8]]
The reverse sorted Matrix is : [[6, 4, 1], [8, 7], [10, 8, 4]]
Method#3: Using map() + sorted This is one way to solve this problem. In this, we update the existing list with the help of map function which sorts the internal list in reverse order using the sorted function.
Python3
# Python3 code to demonstrate# Reverse Row sort in Lists of List# using map + sorted() # initializing listtest_list = [[4, 1, 6], [7, 8], [4, 10, 8]] # printing original listprint("The original list is : " + str(test_list)) # Reverse Row sort in Lists of List# using map + sorted()res = list(map(lambda x: sorted(x, reverse=True), test_list)) # printing resultprint("The reverse sorted Matrix is : " + str(res))
The original list is : [[4, 1, 6], [7, 8], [4, 10, 8]]
The reverse sorted Matrix is : [[6, 4, 1], [8, 7], [10, 8, 4]]
satyam00so
Python list-programs
Python-list-of-lists
Python-Matrix
Python-sort
Python
Python Programs
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here. | [
{
"code": null,
"e": 28,
"s": 0,
"text": "\n16 Jun, 2022"
},
{
"code": null,
"e": 322,
"s": 28,
"text": "Sometimes, while working with data, we can have a problem in which we need to perform the sorting of rows of the matrix in descending order. This kind of problem has its application in the web development and Data Science domain. Let’s discuss certain ways in which this task can be performed."
},
{
"code": null,
"e": 497,
"s": 322,
"text": "Method #1: Using loop + sort() + reverse This problem can be solved using a loop to loop over each row. The sort and reverse can be used to perform the reverse sort of rows. "
},
{
"code": null,
"e": 505,
"s": 497,
"text": "Python3"
},
{
"code": "# Python3 code to demonstrate# Reverse Row sort in Lists of List# using loop # initializing listtest_list = [[4, 1, 6], [7, 8], [4, 10, 8]] # printing original listprint(\"The original list is : \" + str(test_list)) # Reverse Row sort in Lists of List# using loopfor ele in test_list: ele.sort(reverse=True) # printing resultprint(\"The reverse sorted Matrix is : \" + str(test_list))",
"e": 889,
"s": 505,
"text": null
},
{
"code": null,
"e": 1008,
"s": 889,
"text": "The original list is : [[4, 1, 6], [7, 8], [4, 10, 8]]\nThe reverse sorted Matrix is : [[6, 4, 1], [8, 7], [10, 8, 4]]\n"
},
{
"code": null,
"e": 1246,
"s": 1008,
"text": "Method #2: Using list comprehension + sorted() This is yet another way in which this task can be performed. In this, we perform in a similar way, just pack the logic in one line using list comprehension to provide a compact alternative. "
},
{
"code": null,
"e": 1254,
"s": 1246,
"text": "Python3"
},
{
"code": "# Python3 code to demonstrate# Reverse Row sort in Lists of List# using list comprehension + sorted() # initializing listtest_list = [[4, 1, 6], [7, 8], [4, 10, 8]] # printing original listprint(\"The original list is : \" + str(test_list)) # Reverse Row sort in Lists of List# using list comprehension + sorted()res = [sorted(sub, reverse=True) for sub in test_list] # printing resultprint(\"The reverse sorted Matrix is : \" + str(res))",
"e": 1689,
"s": 1254,
"text": null
},
{
"code": null,
"e": 1808,
"s": 1689,
"text": "The original list is : [[4, 1, 6], [7, 8], [4, 10, 8]]\nThe reverse sorted Matrix is : [[6, 4, 1], [8, 7], [10, 8, 4]]\n"
},
{
"code": null,
"e": 2019,
"s": 1808,
"text": "Method#3: Using map() + sorted This is one way to solve this problem. In this, we update the existing list with the help of map function which sorts the internal list in reverse order using the sorted function."
},
{
"code": null,
"e": 2027,
"s": 2019,
"text": "Python3"
},
{
"code": "# Python3 code to demonstrate# Reverse Row sort in Lists of List# using map + sorted() # initializing listtest_list = [[4, 1, 6], [7, 8], [4, 10, 8]] # printing original listprint(\"The original list is : \" + str(test_list)) # Reverse Row sort in Lists of List# using map + sorted()res = list(map(lambda x: sorted(x, reverse=True), test_list)) # printing resultprint(\"The reverse sorted Matrix is : \" + str(res))",
"e": 2439,
"s": 2027,
"text": null
},
{
"code": null,
"e": 2558,
"s": 2439,
"text": "The original list is : [[4, 1, 6], [7, 8], [4, 10, 8]]\nThe reverse sorted Matrix is : [[6, 4, 1], [8, 7], [10, 8, 4]]\n"
},
{
"code": null,
"e": 2569,
"s": 2558,
"text": "satyam00so"
},
{
"code": null,
"e": 2590,
"s": 2569,
"text": "Python list-programs"
},
{
"code": null,
"e": 2611,
"s": 2590,
"text": "Python-list-of-lists"
},
{
"code": null,
"e": 2625,
"s": 2611,
"text": "Python-Matrix"
},
{
"code": null,
"e": 2637,
"s": 2625,
"text": "Python-sort"
},
{
"code": null,
"e": 2644,
"s": 2637,
"text": "Python"
},
{
"code": null,
"e": 2660,
"s": 2644,
"text": "Python Programs"
}
] |
Stream min() method in Java with Examples | 25 Jul, 2019
Stream.min() returns the minimum element of the stream based on the provided Comparator. A Comparator is a comparison function, which imposes a total ordering on some collection of objects. min() is a terminal operation which combines stream elements and returns a summary result. So, min() is a special case of reduction. The method returns Optional instance.
Syntax :
Optional<T> min(Comparator<? super T> comparator)
Where, Optional is a container object which
may or may not contain a non-null value
and T is the type of objects
that may be compared by this comparator
Exception : This method throws NullPointerException if the minimum element is null.
Example 1 : Minimum from list of Integers.
// Java code for Stream.min() method to get// the minimum element of the Stream// according to the provided Comparator.import java.util.*; class GFG { // Driver code public static void main(String[] args) { // Creating a list of integers List<Integer> list = Arrays.asList(-9, -18, 0, 25, 4); // Using stream.min() to get minimum // element according to provided Integer Comparator Integer var = list.stream().min(Integer::compare).get(); System.out.print(var); }}
Output :
-18
Example 2 : Reverse comparator to get maximum value using min() function.
// Java code for Stream.min() method// to get the minimum element of the // Stream according to provided comparator.import java.util.*; class GFG { // Driver code public static void main(String[] args) { // Creating a list of integers List<Integer> list = Arrays.asList(-9, -18, 0, 25, 4); // Using Stream.min() with reverse // comparator to get maximum element. Optional<Integer> var = list.stream() .min(Comparator.reverseOrder()); // IF var is empty, then output will be Optional.empty // else value in var is printed. if(var.isPresent()){ System.out.println(var.get()); } else{ System.out.println("NULL"); } }}
Output :
25
Example 3 : Comparing strings based on last characters.
// Java code for Stream.min() method// to get the minimum element of the // Stream according to provided comparator.import java.util.*; class GFG { // Driver code public static void main(String[] args) { // creating an array of strings String[] array = { "Geeks", "for", "GeeksforGeeks", "GeeksQuiz" }; // The Comparator compares the strings // based on their last characters and returns // the minimum value accordingly. Optional<String> MIN = Arrays.stream(array).min((str1, str2) -> Character.compare(str1.charAt(str1.length() - 1), str2.charAt(str2.length() - 1))); // If a value is present, // isPresent() will return true if (MIN.isPresent()) System.out.println(MIN.get()); else System.out.println("-1"); }}
Output :
for
Akanksha_Rai
Java - util package
Java-Functions
java-stream
Java-Stream interface
Java
Java
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Object Oriented Programming (OOPs) Concept in Java
How to iterate any Map in Java
Interfaces in Java
HashMap in Java with Examples
ArrayList in Java
Collections in Java
Stream In Java
Multidimensional Arrays in Java
Singleton Class in Java
Set in Java | [
{
"code": null,
"e": 52,
"s": 24,
"text": "\n25 Jul, 2019"
},
{
"code": null,
"e": 413,
"s": 52,
"text": "Stream.min() returns the minimum element of the stream based on the provided Comparator. A Comparator is a comparison function, which imposes a total ordering on some collection of objects. min() is a terminal operation which combines stream elements and returns a summary result. So, min() is a special case of reduction. The method returns Optional instance."
},
{
"code": null,
"e": 422,
"s": 413,
"text": "Syntax :"
},
{
"code": null,
"e": 628,
"s": 422,
"text": "Optional<T> min(Comparator<? super T> comparator)\n\nWhere, Optional is a container object which\nmay or may not contain a non-null value \nand T is the type of objects\nthat may be compared by this comparator\n"
},
{
"code": null,
"e": 712,
"s": 628,
"text": "Exception : This method throws NullPointerException if the minimum element is null."
},
{
"code": null,
"e": 755,
"s": 712,
"text": "Example 1 : Minimum from list of Integers."
},
{
"code": "// Java code for Stream.min() method to get// the minimum element of the Stream// according to the provided Comparator.import java.util.*; class GFG { // Driver code public static void main(String[] args) { // Creating a list of integers List<Integer> list = Arrays.asList(-9, -18, 0, 25, 4); // Using stream.min() to get minimum // element according to provided Integer Comparator Integer var = list.stream().min(Integer::compare).get(); System.out.print(var); }}",
"e": 1283,
"s": 755,
"text": null
},
{
"code": null,
"e": 1292,
"s": 1283,
"text": "Output :"
},
{
"code": null,
"e": 1297,
"s": 1292,
"text": "-18\n"
},
{
"code": null,
"e": 1371,
"s": 1297,
"text": "Example 2 : Reverse comparator to get maximum value using min() function."
},
{
"code": "// Java code for Stream.min() method// to get the minimum element of the // Stream according to provided comparator.import java.util.*; class GFG { // Driver code public static void main(String[] args) { // Creating a list of integers List<Integer> list = Arrays.asList(-9, -18, 0, 25, 4); // Using Stream.min() with reverse // comparator to get maximum element. Optional<Integer> var = list.stream() .min(Comparator.reverseOrder()); // IF var is empty, then output will be Optional.empty // else value in var is printed. if(var.isPresent()){ System.out.println(var.get()); } else{ System.out.println(\"NULL\"); } }}",
"e": 2131,
"s": 1371,
"text": null
},
{
"code": null,
"e": 2140,
"s": 2131,
"text": "Output :"
},
{
"code": null,
"e": 2144,
"s": 2140,
"text": "25\n"
},
{
"code": null,
"e": 2200,
"s": 2144,
"text": "Example 3 : Comparing strings based on last characters."
},
{
"code": "// Java code for Stream.min() method// to get the minimum element of the // Stream according to provided comparator.import java.util.*; class GFG { // Driver code public static void main(String[] args) { // creating an array of strings String[] array = { \"Geeks\", \"for\", \"GeeksforGeeks\", \"GeeksQuiz\" }; // The Comparator compares the strings // based on their last characters and returns // the minimum value accordingly. Optional<String> MIN = Arrays.stream(array).min((str1, str2) -> Character.compare(str1.charAt(str1.length() - 1), str2.charAt(str2.length() - 1))); // If a value is present, // isPresent() will return true if (MIN.isPresent()) System.out.println(MIN.get()); else System.out.println(\"-1\"); }}",
"e": 3114,
"s": 2200,
"text": null
},
{
"code": null,
"e": 3123,
"s": 3114,
"text": "Output :"
},
{
"code": null,
"e": 3128,
"s": 3123,
"text": "for\n"
},
{
"code": null,
"e": 3141,
"s": 3128,
"text": "Akanksha_Rai"
},
{
"code": null,
"e": 3161,
"s": 3141,
"text": "Java - util package"
},
{
"code": null,
"e": 3176,
"s": 3161,
"text": "Java-Functions"
},
{
"code": null,
"e": 3188,
"s": 3176,
"text": "java-stream"
},
{
"code": null,
"e": 3210,
"s": 3188,
"text": "Java-Stream interface"
},
{
"code": null,
"e": 3215,
"s": 3210,
"text": "Java"
},
{
"code": null,
"e": 3220,
"s": 3215,
"text": "Java"
},
{
"code": null,
"e": 3318,
"s": 3220,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 3369,
"s": 3318,
"text": "Object Oriented Programming (OOPs) Concept in Java"
},
{
"code": null,
"e": 3400,
"s": 3369,
"text": "How to iterate any Map in Java"
},
{
"code": null,
"e": 3419,
"s": 3400,
"text": "Interfaces in Java"
},
{
"code": null,
"e": 3449,
"s": 3419,
"text": "HashMap in Java with Examples"
},
{
"code": null,
"e": 3467,
"s": 3449,
"text": "ArrayList in Java"
},
{
"code": null,
"e": 3487,
"s": 3467,
"text": "Collections in Java"
},
{
"code": null,
"e": 3502,
"s": 3487,
"text": "Stream In Java"
},
{
"code": null,
"e": 3534,
"s": 3502,
"text": "Multidimensional Arrays in Java"
},
{
"code": null,
"e": 3558,
"s": 3534,
"text": "Singleton Class in Java"
}
] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.