title
stringlengths
3
221
text
stringlengths
17
477k
parsed
listlengths
0
3.17k
How to have actual values in Matplotlib Pie Chart displayed?
To have actual or any custom values in Matplotlib pie chart displayed, we can take the following steps − Set the figure size and adjust the padding between and around the subplots. Make lists of labels, fractions, explode position and get the sum of fractions to calculate the percentage Make a pie chart using labels, fracs and explode with autopct=lambda p: <calculation for percentage>. To display the figure, use show() method. import matplotlib.pyplot as plt plt.rcParams["figure.figsize"] = [7.50, 3.50] plt.rcParams["figure.autolayout"] = True labels = ('Read', 'Eat', 'Sleep', 'Repeat') fracs = [5, 3, 4, 1] total = sum(fracs) explode = (0, 0.05, 0, 0) plt.pie(fracs, explode=explode, labels=labels, autopct=lambda p: '{:.0f}%'.format(p * total / 100), shadow=True, startangle=90) plt.show()
[ { "code": null, "e": 1167, "s": 1062, "text": "To have actual or any custom values in Matplotlib pie chart displayed, we can take the following steps −" }, { "code": null, "e": 1243, "s": 1167, "text": "Set the figure size and adjust the padding between and around the subplots." }, { "code": null, "e": 1350, "s": 1243, "text": "Make lists of labels, fractions, explode position and get the sum of fractions to calculate the percentage" }, { "code": null, "e": 1452, "s": 1350, "text": "Make a pie chart using labels, fracs and explode with autopct=lambda p: <calculation for percentage>." }, { "code": null, "e": 1494, "s": 1452, "text": "To display the figure, use show() method." }, { "code": null, "e": 1873, "s": 1494, "text": "import matplotlib.pyplot as plt\n\nplt.rcParams[\"figure.figsize\"] = [7.50, 3.50]\nplt.rcParams[\"figure.autolayout\"] = True\n\nlabels = ('Read', 'Eat', 'Sleep', 'Repeat')\n\nfracs = [5, 3, 4, 1]\ntotal = sum(fracs)\nexplode = (0, 0.05, 0, 0)\n\nplt.pie(fracs, explode=explode, labels=labels,\n autopct=lambda p: '{:.0f}%'.format(p * total / 100),\n shadow=True, startangle=90)\n\nplt.show()" } ]
Difference between IEnumerator and IEnumerable Interface in C#
IEnumerable and IEnumerator both are interfaces in C#. IEnumerable is an interface defining a single method GetEnumerator() that returns an IEnumerator interface. This works for readonly access to a collection that implements that IEnumerable can be used with a foreach statement. IEnumerator has two methods MoveNext and Reset. It also has a property called Current. The following shows the implementation of IEnumerable and IEnumerator. class Demo : IEnumerable, IEnumerator { // IEnumerable method GetEnumerator() IEnumerator IEnumerable.GetEnumerator() { throw new NotImplementedException(); } public object Current { get { throw new NotImplementedException(); } } // IEnumertor method public bool MoveNext() { throw new NotImplementedException(); } // IEnumertor method public void Reset() { throw new NotImplementedException(); } } Above you can see the two methods of IEnumerator. // IEnumertor method public bool MoveNext() { throw new NotImplementedException(); } // IEnumertor method public void Reset() { throw new NotImplementedException(); }
[ { "code": null, "e": 1117, "s": 1062, "text": "IEnumerable and IEnumerator both are interfaces in C#." }, { "code": null, "e": 1225, "s": 1117, "text": "IEnumerable is an interface defining a single method GetEnumerator() that returns an IEnumerator interface." }, { "code": null, "e": 1343, "s": 1225, "text": "This works for readonly access to a collection that implements that IEnumerable can be used with a foreach statement." }, { "code": null, "e": 1430, "s": 1343, "text": "IEnumerator has two methods MoveNext and Reset. It also has a property called Current." }, { "code": null, "e": 1501, "s": 1430, "text": "The following shows the implementation of IEnumerable and IEnumerator." }, { "code": null, "e": 1960, "s": 1501, "text": "class Demo : IEnumerable, IEnumerator {\n // IEnumerable method GetEnumerator()\n IEnumerator IEnumerable.GetEnumerator() {\n throw new NotImplementedException();\n }\n public object Current {\n get { throw new NotImplementedException(); }\n }\n // IEnumertor method\n public bool MoveNext() {\n throw new NotImplementedException();\n }\n // IEnumertor method\n public void Reset() {\n throw new NotImplementedException();\n }\n}" }, { "code": null, "e": 2010, "s": 1960, "text": "Above you can see the two methods of IEnumerator." }, { "code": null, "e": 2184, "s": 2010, "text": "// IEnumertor method\npublic bool MoveNext() {\n throw new NotImplementedException();\n}\n\n// IEnumertor method\npublic void Reset() {\n throw new NotImplementedException();\n}" } ]
How to adapt a multilingual T5 model for a single language | by David Dale | Towards Data Science
T5 is an encoder-decoder transformer from Google that once was SOTA on several NLU and NLG problems and is still very useful as a base for seq2seq tasks such as text summarization. The first T5 model was for English only, and then the massively multilingual version followed. This model covers 101 languages and is massive indeed. This post shows how to extract a single-language model from the multilingual one by pruning its redundant embeddings. This reduces the number of parameters more than twice without significant loss in quality. Our result is for Russian, but you can try it with any other of the 101 languages that mT5 features. The idea is similar to one in the paper Load What You Need: Smaller Versions of Multilingual BERT. We use the original tokenizer to process a Russian corpus, count the frequencies of different tokens, and preserve only the tokens that were used frequently enough, pruning all the others. We also preserve a small number of English tokens in the model to make it bilingual. We need this to enable the model to transfer knowledge from English to Russian downstream tasks, and also because English words and phrases often occur within modern Russian texts. We start by loading the existing multilingual model. import torchfrom transformers import T5ForConditionalGeneration, T5Tokenizertokenizer = T5Tokenizer.from_pretrained("google/mt5-base")model = T5ForConditionalGeneration.from_pretrained('google/mt5-base') The model consists mostly of embeddings: 33% of its parameters are input embeddings (shared between its encoder and decoder) and 33% are output embeddings. def msize(m): return sum(p.numel() for p in m.parameters())print(msize(model.shared) / msize(model)) # 0.3298print(msize(model.lm_head) / msize(model)) # 0.3298 To estimate the frequency of different tokens, we take a Russian and an English sentence corpora from the Leipzig corpora collection. We use these two languages because we want our model to be bilingual in the end. import pandas as pdimport csvfrom collections import Counterfrom tqdm.auto import tqdm, trangedf_ru = pd.read_csv('rus-ru_web-public_2019_1M-sentences.txt', sep='\t', header=None, quoting=csv.QUOTE_NONE)df_ru.columns = ['idx', 'text']cnt_ru = Counter()for text in tqdm(df_ru.text): cnt_ru.update(tokenizer.encode(text))print(len(cnt_ru), len(cnt_ru)/tokenizer.vocab_size) # 58438 0.2336 After counting the tokens in the Russian corpus we discover that only 23% of the model vocabulary was used. Moreover, the top 20K tokens constitute more than 99% of the Russian corpus. For English, the statistics are similar. for top in 10_000, 20_000, 30_000: print(top, sum(v for k, v in cnt_ru.most_common(top)) / sum(cnt_ru.values()))# 10000 0.9645# 20000 0.9940# 30000 0.9982 We decide to use the following composition of vocabulary: 1K of top tokens of the original tokenizer (just in case) Top 10K of the English vocabulary Top 20K of the Russian vocabulary The 100 special tokens that T5 uses This gives us a vocabulary of 30K tokens, 12% of the 250K tokens in the multilingual version. new_tokens = set(range(1000))for i, (k, v) in enumerate(cnt_en.most_common(10_000)): if k not in new_tokens: new_tokens.add(k)for i, (k, v) in enumerate(cnt_ru.most_common(25_000)): if len(new_tokens) == 29_900: print(i, 'Russan tokens are included') break if k not in new_tokens: new_tokens.add(k)for t in range(tokenizer.vocab_size - 100, tokenizer.vocab_size): new_tokens.add(t)print(len(new_tokens))kept_ids = sorted(new_tokens) Updating the neural networks is easy: just replace the parameters of its input and output embeddings. This reduces the model size by 58% (from 2.2GB to 0.9GB). new_size = len(kept_ids)new_emb = torch.nn.Embedding(new_size, model.shared.embedding_dim)new_head = torch.nn.Linear(in_features=model.lm_head.in_features, out_features=new_size, bias=False)for new_id, old_id in enumerate(kept_ids): new_emb.weight.data[new_id] = model.shared.weight.data[old_id] new_head.weight.data[new_id] = model.lm_head.weight.data[old_id]model.shared.weight = new_emb.weightmodel.lm_head.weight = new_head.weightmodel.config.__dict__['vocab_size'] = new_sizemodel.config.__dict__['_name_or_path'] = 'cointegrated/rut5-base' Updating the tokenizer is surprisingly more tricky. T5 uses Sentencepiece tokenizer, which is implemented in C and is opaque to Python. Fortunately, we can download its model and deploy it into Python using its Protobuf representation. ! wget https://raw.githubusercontent.com/google/sentencepiece/master/src/sentencepiece_model.proto! protoc --python_out=. sentencepiece_model.protoimport sentencepiece_model_pb2 as spmpsmp = tokenizer.sp_model.serialized_model_proto()m = spmp.ModelProto()m.ParseFromString(smp)print('the loaded model has pieces:', len(m.pieces))new_pieces = [m.pieces[idx] for idx in kept_ids]print('the new pieces:', len(new_pieces))# replace the content of the first 30K piecesfor i, p in enumerate(new_pieces): m.pieces[i].piece = p.piece m.pieces[i].score = p.score m.pieces[i].type = p.type# drop the remaining piecesn = len(new_pieces)for i in trange(len(m.pieces) - n): m.pieces.pop(len(m.pieces) - 1)print(len(m.pieces))with open('new_sp.model', 'wb') as f: f.write(m.SerializeToString())new_tokenizer = T5Tokenizer('new_sp.model', extra_ids=0) Now we can save the new model and the new tokenizer. new_tokenizer.save_pretrained('rut5-base')model.save_pretrained('rut5-base') All the code for creating models up to this stage is available on Github. The Russian T5 model is available in the Huggingface repository. Frankly, this model is pretty useless by itself, because mT5 was trained only on the unsupervised task of predicting missing words. However, this model can be fine-tuned for many other tasks: text summarization, translation, dialogue response generation, paraphrasing, etc. In the next post, we will show how to perform such fine-tuning. Subscribe to stay tuned! The post was written by David Dale (https://daviddale.ru/en), a research scientist in NLP and developer of chatbots.
[ { "code": null, "e": 377, "s": 46, "text": "T5 is an encoder-decoder transformer from Google that once was SOTA on several NLU and NLG problems and is still very useful as a base for seq2seq tasks such as text summarization. The first T5 model was for English only, and then the massively multilingual version followed. This model covers 101 languages and is massive indeed." }, { "code": null, "e": 687, "s": 377, "text": "This post shows how to extract a single-language model from the multilingual one by pruning its redundant embeddings. This reduces the number of parameters more than twice without significant loss in quality. Our result is for Russian, but you can try it with any other of the 101 languages that mT5 features." }, { "code": null, "e": 975, "s": 687, "text": "The idea is similar to one in the paper Load What You Need: Smaller Versions of Multilingual BERT. We use the original tokenizer to process a Russian corpus, count the frequencies of different tokens, and preserve only the tokens that were used frequently enough, pruning all the others." }, { "code": null, "e": 1241, "s": 975, "text": "We also preserve a small number of English tokens in the model to make it bilingual. We need this to enable the model to transfer knowledge from English to Russian downstream tasks, and also because English words and phrases often occur within modern Russian texts." }, { "code": null, "e": 1294, "s": 1241, "text": "We start by loading the existing multilingual model." }, { "code": null, "e": 1498, "s": 1294, "text": "import torchfrom transformers import T5ForConditionalGeneration, T5Tokenizertokenizer = T5Tokenizer.from_pretrained(\"google/mt5-base\")model = T5ForConditionalGeneration.from_pretrained('google/mt5-base')" }, { "code": null, "e": 1654, "s": 1498, "text": "The model consists mostly of embeddings: 33% of its parameters are input embeddings (shared between its encoder and decoder) and 33% are output embeddings." }, { "code": null, "e": 1821, "s": 1654, "text": "def msize(m): return sum(p.numel() for p in m.parameters())print(msize(model.shared) / msize(model)) # 0.3298print(msize(model.lm_head) / msize(model)) # 0.3298" }, { "code": null, "e": 2036, "s": 1821, "text": "To estimate the frequency of different tokens, we take a Russian and an English sentence corpora from the Leipzig corpora collection. We use these two languages because we want our model to be bilingual in the end." }, { "code": null, "e": 2427, "s": 2036, "text": "import pandas as pdimport csvfrom collections import Counterfrom tqdm.auto import tqdm, trangedf_ru = pd.read_csv('rus-ru_web-public_2019_1M-sentences.txt', sep='\\t', header=None, quoting=csv.QUOTE_NONE)df_ru.columns = ['idx', 'text']cnt_ru = Counter()for text in tqdm(df_ru.text): cnt_ru.update(tokenizer.encode(text))print(len(cnt_ru), len(cnt_ru)/tokenizer.vocab_size) # 58438 0.2336" }, { "code": null, "e": 2653, "s": 2427, "text": "After counting the tokens in the Russian corpus we discover that only 23% of the model vocabulary was used. Moreover, the top 20K tokens constitute more than 99% of the Russian corpus. For English, the statistics are similar." }, { "code": null, "e": 2811, "s": 2653, "text": "for top in 10_000, 20_000, 30_000: print(top, sum(v for k, v in cnt_ru.most_common(top)) / sum(cnt_ru.values()))# 10000 0.9645# 20000 0.9940# 30000 0.9982" }, { "code": null, "e": 2869, "s": 2811, "text": "We decide to use the following composition of vocabulary:" }, { "code": null, "e": 2927, "s": 2869, "text": "1K of top tokens of the original tokenizer (just in case)" }, { "code": null, "e": 2961, "s": 2927, "text": "Top 10K of the English vocabulary" }, { "code": null, "e": 2995, "s": 2961, "text": "Top 20K of the Russian vocabulary" }, { "code": null, "e": 3031, "s": 2995, "text": "The 100 special tokens that T5 uses" }, { "code": null, "e": 3125, "s": 3031, "text": "This gives us a vocabulary of 30K tokens, 12% of the 250K tokens in the multilingual version." }, { "code": null, "e": 3598, "s": 3125, "text": "new_tokens = set(range(1000))for i, (k, v) in enumerate(cnt_en.most_common(10_000)): if k not in new_tokens: new_tokens.add(k)for i, (k, v) in enumerate(cnt_ru.most_common(25_000)): if len(new_tokens) == 29_900: print(i, 'Russan tokens are included') break if k not in new_tokens: new_tokens.add(k)for t in range(tokenizer.vocab_size - 100, tokenizer.vocab_size): new_tokens.add(t)print(len(new_tokens))kept_ids = sorted(new_tokens)" }, { "code": null, "e": 3758, "s": 3598, "text": "Updating the neural networks is easy: just replace the parameters of its input and output embeddings. This reduces the model size by 58% (from 2.2GB to 0.9GB)." }, { "code": null, "e": 4310, "s": 3758, "text": "new_size = len(kept_ids)new_emb = torch.nn.Embedding(new_size, model.shared.embedding_dim)new_head = torch.nn.Linear(in_features=model.lm_head.in_features, out_features=new_size, bias=False)for new_id, old_id in enumerate(kept_ids): new_emb.weight.data[new_id] = model.shared.weight.data[old_id] new_head.weight.data[new_id] = model.lm_head.weight.data[old_id]model.shared.weight = new_emb.weightmodel.lm_head.weight = new_head.weightmodel.config.__dict__['vocab_size'] = new_sizemodel.config.__dict__['_name_or_path'] = 'cointegrated/rut5-base'" }, { "code": null, "e": 4546, "s": 4310, "text": "Updating the tokenizer is surprisingly more tricky. T5 uses Sentencepiece tokenizer, which is implemented in C and is opaque to Python. Fortunately, we can download its model and deploy it into Python using its Protobuf representation." }, { "code": null, "e": 5398, "s": 4546, "text": "! wget https://raw.githubusercontent.com/google/sentencepiece/master/src/sentencepiece_model.proto! protoc --python_out=. sentencepiece_model.protoimport sentencepiece_model_pb2 as spmpsmp = tokenizer.sp_model.serialized_model_proto()m = spmp.ModelProto()m.ParseFromString(smp)print('the loaded model has pieces:', len(m.pieces))new_pieces = [m.pieces[idx] for idx in kept_ids]print('the new pieces:', len(new_pieces))# replace the content of the first 30K piecesfor i, p in enumerate(new_pieces): m.pieces[i].piece = p.piece m.pieces[i].score = p.score m.pieces[i].type = p.type# drop the remaining piecesn = len(new_pieces)for i in trange(len(m.pieces) - n): m.pieces.pop(len(m.pieces) - 1)print(len(m.pieces))with open('new_sp.model', 'wb') as f: f.write(m.SerializeToString())new_tokenizer = T5Tokenizer('new_sp.model', extra_ids=0)" }, { "code": null, "e": 5451, "s": 5398, "text": "Now we can save the new model and the new tokenizer." }, { "code": null, "e": 5528, "s": 5451, "text": "new_tokenizer.save_pretrained('rut5-base')model.save_pretrained('rut5-base')" }, { "code": null, "e": 5667, "s": 5528, "text": "All the code for creating models up to this stage is available on Github. The Russian T5 model is available in the Huggingface repository." }, { "code": null, "e": 6030, "s": 5667, "text": "Frankly, this model is pretty useless by itself, because mT5 was trained only on the unsupervised task of predicting missing words. However, this model can be fine-tuned for many other tasks: text summarization, translation, dialogue response generation, paraphrasing, etc. In the next post, we will show how to perform such fine-tuning. Subscribe to stay tuned!" } ]
Write a Golang program to print the Fibonacci series
Definition: In a Fibonacci series, the next number would be the summation of its two previous numbers, series starting from 0 and 1. Print a fibonacci series up to num = 10; Series: 1, 2, 3, 5, 8, next is 13 but greater than 10; Step 1: Define a function that accepts a numbers(num) type is int, till then need to print the series. Step 2: Take two initial numbers for the series, i.e., 0 and 1. Step 3: Start a true for loop and declare a third variable to store previous two values. Step 4: Print the summation of two numbers until the summation is lesser than the given num. Live Demo package main import "fmt" func printFibonacciSeries(num int){ a := 0 b := 1 c := b fmt.Printf("Series is: %d %d", a, b) for true{ c = b b = a + b if b >= num{ fmt.Println() break } a = c fmt.Printf(" %d", b) } } func main(){ printFibonacciSeries(10) printFibonacciSeries(16) printFibonacciSeries(100) } Series is: 0 1 1 2 3 5 8 Series is: 0 1 1 2 3 5 8 13 Series is: 0 1 1 2 3 5 8 13 21 34 55 89
[ { "code": null, "e": 1195, "s": 1062, "text": "Definition: In a Fibonacci series, the next number would be the summation of its two previous numbers, series starting from 0 and 1." }, { "code": null, "e": 1236, "s": 1195, "text": "Print a fibonacci series up to num = 10;" }, { "code": null, "e": 1291, "s": 1236, "text": "Series: 1, 2, 3, 5, 8, next is 13 but greater than 10;" }, { "code": null, "e": 1394, "s": 1291, "text": "Step 1: Define a function that accepts a numbers(num) type is int, till then need to print the series." }, { "code": null, "e": 1458, "s": 1394, "text": "Step 2: Take two initial numbers for the series, i.e., 0 and 1." }, { "code": null, "e": 1547, "s": 1458, "text": "Step 3: Start a true for loop and declare a third variable to store previous two values." }, { "code": null, "e": 1640, "s": 1547, "text": "Step 4: Print the summation of two numbers until the summation is lesser than the given num." }, { "code": null, "e": 1650, "s": 1640, "text": "Live Demo" }, { "code": null, "e": 2036, "s": 1650, "text": "package main\nimport \"fmt\"\n\nfunc printFibonacciSeries(num int){\n a := 0\n b := 1\n c := b\n fmt.Printf(\"Series is: %d %d\", a, b)\n for true{\n c = b\n b = a + b\n if b >= num{\n fmt.Println()\n break\n }\n a = c\n fmt.Printf(\" %d\", b)\n }\n}\n\nfunc main(){\n printFibonacciSeries(10)\n printFibonacciSeries(16)\n printFibonacciSeries(100)\n}" }, { "code": null, "e": 2129, "s": 2036, "text": "Series is: 0 1 1 2 3 5 8\nSeries is: 0 1 1 2 3 5 8 13\nSeries is: 0 1 1 2 3 5 8 13 21 34 55 89" } ]
Hibernate - One-to-Many Mapping - GeeksforGeeks
27 Dec, 2021 Spring Boot is built on the top of the spring and contains all the features of spring. Spring also provides JPA and hibernate to increase the data manipulation efficiency between the spring application and the database. In very simple terms we can say JPA (Java persistence api) is like an interface and the hibernate is the implementation of the methods of the interface Like how insertion will be down is already defined with the help of hibernating. In this article, we will discuss One-to-Many Mapping in the Hibernate. Let’ understand the One to many mapping with the help of a real-life example. Bike manufacture can manufacture multiple models of the bike but the same bike model cannot be manufactured by multiple manufactures. Syntax: @oneToMany(mappedby=”nameofmappedvariable”) This mappedvariable of the other tables is responsible for mapping between two tables. Spring Initializer is a web-based tool using which we can easily generate the structure of the Spring Boot project. It also provides various different features for the projects expressed in a metadata model. This model allows us to configure the list of dependencies that are supported by JVM. Here, we will create the structure of an application using a spring initializer. Step 1: Go to this link. Fill in the details as per the requirements. For this application: Project: Maven Language: Java Spring Boot: 2.5.7 Packaging: JAR Java: 11 Dependencies: Spring Web,Spring Data JPA, MySql Driver Click on Generate which will download the starter project. Step 2: Extract the zip file. Now open a suitable IDE and then go to File > New > Project from existing sources > Spring-boot-app and select pom.xml. Click on import changes on prompt and wait for the project to sync as pictorially depicted below as follows: Project Structure: One to Many Mapping Step 3: Adding the necessary properties in the application.properties file. (mapping is the database name) spring.datasource.username=root spring.datasource.password=Aayush spring.datasource.url=jdbc:mysql://localhost:3306/mapping spring.jpa.hibernate.ddl-auto=update Step 4: Go to src->main->java->com->example->Mapping and create two files in the models folder i.e Manufactures.java and Model.java Project structure: Manufactures.java Java package com.example.Mapping.Models; import javax.persistence.*;import java.util.List; @Entitypublic class Manufactures { @Id @GeneratedValue(strategy = GenerationType.IDENTITY) private int id; // One manufactures can produces // multiple models of the bike private String manufactures_name; @OneToMany(mappedBy ="ob") private List<Model>models; public Manufactures(int id, String manufactures_name) { this.id = id; this.manufactures_name = manufactures_name; } Manufactures(){ } public int getId() { return id; } public void setId(int id) { this.id = id; } public String getManufactures_name() { return manufactures_name; } public void setManufactures_name(String manufactures_name) { this.manufactures_name = manufactures_name; }} Models(Mapped by table) Java package com.example.Mapping.Models; import javax.persistence.Entity;import javax.persistence.Id;import javax.persistence.JoinColumn;import javax.persistence.ManyToOne; @Entitypublic class Model { @Id private int model_id; private String name; @ManyToOne @JoinColumn(name = "manufacture_id") private Manufactures ob; public Model(int model_id, String name, Manufactures ob) { this.model_id = model_id; this.name = name; this.ob = ob; } Model(){ } public int getModel_id() { return model_id; } public void setModel_id(int model_id) { this.model_id = model_id; } public String getName() { return name; } public void setName(String name) { this.name = name; } public Manufactures getOb() { return ob; } public void setOb(Manufactures ob) { this.ob = ob; }} Step 5: Adding the JPA repository of both classes in the project structure: ManufactureRepo Java package com.example.Mapping.Reposteries; import com.example.Mapping.Models.Manufactures;import org.springframework.data.jpa.repository.JpaRepository; public interface ManufacturesRepo extends JpaRepository<Manufactures,Integer> { } ModelRepo: Java package com.example.Mapping.Reposteries; import com.example.Mapping.Models.Model;import org.springframework.data.jpa.repository.JpaRepository; public interface ModelRepo extends JpaRepository<Model, Integer> {} MappingApplication: Java package com.example.Mapping; import com.example.Mapping.Models.Manufactures;import com.example.Mapping.Models.Model;import com.example.Mapping.Reposteries.ManufacturesRepo;import com.example.Mapping.Reposteries.ModelRepo;import org.springframework.beans.factory.annotation.Autowired;import org.springframework.boot.CommandLineRunner;import org.springframework.boot.SpringApplication;import org.springframework.boot.autoconfigure.SpringBootApplication; @SpringBootApplicationpublic class MappingApplication implements CommandLineRunner { @Autowired ManufacturesRepo manufacturesRepo; @Autowired ModelRepo modelRepo; public static void main(String[] args) { SpringApplication.run(MappingApplication.class, args); } @Override public void run(String... args) throws Exception { Manufactures data=new Manufactures(1,"Honda"); // Inserting the record in the Manufactures table. manufacturesRepo.save(data); // Now try to mapped above record with multiple models Model model1=new Model(1,"AYZ",data); Model model2=new Model(2,"ZET",data); modelRepo.save(model1); modelRepo.save(model2); }} Run the main application: manufacture table model table varshagumber28 rajeev0719singh Java-Hibernate Picked Java Java Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Stream In Java Different ways of Reading a text file in Java Constructors in Java Exceptions in Java Generics in Java Functional Interfaces in Java Comparator Interface in Java with Examples HashMap get() Method in Java Introduction to Java Difference between Abstract Class and Interface in Java
[ { "code": null, "e": 23973, "s": 23945, "text": "\n27 Dec, 2021" }, { "code": null, "e": 24709, "s": 23973, "text": "Spring Boot is built on the top of the spring and contains all the features of spring. Spring also provides JPA and hibernate to increase the data manipulation efficiency between the spring application and the database. In very simple terms we can say JPA (Java persistence api) is like an interface and the hibernate is the implementation of the methods of the interface Like how insertion will be down is already defined with the help of hibernating. In this article, we will discuss One-to-Many Mapping in the Hibernate. Let’ understand the One to many mapping with the help of a real-life example. Bike manufacture can manufacture multiple models of the bike but the same bike model cannot be manufactured by multiple manufactures." }, { "code": null, "e": 24717, "s": 24709, "text": "Syntax:" }, { "code": null, "e": 24762, "s": 24717, "text": "@oneToMany(mappedby=”nameofmappedvariable”) " }, { "code": null, "e": 24849, "s": 24762, "text": "This mappedvariable of the other tables is responsible for mapping between two tables." }, { "code": null, "e": 25224, "s": 24849, "text": "Spring Initializer is a web-based tool using which we can easily generate the structure of the Spring Boot project. It also provides various different features for the projects expressed in a metadata model. This model allows us to configure the list of dependencies that are supported by JVM. Here, we will create the structure of an application using a spring initializer." }, { "code": null, "e": 25316, "s": 25224, "text": "Step 1: Go to this link. Fill in the details as per the requirements. For this application:" }, { "code": null, "e": 25444, "s": 25316, "text": "Project: Maven\nLanguage: Java\nSpring Boot: 2.5.7\nPackaging: JAR\nJava: 11\nDependencies: Spring Web,Spring Data JPA, MySql Driver" }, { "code": null, "e": 25503, "s": 25444, "text": "Click on Generate which will download the starter project." }, { "code": null, "e": 25762, "s": 25503, "text": "Step 2: Extract the zip file. Now open a suitable IDE and then go to File > New > Project from existing sources > Spring-boot-app and select pom.xml. Click on import changes on prompt and wait for the project to sync as pictorially depicted below as follows:" }, { "code": null, "e": 25781, "s": 25762, "text": "Project Structure:" }, { "code": null, "e": 25801, "s": 25781, "text": "One to Many Mapping" }, { "code": null, "e": 25908, "s": 25801, "text": "Step 3: Adding the necessary properties in the application.properties file. (mapping is the database name)" }, { "code": null, "e": 26069, "s": 25908, "text": "spring.datasource.username=root\nspring.datasource.password=Aayush\nspring.datasource.url=jdbc:mysql://localhost:3306/mapping\nspring.jpa.hibernate.ddl-auto=update" }, { "code": null, "e": 26204, "s": 26069, "text": "Step 4: Go to src->main->java->com->example->Mapping and create two files in the models folder i.e Manufactures.java and Model.java" }, { "code": null, "e": 26223, "s": 26204, "text": "Project structure:" }, { "code": null, "e": 26241, "s": 26223, "text": "Manufactures.java" }, { "code": null, "e": 26246, "s": 26241, "text": "Java" }, { "code": "package com.example.Mapping.Models; import javax.persistence.*;import java.util.List; @Entitypublic class Manufactures { @Id @GeneratedValue(strategy = GenerationType.IDENTITY) private int id; // One manufactures can produces // multiple models of the bike private String manufactures_name; @OneToMany(mappedBy =\"ob\") private List<Model>models; public Manufactures(int id, String manufactures_name) { this.id = id; this.manufactures_name = manufactures_name; } Manufactures(){ } public int getId() { return id; } public void setId(int id) { this.id = id; } public String getManufactures_name() { return manufactures_name; } public void setManufactures_name(String manufactures_name) { this.manufactures_name = manufactures_name; }}", "e": 27099, "s": 26246, "text": null }, { "code": null, "e": 27123, "s": 27099, "text": "Models(Mapped by table)" }, { "code": null, "e": 27128, "s": 27123, "text": "Java" }, { "code": "package com.example.Mapping.Models; import javax.persistence.Entity;import javax.persistence.Id;import javax.persistence.JoinColumn;import javax.persistence.ManyToOne; @Entitypublic class Model { @Id private int model_id; private String name; @ManyToOne @JoinColumn(name = \"manufacture_id\") private Manufactures ob; public Model(int model_id, String name, Manufactures ob) { this.model_id = model_id; this.name = name; this.ob = ob; } Model(){ } public int getModel_id() { return model_id; } public void setModel_id(int model_id) { this.model_id = model_id; } public String getName() { return name; } public void setName(String name) { this.name = name; } public Manufactures getOb() { return ob; } public void setOb(Manufactures ob) { this.ob = ob; }}", "e": 28026, "s": 27128, "text": null }, { "code": null, "e": 28102, "s": 28026, "text": "Step 5: Adding the JPA repository of both classes in the project structure:" }, { "code": null, "e": 28118, "s": 28102, "text": "ManufactureRepo" }, { "code": null, "e": 28123, "s": 28118, "text": "Java" }, { "code": "package com.example.Mapping.Reposteries; import com.example.Mapping.Models.Manufactures;import org.springframework.data.jpa.repository.JpaRepository; public interface ManufacturesRepo extends JpaRepository<Manufactures,Integer> { }", "e": 28357, "s": 28123, "text": null }, { "code": null, "e": 28368, "s": 28357, "text": "ModelRepo:" }, { "code": null, "e": 28373, "s": 28368, "text": "Java" }, { "code": "package com.example.Mapping.Reposteries; import com.example.Mapping.Models.Model;import org.springframework.data.jpa.repository.JpaRepository; public interface ModelRepo extends JpaRepository<Model, Integer> {}", "e": 28584, "s": 28373, "text": null }, { "code": null, "e": 28604, "s": 28584, "text": "MappingApplication:" }, { "code": null, "e": 28609, "s": 28604, "text": "Java" }, { "code": "package com.example.Mapping; import com.example.Mapping.Models.Manufactures;import com.example.Mapping.Models.Model;import com.example.Mapping.Reposteries.ManufacturesRepo;import com.example.Mapping.Reposteries.ModelRepo;import org.springframework.beans.factory.annotation.Autowired;import org.springframework.boot.CommandLineRunner;import org.springframework.boot.SpringApplication;import org.springframework.boot.autoconfigure.SpringBootApplication; @SpringBootApplicationpublic class MappingApplication implements CommandLineRunner { @Autowired ManufacturesRepo manufacturesRepo; @Autowired ModelRepo modelRepo; public static void main(String[] args) { SpringApplication.run(MappingApplication.class, args); } @Override public void run(String... args) throws Exception { Manufactures data=new Manufactures(1,\"Honda\"); // Inserting the record in the Manufactures table. manufacturesRepo.save(data); // Now try to mapped above record with multiple models Model model1=new Model(1,\"AYZ\",data); Model model2=new Model(2,\"ZET\",data); modelRepo.save(model1); modelRepo.save(model2); }}", "e": 29794, "s": 28609, "text": null }, { "code": null, "e": 29820, "s": 29794, "text": "Run the main application:" }, { "code": null, "e": 29838, "s": 29820, "text": "manufacture table" }, { "code": null, "e": 29850, "s": 29838, "text": "model table" }, { "code": null, "e": 29865, "s": 29850, "text": "varshagumber28" }, { "code": null, "e": 29881, "s": 29865, "text": "rajeev0719singh" }, { "code": null, "e": 29896, "s": 29881, "text": "Java-Hibernate" }, { "code": null, "e": 29903, "s": 29896, "text": "Picked" }, { "code": null, "e": 29908, "s": 29903, "text": "Java" }, { "code": null, "e": 29913, "s": 29908, "text": "Java" }, { "code": null, "e": 30011, "s": 29913, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 30026, "s": 30011, "text": "Stream In Java" }, { "code": null, "e": 30072, "s": 30026, "text": "Different ways of Reading a text file in Java" }, { "code": null, "e": 30093, "s": 30072, "text": "Constructors in Java" }, { "code": null, "e": 30112, "s": 30093, "text": "Exceptions in Java" }, { "code": null, "e": 30129, "s": 30112, "text": "Generics in Java" }, { "code": null, "e": 30159, "s": 30129, "text": "Functional Interfaces in Java" }, { "code": null, "e": 30202, "s": 30159, "text": "Comparator Interface in Java with Examples" }, { "code": null, "e": 30231, "s": 30202, "text": "HashMap get() Method in Java" }, { "code": null, "e": 30252, "s": 30231, "text": "Introduction to Java" } ]
Laravel - Blade Templates
Laravel 5.1 introduces the concept of using Blade, a templating engine to design a unique layout. The layout thus designed can be used by other views, and includes a consistent design and structure. When compared to other templating engines, Blade is unique in the following ways − It does not restrict the developer from using plain PHP code in views. It does not restrict the developer from using plain PHP code in views. The blade views thus designed, are compiled and cached until they are modified. The blade views thus designed, are compiled and cached until they are modified. The complete directory structure of Laravel is shown in the screenshot given here. You can observe that all views are stored in the resources/views directory and the default view for Laravel framework is welcome.blade.php. Please note that other blade templates are also created similarly. You will have to use the following steps to create a blade template layout − Create a layout folder inside the resources/views folder. We are going to use this folder to store all layouts together. Create a layout folder inside the resources/views folder. We are going to use this folder to store all layouts together. Create a file name master.blade.php which will have the following code associated with it − Create a file name master.blade.php which will have the following code associated with it − <html> <head> <title>DemoLaravel - @yield('title')</title> </head> <body> @yield('content') </body> </html> In this step, you should extend the layout. Extending a layout involves defining the child elements. Laravel uses the Blade @extends directive for defining the child elements. When you are extending a layout, please note the following points − Views defined in the Blade Layout injects the container in a unique way. Views defined in the Blade Layout injects the container in a unique way. Various sections of view are created as child elements. Various sections of view are created as child elements. Child elements are stored in layouts folder as child.blade.php Child elements are stored in layouts folder as child.blade.php An example that shows extending the layout created above is shown here − @extends('layouts.app') @section('title', 'Page Title') @section('sidebar') @parent <p>This refers to the master sidebar.</p> @endsection @section('content') <p>This is my body content.</p> @endsection To implement the child elements in views, you should define the layout in the way it is needed. Observe the screenshot shown here. You can find that each of links mentioned in the landing page are hyperlinks. Please note that you can also create them as child elements with the help of blade templates by using the procedure given above. 13 Lectures 3 hours Sebastian Sulinski 35 Lectures 3.5 hours Antonio Papa 7 Lectures 1.5 hours Sebastian Sulinski 42 Lectures 1 hours Skillbakerystudios 165 Lectures 13 hours Paul Carlo Tordecilla 116 Lectures 13 hours Hafizullah Masoudi Print Add Notes Bookmark this page
[ { "code": null, "e": 2671, "s": 2472, "text": "Laravel 5.1 introduces the concept of using Blade, a templating engine to design a unique layout. The layout thus designed can be used by other views, and includes a consistent design and structure." }, { "code": null, "e": 2754, "s": 2671, "text": "When compared to other templating engines, Blade is unique in the following ways −" }, { "code": null, "e": 2825, "s": 2754, "text": "It does not restrict the developer from using plain PHP code in views." }, { "code": null, "e": 2896, "s": 2825, "text": "It does not restrict the developer from using plain PHP code in views." }, { "code": null, "e": 2976, "s": 2896, "text": "The blade views thus designed, are compiled and cached until they are modified." }, { "code": null, "e": 3056, "s": 2976, "text": "The blade views thus designed, are compiled and cached until they are modified." }, { "code": null, "e": 3139, "s": 3056, "text": "The complete directory structure of Laravel is shown in the screenshot given here." }, { "code": null, "e": 3279, "s": 3139, "text": "You can observe that all views are stored in the resources/views directory and the default view for Laravel framework is welcome.blade.php." }, { "code": null, "e": 3346, "s": 3279, "text": "Please note that other blade templates are also created similarly." }, { "code": null, "e": 3423, "s": 3346, "text": "You will have to use the following steps to create a blade template layout −" }, { "code": null, "e": 3544, "s": 3423, "text": "Create a layout folder inside the resources/views folder. We are going to use this folder to store all layouts together." }, { "code": null, "e": 3665, "s": 3544, "text": "Create a layout folder inside the resources/views folder. We are going to use this folder to store all layouts together." }, { "code": null, "e": 3757, "s": 3665, "text": "Create a file name master.blade.php which will have the following code associated with it −" }, { "code": null, "e": 3849, "s": 3757, "text": "Create a file name master.blade.php which will have the following code associated with it −" }, { "code": null, "e": 3981, "s": 3849, "text": "<html>\n <head>\n <title>DemoLaravel - @yield('title')</title>\n </head>\n <body>\n @yield('content')\n </body>\n</html>" }, { "code": null, "e": 4157, "s": 3981, "text": "In this step, you should extend the layout. Extending a layout involves defining the child elements. Laravel uses the Blade @extends directive for defining the child elements." }, { "code": null, "e": 4225, "s": 4157, "text": "When you are extending a layout, please note the following points −" }, { "code": null, "e": 4298, "s": 4225, "text": "Views defined in the Blade Layout injects the container in a unique way." }, { "code": null, "e": 4371, "s": 4298, "text": "Views defined in the Blade Layout injects the container in a unique way." }, { "code": null, "e": 4427, "s": 4371, "text": "Various sections of view are created as child elements." }, { "code": null, "e": 4483, "s": 4427, "text": "Various sections of view are created as child elements." }, { "code": null, "e": 4546, "s": 4483, "text": "Child elements are stored in layouts folder as child.blade.php" }, { "code": null, "e": 4609, "s": 4546, "text": "Child elements are stored in layouts folder as child.blade.php" }, { "code": null, "e": 4682, "s": 4609, "text": "An example that shows extending the layout created above is shown here −" }, { "code": null, "e": 4887, "s": 4682, "text": "@extends('layouts.app')\n@section('title', 'Page Title')\n@section('sidebar')\n @parent\n<p>This refers to the master sidebar.</p>\n@endsection\n@section('content')\n<p>This is my body content.</p>\n@endsection" }, { "code": null, "e": 4983, "s": 4887, "text": "To implement the child elements in views, you should define the layout in the way it is needed." }, { "code": null, "e": 5225, "s": 4983, "text": "Observe the screenshot shown here. You can find that each of links mentioned in the landing page are hyperlinks. Please note that you can also create them as child elements with the help of blade templates by using the procedure given above." }, { "code": null, "e": 5258, "s": 5225, "text": "\n 13 Lectures \n 3 hours \n" }, { "code": null, "e": 5278, "s": 5258, "text": " Sebastian Sulinski" }, { "code": null, "e": 5313, "s": 5278, "text": "\n 35 Lectures \n 3.5 hours \n" }, { "code": null, "e": 5327, "s": 5313, "text": " Antonio Papa" }, { "code": null, "e": 5361, "s": 5327, "text": "\n 7 Lectures \n 1.5 hours \n" }, { "code": null, "e": 5381, "s": 5361, "text": " Sebastian Sulinski" }, { "code": null, "e": 5414, "s": 5381, "text": "\n 42 Lectures \n 1 hours \n" }, { "code": null, "e": 5434, "s": 5414, "text": " Skillbakerystudios" }, { "code": null, "e": 5469, "s": 5434, "text": "\n 165 Lectures \n 13 hours \n" }, { "code": null, "e": 5492, "s": 5469, "text": " Paul Carlo Tordecilla" }, { "code": null, "e": 5527, "s": 5492, "text": "\n 116 Lectures \n 13 hours \n" }, { "code": null, "e": 5547, "s": 5527, "text": " Hafizullah Masoudi" }, { "code": null, "e": 5554, "s": 5547, "text": " Print" }, { "code": null, "e": 5565, "s": 5554, "text": " Add Notes" } ]
DayOfWeek getValue() method in Java with Examples - GeeksforGeeks
19 Mar, 2019 The getValue() method of java.time.DayOfWeek is an in-built function in Java which return the integer value assigned to the 7 days of the week, i.e, Monday, Tuesday, Wednesday, Thursday, Friday, Saturday and Sunday. The int value follows the ISO-8601 standard, from 1 (Monday) to 7 (Sunday). Method Declaration: public int getValue() Syntax: int val = DayOfWeekObject.getValue() Parameters: This method does not accepts any parameters. Return Value: The function returns int value of the day of the week, e.g, 1 for Monday, 2 for Tuesday and so on. Below program illustrate the above method:Program 1: // Java Program Demonstrate getValue()// method of DayOfWeekimport java.time.*;import java.time.DayOfWeek; class DayOfWeekExample { public static void main(String[] args) { // Set a local date whose day is found LocalDate localDate = LocalDate.of(1947, Month.AUGUST, 15); // Find the day from the local date DayOfWeek dayOfWeek = DayOfWeek.from(localDate); // Printing the day of the week // and its Int value System.out.println("Day of the Week on" + " 15th August 1947 - " + dayOfWeek.name()); int val = dayOfWeek.getValue(); System.out.println("Int Value of " + dayOfWeek.name() + " - " + val); }} Day of the Week on 15th August 1947 - FRIDAY Int Value of FRIDAY - 5 Program 2: // Java Program Demonstrate getValue()// method of DayOfWeekimport java.time.*;import java.time.DayOfWeek; class DayOfWeekExample { public static void main(String[] args) { // Set a local date whose day is found LocalDate localDate = LocalDate.of(2015, Month.JULY, 13); // Find the day from the local date DayOfWeek dayOfWeek = DayOfWeek.from(localDate); // Printing the day of the week // and its Int value System.out.println("Day of the Week on" + " 13th July 2015 - " + dayOfWeek.name()); int val = dayOfWeek.getValue(); System.out.println("Int Value of " + dayOfWeek.name() + " - " + val); }} Day of the Week on 13th July 2015 - MONDAY Int Value of MONDAY - 1 Reference: https://docs.oracle.com/javase/8/docs/api/java/time/DayOfWeek.html#getValue– Java - util package Java-DayOfWeek Java-Functions Java Java Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Initialize an ArrayList in Java Object Oriented Programming (OOPs) Concept in Java HashMap in Java with Examples Interfaces in Java How to iterate any Map in Java ArrayList in Java Multidimensional Arrays in Java Stream In Java Stack Class in Java Singleton Class in Java
[ { "code": null, "e": 24504, "s": 24476, "text": "\n19 Mar, 2019" }, { "code": null, "e": 24796, "s": 24504, "text": "The getValue() method of java.time.DayOfWeek is an in-built function in Java which return the integer value assigned to the 7 days of the week, i.e, Monday, Tuesday, Wednesday, Thursday, Friday, Saturday and Sunday. The int value follows the ISO-8601 standard, from 1 (Monday) to 7 (Sunday)." }, { "code": null, "e": 24816, "s": 24796, "text": "Method Declaration:" }, { "code": null, "e": 24839, "s": 24816, "text": "public int getValue()\n" }, { "code": null, "e": 24847, "s": 24839, "text": "Syntax:" }, { "code": null, "e": 24885, "s": 24847, "text": "int val = DayOfWeekObject.getValue()\n" }, { "code": null, "e": 24942, "s": 24885, "text": "Parameters: This method does not accepts any parameters." }, { "code": null, "e": 25055, "s": 24942, "text": "Return Value: The function returns int value of the day of the week, e.g, 1 for Monday, 2 for Tuesday and so on." }, { "code": null, "e": 25108, "s": 25055, "text": "Below program illustrate the above method:Program 1:" }, { "code": "// Java Program Demonstrate getValue()// method of DayOfWeekimport java.time.*;import java.time.DayOfWeek; class DayOfWeekExample { public static void main(String[] args) { // Set a local date whose day is found LocalDate localDate = LocalDate.of(1947, Month.AUGUST, 15); // Find the day from the local date DayOfWeek dayOfWeek = DayOfWeek.from(localDate); // Printing the day of the week // and its Int value System.out.println(\"Day of the Week on\" + \" 15th August 1947 - \" + dayOfWeek.name()); int val = dayOfWeek.getValue(); System.out.println(\"Int Value of \" + dayOfWeek.name() + \" - \" + val); }}", "e": 25942, "s": 25108, "text": null }, { "code": null, "e": 26012, "s": 25942, "text": "Day of the Week on 15th August 1947 - FRIDAY\nInt Value of FRIDAY - 5\n" }, { "code": null, "e": 26023, "s": 26012, "text": "Program 2:" }, { "code": "// Java Program Demonstrate getValue()// method of DayOfWeekimport java.time.*;import java.time.DayOfWeek; class DayOfWeekExample { public static void main(String[] args) { // Set a local date whose day is found LocalDate localDate = LocalDate.of(2015, Month.JULY, 13); // Find the day from the local date DayOfWeek dayOfWeek = DayOfWeek.from(localDate); // Printing the day of the week // and its Int value System.out.println(\"Day of the Week on\" + \" 13th July 2015 - \" + dayOfWeek.name()); int val = dayOfWeek.getValue(); System.out.println(\"Int Value of \" + dayOfWeek.name() + \" - \" + val); }}", "e": 26853, "s": 26023, "text": null }, { "code": null, "e": 26921, "s": 26853, "text": "Day of the Week on 13th July 2015 - MONDAY\nInt Value of MONDAY - 1\n" }, { "code": null, "e": 27009, "s": 26921, "text": "Reference: https://docs.oracle.com/javase/8/docs/api/java/time/DayOfWeek.html#getValue–" }, { "code": null, "e": 27029, "s": 27009, "text": "Java - util package" }, { "code": null, "e": 27044, "s": 27029, "text": "Java-DayOfWeek" }, { "code": null, "e": 27059, "s": 27044, "text": "Java-Functions" }, { "code": null, "e": 27064, "s": 27059, "text": "Java" }, { "code": null, "e": 27069, "s": 27064, "text": "Java" }, { "code": null, "e": 27167, "s": 27069, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 27199, "s": 27167, "text": "Initialize an ArrayList in Java" }, { "code": null, "e": 27250, "s": 27199, "text": "Object Oriented Programming (OOPs) Concept in Java" }, { "code": null, "e": 27280, "s": 27250, "text": "HashMap in Java with Examples" }, { "code": null, "e": 27299, "s": 27280, "text": "Interfaces in Java" }, { "code": null, "e": 27330, "s": 27299, "text": "How to iterate any Map in Java" }, { "code": null, "e": 27348, "s": 27330, "text": "ArrayList in Java" }, { "code": null, "e": 27380, "s": 27348, "text": "Multidimensional Arrays in Java" }, { "code": null, "e": 27395, "s": 27380, "text": "Stream In Java" }, { "code": null, "e": 27415, "s": 27395, "text": "Stack Class in Java" } ]
DSA using Java - Circular Linked List
Circular Linked List is a variation of Linked list in which first element points to last element and last element points to first element. Both Singly Linked List and Doubly Linked List can be made into as circular linked list As per above shown illustrations, following are the important points to be considered. Last Link'next points to first link of the list in both cases of singly as well as doubly linked list. Last Link'next points to first link of the list in both cases of singly as well as doubly linked list. First Link's prev points to the last of the list in case of doubly linked list. First Link's prev points to the last of the list in case of doubly linked list. Following are the important operations supported by a circular list. insert − insert an element in the start of the list. insert − insert an element in the start of the list. delete − insert an element from the start of the list. delete − insert an element from the start of the list. display − display the list. display − display the list. Following code demonstrate insertion operation at in a circular linked list based on single linked list. //insert link at the first location public void insertFirst(int key, int data){ //create a link Link link = new Link(key,data); if (isEmpty()) { first = link; first.next = first; } else{ //point it to old first node link.next = first; //point first to new first node first = link; } } Following code demonstrate deletion operation at in a circular linked list based on single linked list. //delete link at the first location public Link deleteFirst(){ //save reference to first link Link tempLink = first; //if only one link if(first.next == null){ last = null; }else { first.next.prev = null; } first = first.next; //return the deleted link return tempLink; } Following code demonstrate display list operation in a circular linked list. public void display(){ //start from the beginning Link current = first; //navigate till the end of the list System.out.print("[ "); if(first != null){ while(current.next != current){ //print data current.display(); //move to next item current = current.next; System.out.print(" "); } } System.out.print(" ]"); } Link.java package com.tutorialspoint.list; public class CircularLinkedList { //this link always point to first Link private Link first; // create an empty linked list public CircularLinkedList(){ first = null; } public boolean isEmpty(){ return first == null; } public int length(){ int length = 0; //if list is empty if(first == null){ return 0; } Link current = first.next; while(current != first){ length++; current = current.next; } return length; } //insert link at the first location public void insertFirst(int key, int data){ //create a link Link link = new Link(key,data); if (isEmpty()) { first = link; first.next = first; } else{ //point it to old first node link.next = first; //point first to new first node first = link; } } //delete first item public Link deleteFirst(){ //save reference to first link Link tempLink = first; if(first.next == first){ first = null; return tempLink; } //mark next to first link as first first = first.next; //return the deleted link return tempLink; } public void display(){ //start from the beginning Link current = first; //navigate till the end of the list System.out.print("[ "); if(first != null){ while(current.next != current){ //print data current.display(); //move to next item current = current.next; System.out.print(" "); } } System.out.print(" ]"); } } DoublyLinkedListDemo.java package com.tutorialspoint.list; public class CircularLinkedListDemo { public static void main(String args[]){ CircularLinkedList list = new CircularLinkedList(); list.insertFirst(1, 10); list.insertFirst(2, 20); list.insertFirst(3, 30); list.insertFirst(4, 1); list.insertFirst(5, 40); list.insertFirst(6, 56); System.out.print("\nOriginal List: "); list.display(); System.out.println(""); while(!list.isEmpty()){ Link temp = list.deleteFirst(); System.out.print("Deleted value:"); temp.display(); System.out.println(""); } System.out.print("List after deleting all items: "); list.display(); System.out.println(""); } } If we compile and run the above program then it would produce following result − Original List: [ {6,56} {5,40} {4,1} {3,30} {2,20} ] Deleted value:{6,56} Deleted value:{5,40} Deleted value:{4,1} Deleted value:{3,30} Deleted value:{2,20} Deleted value:{1,10} List after deleting all items: [ ] Print Add Notes Bookmark this page
[ { "code": null, "e": 2395, "s": 2168, "text": "Circular Linked List is a variation of Linked list in which first element points to last element and last element points to first element. Both Singly Linked List and Doubly Linked List can be made into as circular linked list" }, { "code": null, "e": 2482, "s": 2395, "text": "As per above shown illustrations, following are the important points to be considered." }, { "code": null, "e": 2585, "s": 2482, "text": "Last Link'next points to first link of the list in both cases of singly as well as doubly linked list." }, { "code": null, "e": 2688, "s": 2585, "text": "Last Link'next points to first link of the list in both cases of singly as well as doubly linked list." }, { "code": null, "e": 2768, "s": 2688, "text": "First Link's prev points to the last of the list in case of doubly linked list." }, { "code": null, "e": 2848, "s": 2768, "text": "First Link's prev points to the last of the list in case of doubly linked list." }, { "code": null, "e": 2917, "s": 2848, "text": "Following are the important operations supported by a circular list." }, { "code": null, "e": 2970, "s": 2917, "text": "insert − insert an element in the start of the list." }, { "code": null, "e": 3023, "s": 2970, "text": "insert − insert an element in the start of the list." }, { "code": null, "e": 3078, "s": 3023, "text": "delete − insert an element from the start of the list." }, { "code": null, "e": 3133, "s": 3078, "text": "delete − insert an element from the start of the list." }, { "code": null, "e": 3161, "s": 3133, "text": "display − display the list." }, { "code": null, "e": 3189, "s": 3161, "text": "display − display the list." }, { "code": null, "e": 3294, "s": 3189, "text": "Following code demonstrate insertion operation at in a circular linked list based on single linked list." }, { "code": null, "e": 3646, "s": 3294, "text": "//insert link at the first location\npublic void insertFirst(int key, int data){\n //create a link\n Link link = new Link(key,data);\n if (isEmpty()) {\n first = link;\n first.next = first;\n } \n else{\n //point it to old first node\n link.next = first;\n //point first to new first node\n first = link;\n } \n}" }, { "code": null, "e": 3750, "s": 3646, "text": "Following code demonstrate deletion operation at in a circular linked list based on single linked list." }, { "code": null, "e": 4061, "s": 3750, "text": "//delete link at the first location\npublic Link deleteFirst(){\n //save reference to first link\n Link tempLink = first;\n //if only one link\n if(first.next == null){\n last = null;\n }else {\n first.next.prev = null;\n }\n first = first.next;\n //return the deleted link\n return tempLink;\n}" }, { "code": null, "e": 4138, "s": 4061, "text": "Following code demonstrate display list operation in a circular linked list." }, { "code": null, "e": 4530, "s": 4138, "text": "public void display(){ \n //start from the beginning\n Link current = first;\n //navigate till the end of the list\n System.out.print(\"[ \");\n if(first != null){\n while(current.next != current){\n //print data\n current.display();\n //move to next item\n current = current.next;\n System.out.print(\" \");\n }\n }\n System.out.print(\" ]\");\n}" }, { "code": null, "e": 4540, "s": 4530, "text": "Link.java" }, { "code": null, "e": 6301, "s": 4540, "text": "package com.tutorialspoint.list;\n \npublic class CircularLinkedList {\n //this link always point to first Link \n private Link first;\n\n // create an empty linked list \n public CircularLinkedList(){\n first = null; \n }\n\n public boolean isEmpty(){\n return first == null;\n }\n\n public int length(){\n int length = 0;\n\n //if list is empty\n if(first == null){\n return 0;\n }\n\n Link current = first.next;\n\n while(current != first){\n length++;\n current = current.next; \n }\n return length;\n }\n\n //insert link at the first location\n public void insertFirst(int key, int data){\n //create a link\n Link link = new Link(key,data);\n if (isEmpty()) {\n first = link;\n first.next = first;\n } \n else{\n //point it to old first node\n link.next = first;\n //point first to new first node\n first = link;\n } \n }\n\n //delete first item\n public Link deleteFirst(){\n //save reference to first link\n Link tempLink = first;\n if(first.next == first){ \n first = null;\n return tempLink;\n } \n\n //mark next to first link as first \n first = first.next;\n //return the deleted link\n return tempLink;\n }\n\n public void display(){\n\n //start from the beginning\n Link current = first;\n //navigate till the end of the list\n System.out.print(\"[ \");\n if(first != null){\n while(current.next != current){\n //print data\n current.display();\n //move to next item\n current = current.next;\n System.out.print(\" \");\n }\n }\n System.out.print(\" ]\");\n } \n}" }, { "code": null, "e": 6327, "s": 6301, "text": "DoublyLinkedListDemo.java" }, { "code": null, "e": 7121, "s": 6327, "text": "package com.tutorialspoint.list;\n\npublic class CircularLinkedListDemo {\n public static void main(String args[]){\n CircularLinkedList list = new CircularLinkedList();\n\n list.insertFirst(1, 10);\n list.insertFirst(2, 20);\n list.insertFirst(3, 30);\n list.insertFirst(4, 1);\n list.insertFirst(5, 40);\n list.insertFirst(6, 56);\n\n System.out.print(\"\\nOriginal List: \"); \n list.display();\n System.out.println(\"\"); \n while(!list.isEmpty()){ \n Link temp = list.deleteFirst();\n System.out.print(\"Deleted value:\"); \n temp.display();\n System.out.println(\"\");\n } \n System.out.print(\"List after deleting all items: \"); \n list.display();\n System.out.println(\"\");\n }\n}" }, { "code": null, "e": 7202, "s": 7121, "text": "If we compile and run the above program then it would produce following result −" }, { "code": null, "e": 7418, "s": 7202, "text": "Original List: [ {6,56} {5,40} {4,1} {3,30} {2,20} ]\nDeleted value:{6,56}\nDeleted value:{5,40}\nDeleted value:{4,1}\nDeleted value:{3,30}\nDeleted value:{2,20}\nDeleted value:{1,10}\nList after deleting all items: [ ]\n" }, { "code": null, "e": 7425, "s": 7418, "text": " Print" }, { "code": null, "e": 7436, "s": 7425, "text": " Add Notes" } ]
How to Benefit from the Semi-Supervised Learning with Label Spreading Algorithm | by Saul Dobilas | Towards Data Science
This is a second article covering Semi-Supervised Learning, where I explore ways of using labeled and unlabeled data together to build better models. This time I focus on the Label Spreading algorithm, which attempts to construct a smooth classifying function based on the intrinsic structure revealed by known labeled and unlabeled points. While similar to Label Propagation, Label Spreading does a few things differently, which will be explored later in the article. The place of Label Spreading within the universe of Machine Learning algorithms Main differences between Label Spreading and Label Propagation A brief explanation of how Label Spreading works How to use Label Spreading in Python? Sometimes we find ourselves having a mix of labeled data (perfect for supervised learning like classification or regression) and unlabeled data (perfect for unsupervised learning like clustering or dimensionality reduction). However, to get the best results, it is often beneficial to combine these two sets of data. Such a situation is an excellent example of where we would want to use a Semi-Supervised Learning approach, with the Label Spreading algorithm being one of our options. The below interactive sunburst chart shows the categorization of different ML algorithms. Make sure to click👇 on various categories to enlarge and reveal more. If you enjoy Data Science and Machine Learning, please subscribe to get an email whenever I publish a new story. If you are already familiar with the Label Propagation algorithm, you may want to know about the two ways that Label Spreading differs from it. If you are not familiar with Label Propagation, then feel free to skip to the next section. The Label Spreading algorithm uses symmetric normalized graph Laplacian matrix in its calculations, while Label Propagation employs a random walk normalized Laplacian. However, note that the two matrices are similar and that one can be derived from the other. Hence, from the perspective of this article, it is not crucial for us to understand the nuances of these two matrices. Label Propagation uses hard clamping, which means that the labels of the originally labeled points never change. Meanwhile, Label Spreading adopts soft clamping controlled through a hyperparameter α (alpha), which specifies the relative amount of information the point obtains from its neighbors vs. its initial label information. Four steps describe how the Label Spreading algorithm operates. 1. Define a pairwise relationship between points, called affinity matrix W. The matrix is created with the help of a Radial Basis Function kernel (a.k.a. RBF kernel), which is used to determine edge weights. Note that matrix W contains 0’s in the diagonal since no edge connects a point to itself. Note, sklrean's implementation of RBF kernel looks slightly different as it replaces 1/2sigma^2 with a hyperparameter gamma. The effect is the same as it allows you to control the smoothness of the function. High gamma extends the influence of each individual point wide, hence creating a smooth transition in label probabilities. Meanwhile, low gamma leads to only the closest neighbors having influence over the label probabilities. And here is what the affinity matrix looks like: 2. Create a symmetric normalized graph Laplacian matrix. This step takes affinity matrix W and normalizes it symmetrically, which helps with the convergence in step 3. 3. The third step is iterative, which uses matrix multiplication to spread information from labeled points to unlabeled points. Each point receives the information from its neighbors (first term) and also retains its initial information (second term). The parameter α (alpha) enables soft clamping by controlling the proportion of information received from neighbors vs. the initial label. Alpha close to 0 keeps all the initial label information (equivalent to hard clamping), while alpha close to 1 allows most of the initial label information to be replaced. Note that F(0)=Y, so the iterative process starts with the initial label information. 4. After the process in step 3 converges or reaches the specified maximum number of iterations, we arrive at the final step of assigning the labels. Matrix F contains label vectors, representing the probabilities of each point belonging to a specific class (i.e., having a particular label). The final label is then chosen using argmax operation, meaning that the algorithm assigns the label with the highest probability. It is finally time to use Label Spreading on real data. Note, for this example, we have chosen marketing campaign data that have labels available, which will help us to evaluate the performance of our semi-supervised model. Of course, before we fit the model, we will mask most of the labels to simulate a scenario of mainly having unlabeled data. We will use the following data and libraries: Marketing campaign data from Kaggle Scikit-learn library for1) feature scaling (MinMaxScaler);2) performing Label Spreading (LabelSpreading);3) model evaluation (classification_report, confusion_matrix, ConfusionMatrixDisplay) Plotly and Matplotlib for data visualizations Pandas for data manipulation The first step is to import the libraries that we have listed above. Next, we download and ingest marketing campaign data (source: Kaggle). This time we will use only two features to spread the labels. Hence, I have limited the ingestion to a few key columns instead of reading in the entire table. Also, you will see that we have derived a few additional fields required for creating a target variable with masked labels. The below snippet shows the data and the distribution of a target variable. Note, we have kept 2% of the actual labels (1’s and 0’s) and masked the remainder 98% (-1’s). Hence, our target contains information on whether the shopper has any dependents (1), does not have any dependents (0), or this information is masked (-1). We are being ambitious here as we aim to assign labels to 2,195 data points by using only 45 known labels. The features that we use are MntMeatProducts (shopper’s annual spend on meat products) MntWines (shopper’s annual spend on wine). Now, let’s see what the data looks like when we plot it on a graph. The next piece of code consists of a few steps that help us prepare the data, fit the model and print the results. And here are the results: As you can see, despite being very ambitious, we have achieved a pretty good result with a model accuracy of 82% (to make the assessment fair, we only used records with masked labels for model performance evaluation). Let’s plot a 2D graph again to see how the newly assigned labels are distributed. We can see a clear separation of blue points (no dependents) and red points (with dependents) with a decision boundary located at around 400 spent on meat and ~1,000 spent on wine. So, according to this data, it looks like people without kids tend to eat more meat and drink more wine. Label Spreading is an excellent algorithm when you have only a small number of labeled examples and want to apply auto-labeling on a large amount of unlabeled data. However, as with all Semi-Supervised Learning techniques, you need to approach it with caution. It is always worth evaluating the model by creating a test sample with known labels or manually checking a sub-sample of Label Spreading results. I hope you enjoyed reading this article, and I encourage you to try out Semi-Supervised Learning in your next Data Science project! Please do not hesitate to reach out if you have any questions or suggestions. Cheers 👏Saul Dobilas If you have already spent your learning budget for this month, please remember me next time. My personalized link to join Medium is: solclover.com Other articles you may find interesting:
[ { "code": null, "e": 322, "s": 172, "text": "This is a second article covering Semi-Supervised Learning, where I explore ways of using labeled and unlabeled data together to build better models." }, { "code": null, "e": 513, "s": 322, "text": "This time I focus on the Label Spreading algorithm, which attempts to construct a smooth classifying function based on the intrinsic structure revealed by known labeled and unlabeled points." }, { "code": null, "e": 641, "s": 513, "text": "While similar to Label Propagation, Label Spreading does a few things differently, which will be explored later in the article." }, { "code": null, "e": 721, "s": 641, "text": "The place of Label Spreading within the universe of Machine Learning algorithms" }, { "code": null, "e": 784, "s": 721, "text": "Main differences between Label Spreading and Label Propagation" }, { "code": null, "e": 833, "s": 784, "text": "A brief explanation of how Label Spreading works" }, { "code": null, "e": 871, "s": 833, "text": "How to use Label Spreading in Python?" }, { "code": null, "e": 1096, "s": 871, "text": "Sometimes we find ourselves having a mix of labeled data (perfect for supervised learning like classification or regression) and unlabeled data (perfect for unsupervised learning like clustering or dimensionality reduction)." }, { "code": null, "e": 1357, "s": 1096, "text": "However, to get the best results, it is often beneficial to combine these two sets of data. Such a situation is an excellent example of where we would want to use a Semi-Supervised Learning approach, with the Label Spreading algorithm being one of our options." }, { "code": null, "e": 1517, "s": 1357, "text": "The below interactive sunburst chart shows the categorization of different ML algorithms. Make sure to click👇 on various categories to enlarge and reveal more." }, { "code": null, "e": 1630, "s": 1517, "text": "If you enjoy Data Science and Machine Learning, please subscribe to get an email whenever I publish a new story." }, { "code": null, "e": 1866, "s": 1630, "text": "If you are already familiar with the Label Propagation algorithm, you may want to know about the two ways that Label Spreading differs from it. If you are not familiar with Label Propagation, then feel free to skip to the next section." }, { "code": null, "e": 2034, "s": 1866, "text": "The Label Spreading algorithm uses symmetric normalized graph Laplacian matrix in its calculations, while Label Propagation employs a random walk normalized Laplacian." }, { "code": null, "e": 2245, "s": 2034, "text": "However, note that the two matrices are similar and that one can be derived from the other. Hence, from the perspective of this article, it is not crucial for us to understand the nuances of these two matrices." }, { "code": null, "e": 2358, "s": 2245, "text": "Label Propagation uses hard clamping, which means that the labels of the originally labeled points never change." }, { "code": null, "e": 2576, "s": 2358, "text": "Meanwhile, Label Spreading adopts soft clamping controlled through a hyperparameter α (alpha), which specifies the relative amount of information the point obtains from its neighbors vs. its initial label information." }, { "code": null, "e": 2640, "s": 2576, "text": "Four steps describe how the Label Spreading algorithm operates." }, { "code": null, "e": 2938, "s": 2640, "text": "1. Define a pairwise relationship between points, called affinity matrix W. The matrix is created with the help of a Radial Basis Function kernel (a.k.a. RBF kernel), which is used to determine edge weights. Note that matrix W contains 0’s in the diagonal since no edge connects a point to itself." }, { "code": null, "e": 3374, "s": 2938, "text": "Note, sklrean's implementation of RBF kernel looks slightly different as it replaces 1/2sigma^2 with a hyperparameter gamma. The effect is the same as it allows you to control the smoothness of the function. High gamma extends the influence of each individual point wide, hence creating a smooth transition in label probabilities. Meanwhile, low gamma leads to only the closest neighbors having influence over the label probabilities. " }, { "code": null, "e": 3423, "s": 3374, "text": "And here is what the affinity matrix looks like:" }, { "code": null, "e": 3591, "s": 3423, "text": "2. Create a symmetric normalized graph Laplacian matrix. This step takes affinity matrix W and normalizes it symmetrically, which helps with the convergence in step 3." }, { "code": null, "e": 3719, "s": 3591, "text": "3. The third step is iterative, which uses matrix multiplication to spread information from labeled points to unlabeled points." }, { "code": null, "e": 4153, "s": 3719, "text": "Each point receives the information from its neighbors (first term) and also retains its initial information (second term). The parameter α (alpha) enables soft clamping by controlling the proportion of information received from neighbors vs. the initial label. Alpha close to 0 keeps all the initial label information (equivalent to hard clamping), while alpha close to 1 allows most of the initial label information to be replaced." }, { "code": null, "e": 4239, "s": 4153, "text": "Note that F(0)=Y, so the iterative process starts with the initial label information." }, { "code": null, "e": 4388, "s": 4239, "text": "4. After the process in step 3 converges or reaches the specified maximum number of iterations, we arrive at the final step of assigning the labels." }, { "code": null, "e": 4661, "s": 4388, "text": "Matrix F contains label vectors, representing the probabilities of each point belonging to a specific class (i.e., having a particular label). The final label is then chosen using argmax operation, meaning that the algorithm assigns the label with the highest probability." }, { "code": null, "e": 4717, "s": 4661, "text": "It is finally time to use Label Spreading on real data." }, { "code": null, "e": 4885, "s": 4717, "text": "Note, for this example, we have chosen marketing campaign data that have labels available, which will help us to evaluate the performance of our semi-supervised model." }, { "code": null, "e": 5009, "s": 4885, "text": "Of course, before we fit the model, we will mask most of the labels to simulate a scenario of mainly having unlabeled data." }, { "code": null, "e": 5055, "s": 5009, "text": "We will use the following data and libraries:" }, { "code": null, "e": 5091, "s": 5055, "text": "Marketing campaign data from Kaggle" }, { "code": null, "e": 5282, "s": 5091, "text": "Scikit-learn library for1) feature scaling (MinMaxScaler);2) performing Label Spreading (LabelSpreading);3) model evaluation (classification_report, confusion_matrix, ConfusionMatrixDisplay)" }, { "code": null, "e": 5328, "s": 5282, "text": "Plotly and Matplotlib for data visualizations" }, { "code": null, "e": 5357, "s": 5328, "text": "Pandas for data manipulation" }, { "code": null, "e": 5426, "s": 5357, "text": "The first step is to import the libraries that we have listed above." }, { "code": null, "e": 5656, "s": 5426, "text": "Next, we download and ingest marketing campaign data (source: Kaggle). This time we will use only two features to spread the labels. Hence, I have limited the ingestion to a few key columns instead of reading in the entire table." }, { "code": null, "e": 5780, "s": 5656, "text": "Also, you will see that we have derived a few additional fields required for creating a target variable with masked labels." }, { "code": null, "e": 5856, "s": 5780, "text": "The below snippet shows the data and the distribution of a target variable." }, { "code": null, "e": 6106, "s": 5856, "text": "Note, we have kept 2% of the actual labels (1’s and 0’s) and masked the remainder 98% (-1’s). Hence, our target contains information on whether the shopper has any dependents (1), does not have any dependents (0), or this information is masked (-1)." }, { "code": null, "e": 6213, "s": 6106, "text": "We are being ambitious here as we aim to assign labels to 2,195 data points by using only 45 known labels." }, { "code": null, "e": 6411, "s": 6213, "text": "The features that we use are MntMeatProducts (shopper’s annual spend on meat products) MntWines (shopper’s annual spend on wine). Now, let’s see what the data looks like when we plot it on a graph." }, { "code": null, "e": 6526, "s": 6411, "text": "The next piece of code consists of a few steps that help us prepare the data, fit the model and print the results." }, { "code": null, "e": 6552, "s": 6526, "text": "And here are the results:" }, { "code": null, "e": 6770, "s": 6552, "text": "As you can see, despite being very ambitious, we have achieved a pretty good result with a model accuracy of 82% (to make the assessment fair, we only used records with masked labels for model performance evaluation)." }, { "code": null, "e": 6852, "s": 6770, "text": "Let’s plot a 2D graph again to see how the newly assigned labels are distributed." }, { "code": null, "e": 7138, "s": 6852, "text": "We can see a clear separation of blue points (no dependents) and red points (with dependents) with a decision boundary located at around 400 spent on meat and ~1,000 spent on wine. So, according to this data, it looks like people without kids tend to eat more meat and drink more wine." }, { "code": null, "e": 7303, "s": 7138, "text": "Label Spreading is an excellent algorithm when you have only a small number of labeled examples and want to apply auto-labeling on a large amount of unlabeled data." }, { "code": null, "e": 7545, "s": 7303, "text": "However, as with all Semi-Supervised Learning techniques, you need to approach it with caution. It is always worth evaluating the model by creating a test sample with known labels or manually checking a sub-sample of Label Spreading results." }, { "code": null, "e": 7755, "s": 7545, "text": "I hope you enjoyed reading this article, and I encourage you to try out Semi-Supervised Learning in your next Data Science project! Please do not hesitate to reach out if you have any questions or suggestions." }, { "code": null, "e": 7776, "s": 7755, "text": "Cheers 👏Saul Dobilas" }, { "code": null, "e": 7909, "s": 7776, "text": "If you have already spent your learning budget for this month, please remember me next time. My personalized link to join Medium is:" }, { "code": null, "e": 7923, "s": 7909, "text": "solclover.com" } ]
Minimum Group Flips to Make Binary Array Elements Same - GeeksforGeeks
24 May, 2021 Given a binary array, we need to convert this array into an array that either contains all 1s or all 0s. We need to do it using the minimum number of group flips. Examples : Input : arr[] = {1, 1, 0, 0, 0, 1}Output : From 2 to 4Explanation : We have two choices, we make all 0s or do all 1s. We need to do two group flips to make all elements 0 and one group flip to make all elements 1. Since making all elements 1 takes least group flips, we do this.Input : arr[] = {1, 0, 0, 0, 1, 0, 0, 1, 0, 1}Output : From 1 to 3From 5 to 6From 8 to 8Input : arr[] = {0, 0, 0}Output : Explanation : Output is empty, we need not to make any changeInput : arr[] = {1, 1, 1}Output : Explanation : Output is empty, we need not to make any changeInput : arr[] = {0, 1}Output : From 0 to 0 ORFrom 1 to 1Explanation : Here number of flips are same either we make all elements as 1 or all elements as 0. A Naive Solution is to traverse do two traversals of the array. We first traverse to find the number of groups of 0s and the number of groups of 1. We find the minimum of these two. Then we traverse the array and flip the 1s if groups of 1s are less. Otherwise, we flip 0s. How to do it with one traversal of array? An Efficient Solution is based on the below facts : There are only two types of groups (groups of 0s and groups of 1s) Either the counts of both groups are same or the difference between counts is at most 1. For example, in {1, 1, 0, 1, 0, 0} there are two groups of 0s and two groups of 1s. In example, {1, 1, 0, 0, 0, 1, 0, 0, 1, 1}, count of groups of 1 is one more than the counts of 0s. Based on the above facts, we can conclude that if we always flip the second group and other groups that of the same type as the second group, we always get the correct answer. In the first case, when group counts are the same, it does not matter which group type we flip as both will lead to the correct answer. In the second case, when there is one extra, by ignoring the first group and starting from the second group, we convert this case to first case (for subarray beginning from the second group) and get the correct answer. C++ Java Python3 C# Javascript // C++ program to find the minimum// group flips in a binary array#include <iostream>using namespace std; void printGroups(bool arr[], int n) { // Traverse through all array elements // starting from the second element for (int i = 1; i < n; i++) { // If current element is not same // as previous if (arr[i] != arr[i - 1]) { // If it is same as first element // then it is starting of the interval // to be flipped. if (arr[i] != arr[0]) cout << "From " << i << " to "; // If it is not same as previous // and same as first element, then // previous element is end of interval else cout << (i - 1) << endl; } } // Explicitly handling the end of // last interval if (arr[n - 1] != arr[0]) cout << (n - 1) << endl;} int main() { bool arr[] = {0, 1, 1, 0, 0, 0, 1, 1}; int n = sizeof(arr) / sizeof(arr[0]); printGroups(arr, n); return 0;} // Java program to find the minimum// group flips in a binary arrayimport java.io.*;import java.util.*; class GFG { static void printGroups(int arr[], int n){ // Traverse through all array elements // starting from the second element for(int i = 1; i < n; i++) { // If current element is not same // as previous if (arr[i] != arr[i - 1]) { // If it is same as first element // then it is starting of the interval // to be flipped. if (arr[i] != arr[0]) System.out.print("From " + i + " to "); // If it is not same as previous // and same as first element, then // previous element is end of interval else System.out.println(i - 1); } } // Explicitly handling the end of // last interval if (arr[n - 1] != arr[0]) System.out.println(n - 1);} // Driver codepublic static void main(String[] args){ int arr[] = {0, 1, 1, 0, 0, 0, 1, 1}; int n = arr.length; printGroups(arr, n);}} // This code is contributed by coder001 # Python3 program to find the minimum# group flips in a binary array def printGroups(arr, n): # Traverse through all array elements # starting from the second element for i in range(1, n): # If current element is not same # as previous if (arr[i] != arr[i - 1]): # If it is same as first element # then it is starting of the interval # to be flipped. if (arr[i] != arr[0]): print("From", i, "to ", end = "") # If it is not same as previous # and same as the first element, then # previous element is end of interval else: print(i - 1) # Explicitly handling the end of # last interval if (arr[n - 1] != arr[0]): print(n - 1) # Driver Codeif __name__ == '__main__': arr = [ 0, 1, 1, 0, 0, 0, 1, 1 ] n = len(arr) printGroups(arr, n) # This code is contributed by Bhupendra_Singh // C# program to find the minimum// group flips in a binary arrayusing System; class GFG{ static void printGroups(int []arr, int n){ // Traverse through all array elements // starting from the second element for(int i = 1; i < n; i++) { // If current element is not same // as previous if (arr[i] != arr[i - 1]) { // If it is same as first element // then it is starting of the interval // to be flipped. if (arr[i] != arr[0]) Console.Write("From " + i + " to "); // If it is not same as previous // and same as first element, then // previous element is end of interval else Console.WriteLine(i - 1); } } // Explicitly handling the end // of last interval if (arr[n - 1] != arr[0]) Console.WriteLine(n - 1);} // Driver codepublic static void Main(String[] args){ int []arr = { 0, 1, 1, 0, 0, 0, 1, 1 }; int n = arr.Length; printGroups(arr, n);}} // This code is contributed by amal kumar choubey <script> // JavaScript program to find the minimum// group flips in a binary array function printGroups(arr, n) { // Traverse through all array elements // starting from the second element for (var i = 1; i < n; i++) { // If current element is not same // as previous if (arr[i] != arr[i - 1]) { // If it is same as first element // then it is starting of the interval // to be flipped. if (arr[i] != arr[0]) document.write( "From " + i + " to "); // If it is not same as previous // and same as first element, then // previous element is end of interval else document.write(i - 1 + "<br>"); } } // Explicitly handling the end of // last interval if (arr[n - 1] != arr[0]) document.write(n - 1 + "<br>");} var arr = [0, 1, 1, 0, 0, 0, 1, 1];var n = arr.length;printGroups(arr, n); </script> From 1 to 2 From 6 to 7 Time Complexity: O(n)Auxiliary Space: O(1) bgangwar59 coder001 Amal Kumar Choubey itsok array-traversal-question binary-string Arrays Arrays Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments Stack Data Structure (Introduction and Program) Top 50 Array Coding Problems for Interviews Introduction to Arrays Multidimensional Arrays in Java Linear Search Given an array A[] and a number x, check for pair in A[] with sum as x (aka Two Sum) Linked List vs Array Python | Using 2D arrays/lists the right way Given an array of size n and a number k, find all elements that appear more than n/k times Maximum and minimum of an array using minimum number of comparisons
[ { "code": null, "e": 24677, "s": 24649, "text": "\n24 May, 2021" }, { "code": null, "e": 24842, "s": 24677, "text": "Given a binary array, we need to convert this array into an array that either contains all 1s or all 0s. We need to do it using the minimum number of group flips. " }, { "code": null, "e": 24854, "s": 24842, "text": "Examples : " }, { "code": null, "e": 25576, "s": 24854, "text": "Input : arr[] = {1, 1, 0, 0, 0, 1}Output : From 2 to 4Explanation : We have two choices, we make all 0s or do all 1s. We need to do two group flips to make all elements 0 and one group flip to make all elements 1. Since making all elements 1 takes least group flips, we do this.Input : arr[] = {1, 0, 0, 0, 1, 0, 0, 1, 0, 1}Output : From 1 to 3From 5 to 6From 8 to 8Input : arr[] = {0, 0, 0}Output : Explanation : Output is empty, we need not to make any changeInput : arr[] = {1, 1, 1}Output : Explanation : Output is empty, we need not to make any changeInput : arr[] = {0, 1}Output : From 0 to 0 ORFrom 1 to 1Explanation : Here number of flips are same either we make all elements as 1 or all elements as 0. " }, { "code": null, "e": 25852, "s": 25576, "text": "A Naive Solution is to traverse do two traversals of the array. We first traverse to find the number of groups of 0s and the number of groups of 1. We find the minimum of these two. Then we traverse the array and flip the 1s if groups of 1s are less. Otherwise, we flip 0s." }, { "code": null, "e": 25894, "s": 25852, "text": "How to do it with one traversal of array?" }, { "code": null, "e": 25947, "s": 25894, "text": "An Efficient Solution is based on the below facts : " }, { "code": null, "e": 26014, "s": 25947, "text": "There are only two types of groups (groups of 0s and groups of 1s)" }, { "code": null, "e": 26288, "s": 26014, "text": "Either the counts of both groups are same or the difference between counts is at most 1. For example, in {1, 1, 0, 1, 0, 0} there are two groups of 0s and two groups of 1s. In example, {1, 1, 0, 0, 0, 1, 0, 0, 1, 1}, count of groups of 1 is one more than the counts of 0s." }, { "code": null, "e": 26821, "s": 26288, "text": "Based on the above facts, we can conclude that if we always flip the second group and other groups that of the same type as the second group, we always get the correct answer. In the first case, when group counts are the same, it does not matter which group type we flip as both will lead to the correct answer. In the second case, when there is one extra, by ignoring the first group and starting from the second group, we convert this case to first case (for subarray beginning from the second group) and get the correct answer." }, { "code": null, "e": 26825, "s": 26821, "text": "C++" }, { "code": null, "e": 26830, "s": 26825, "text": "Java" }, { "code": null, "e": 26838, "s": 26830, "text": "Python3" }, { "code": null, "e": 26841, "s": 26838, "text": "C#" }, { "code": null, "e": 26852, "s": 26841, "text": "Javascript" }, { "code": "// C++ program to find the minimum// group flips in a binary array#include <iostream>using namespace std; void printGroups(bool arr[], int n) { // Traverse through all array elements // starting from the second element for (int i = 1; i < n; i++) { // If current element is not same // as previous if (arr[i] != arr[i - 1]) { // If it is same as first element // then it is starting of the interval // to be flipped. if (arr[i] != arr[0]) cout << \"From \" << i << \" to \"; // If it is not same as previous // and same as first element, then // previous element is end of interval else cout << (i - 1) << endl; } } // Explicitly handling the end of // last interval if (arr[n - 1] != arr[0]) cout << (n - 1) << endl;} int main() { bool arr[] = {0, 1, 1, 0, 0, 0, 1, 1}; int n = sizeof(arr) / sizeof(arr[0]); printGroups(arr, n); return 0;}", "e": 27786, "s": 26852, "text": null }, { "code": "// Java program to find the minimum// group flips in a binary arrayimport java.io.*;import java.util.*; class GFG { static void printGroups(int arr[], int n){ // Traverse through all array elements // starting from the second element for(int i = 1; i < n; i++) { // If current element is not same // as previous if (arr[i] != arr[i - 1]) { // If it is same as first element // then it is starting of the interval // to be flipped. if (arr[i] != arr[0]) System.out.print(\"From \" + i + \" to \"); // If it is not same as previous // and same as first element, then // previous element is end of interval else System.out.println(i - 1); } } // Explicitly handling the end of // last interval if (arr[n - 1] != arr[0]) System.out.println(n - 1);} // Driver codepublic static void main(String[] args){ int arr[] = {0, 1, 1, 0, 0, 0, 1, 1}; int n = arr.length; printGroups(arr, n);}} // This code is contributed by coder001", "e": 28936, "s": 27786, "text": null }, { "code": "# Python3 program to find the minimum# group flips in a binary array def printGroups(arr, n): # Traverse through all array elements # starting from the second element for i in range(1, n): # If current element is not same # as previous if (arr[i] != arr[i - 1]): # If it is same as first element # then it is starting of the interval # to be flipped. if (arr[i] != arr[0]): print(\"From\", i, \"to \", end = \"\") # If it is not same as previous # and same as the first element, then # previous element is end of interval else: print(i - 1) # Explicitly handling the end of # last interval if (arr[n - 1] != arr[0]): print(n - 1) # Driver Codeif __name__ == '__main__': arr = [ 0, 1, 1, 0, 0, 0, 1, 1 ] n = len(arr) printGroups(arr, n) # This code is contributed by Bhupendra_Singh", "e": 29928, "s": 28936, "text": null }, { "code": "// C# program to find the minimum// group flips in a binary arrayusing System; class GFG{ static void printGroups(int []arr, int n){ // Traverse through all array elements // starting from the second element for(int i = 1; i < n; i++) { // If current element is not same // as previous if (arr[i] != arr[i - 1]) { // If it is same as first element // then it is starting of the interval // to be flipped. if (arr[i] != arr[0]) Console.Write(\"From \" + i + \" to \"); // If it is not same as previous // and same as first element, then // previous element is end of interval else Console.WriteLine(i - 1); } } // Explicitly handling the end // of last interval if (arr[n - 1] != arr[0]) Console.WriteLine(n - 1);} // Driver codepublic static void Main(String[] args){ int []arr = { 0, 1, 1, 0, 0, 0, 1, 1 }; int n = arr.Length; printGroups(arr, n);}} // This code is contributed by amal kumar choubey", "e": 31051, "s": 29928, "text": null }, { "code": "<script> // JavaScript program to find the minimum// group flips in a binary array function printGroups(arr, n) { // Traverse through all array elements // starting from the second element for (var i = 1; i < n; i++) { // If current element is not same // as previous if (arr[i] != arr[i - 1]) { // If it is same as first element // then it is starting of the interval // to be flipped. if (arr[i] != arr[0]) document.write( \"From \" + i + \" to \"); // If it is not same as previous // and same as first element, then // previous element is end of interval else document.write(i - 1 + \"<br>\"); } } // Explicitly handling the end of // last interval if (arr[n - 1] != arr[0]) document.write(n - 1 + \"<br>\");} var arr = [0, 1, 1, 0, 0, 0, 1, 1];var n = arr.length;printGroups(arr, n); </script>", "e": 31935, "s": 31051, "text": null }, { "code": null, "e": 31959, "s": 31935, "text": "From 1 to 2\nFrom 6 to 7" }, { "code": null, "e": 32004, "s": 31959, "text": "Time Complexity: O(n)Auxiliary Space: O(1)" }, { "code": null, "e": 32015, "s": 32004, "text": "bgangwar59" }, { "code": null, "e": 32024, "s": 32015, "text": "coder001" }, { "code": null, "e": 32043, "s": 32024, "text": "Amal Kumar Choubey" }, { "code": null, "e": 32049, "s": 32043, "text": "itsok" }, { "code": null, "e": 32074, "s": 32049, "text": "array-traversal-question" }, { "code": null, "e": 32088, "s": 32074, "text": "binary-string" }, { "code": null, "e": 32095, "s": 32088, "text": "Arrays" }, { "code": null, "e": 32102, "s": 32095, "text": "Arrays" }, { "code": null, "e": 32200, "s": 32102, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 32209, "s": 32200, "text": "Comments" }, { "code": null, "e": 32222, "s": 32209, "text": "Old Comments" }, { "code": null, "e": 32270, "s": 32222, "text": "Stack Data Structure (Introduction and Program)" }, { "code": null, "e": 32314, "s": 32270, "text": "Top 50 Array Coding Problems for Interviews" }, { "code": null, "e": 32337, "s": 32314, "text": "Introduction to Arrays" }, { "code": null, "e": 32369, "s": 32337, "text": "Multidimensional Arrays in Java" }, { "code": null, "e": 32383, "s": 32369, "text": "Linear Search" }, { "code": null, "e": 32468, "s": 32383, "text": "Given an array A[] and a number x, check for pair in A[] with sum as x (aka Two Sum)" }, { "code": null, "e": 32489, "s": 32468, "text": "Linked List vs Array" }, { "code": null, "e": 32534, "s": 32489, "text": "Python | Using 2D arrays/lists the right way" }, { "code": null, "e": 32625, "s": 32534, "text": "Given an array of size n and a number k, find all elements that appear more than n/k times" } ]
Tryit Editor v3.7
Tryit: HTML picture source
[]
How to Install Nose 2 in Python on Windows? - GeeksforGeeks
22 Sep, 2021 Nose 2 is a successor of Nose package and is used for testing python applications. In this article, we will look into the process of installing Nose2 Package on Windows. The only thing that you need for installing the Scrapy module on Windows are: Python PIP or Conda (depending upon user preference) If you want the installation to be done through conda, open up the Anaconda Powershell Prompt and use the below command: conda install -c conda-forge nose2 Note: The best way to install this module in conda is through coda-forge. Type y for yes when prompted. You will get a similar message once the installation is complete: Make sure you follow the best practices for installation using conda as: Use an environment for installation rather than in the base environment using the below command: conda create -n my-env conda activate my-env To verify if Nose2 Package has been successfully installed in your system run the below command in Anaconda Powershell Prompt: conda list nose2 You’ll get the below message if the installation is complete: If you want the installation to be done through PIP, open up the command Prompt and use the below command: pip install nose2 You will get a similar message once the installation is complete: To verify if the Nose2 package has been successfully installed in your system run the below command in Command Prompt: python -m pip show nose2 You’ll get the below message if the installation is complete: how-to-install Picked How To Installation Guide Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments How to Install FFmpeg on Windows? How to Install Jupyter Notebook on MacOS? How to Install Flutter on Visual Studio Code? How to Override compareTo Method in Java? How to Install Python Pandas on MacOS? Installation of Node.js on Linux How to Install FFmpeg on Windows? How to Install Selenium on MacOS? How to Install Pygame on Windows ? How to Add External JAR File to an IntelliJ IDEA Project?
[ { "code": null, "e": 24872, "s": 24844, "text": "\n22 Sep, 2021" }, { "code": null, "e": 25042, "s": 24872, "text": "Nose 2 is a successor of Nose package and is used for testing python applications. In this article, we will look into the process of installing Nose2 Package on Windows." }, { "code": null, "e": 25120, "s": 25042, "text": "The only thing that you need for installing the Scrapy module on Windows are:" }, { "code": null, "e": 25128, "s": 25120, "text": "Python " }, { "code": null, "e": 25174, "s": 25128, "text": "PIP or Conda (depending upon user preference)" }, { "code": null, "e": 25296, "s": 25174, "text": "If you want the installation to be done through conda, open up the Anaconda Powershell Prompt and use the below command:" }, { "code": null, "e": 25331, "s": 25296, "text": "conda install -c conda-forge nose2" }, { "code": null, "e": 25405, "s": 25331, "text": "Note: The best way to install this module in conda is through coda-forge." }, { "code": null, "e": 25435, "s": 25405, "text": "Type y for yes when prompted." }, { "code": null, "e": 25501, "s": 25435, "text": "You will get a similar message once the installation is complete:" }, { "code": null, "e": 25574, "s": 25501, "text": "Make sure you follow the best practices for installation using conda as:" }, { "code": null, "e": 25671, "s": 25574, "text": "Use an environment for installation rather than in the base environment using the below command:" }, { "code": null, "e": 25716, "s": 25671, "text": "conda create -n my-env\nconda activate my-env" }, { "code": null, "e": 25843, "s": 25716, "text": "To verify if Nose2 Package has been successfully installed in your system run the below command in Anaconda Powershell Prompt:" }, { "code": null, "e": 25860, "s": 25843, "text": "conda list nose2" }, { "code": null, "e": 25922, "s": 25860, "text": "You’ll get the below message if the installation is complete:" }, { "code": null, "e": 26030, "s": 25922, "text": "If you want the installation to be done through PIP, open up the command Prompt and use the below command:" }, { "code": null, "e": 26048, "s": 26030, "text": "pip install nose2" }, { "code": null, "e": 26114, "s": 26048, "text": "You will get a similar message once the installation is complete:" }, { "code": null, "e": 26233, "s": 26114, "text": "To verify if the Nose2 package has been successfully installed in your system run the below command in Command Prompt:" }, { "code": null, "e": 26258, "s": 26233, "text": "python -m pip show nose2" }, { "code": null, "e": 26320, "s": 26258, "text": "You’ll get the below message if the installation is complete:" }, { "code": null, "e": 26335, "s": 26320, "text": "how-to-install" }, { "code": null, "e": 26342, "s": 26335, "text": "Picked" }, { "code": null, "e": 26349, "s": 26342, "text": "How To" }, { "code": null, "e": 26368, "s": 26349, "text": "Installation Guide" }, { "code": null, "e": 26466, "s": 26368, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 26475, "s": 26466, "text": "Comments" }, { "code": null, "e": 26488, "s": 26475, "text": "Old Comments" }, { "code": null, "e": 26522, "s": 26488, "text": "How to Install FFmpeg on Windows?" }, { "code": null, "e": 26564, "s": 26522, "text": "How to Install Jupyter Notebook on MacOS?" }, { "code": null, "e": 26610, "s": 26564, "text": "How to Install Flutter on Visual Studio Code?" }, { "code": null, "e": 26652, "s": 26610, "text": "How to Override compareTo Method in Java?" }, { "code": null, "e": 26691, "s": 26652, "text": "How to Install Python Pandas on MacOS?" }, { "code": null, "e": 26724, "s": 26691, "text": "Installation of Node.js on Linux" }, { "code": null, "e": 26758, "s": 26724, "text": "How to Install FFmpeg on Windows?" }, { "code": null, "e": 26792, "s": 26758, "text": "How to Install Selenium on MacOS?" }, { "code": null, "e": 26827, "s": 26792, "text": "How to Install Pygame on Windows ?" } ]
Constant time range add operation on an array - GeeksforGeeks
19 Apr, 2021 Given an array of size N which is initialized with all zeros. We are given many ranges add queries, which should be applied to this array. We need to print the final updated array as our result. Examples: N = 6 Arr = [0, 0, 0, 0, 0, 0] rangeUpdate1 [0, 2], add 100 Arr = [100, 100, 100, 0, 0, 0] rangeUpdate1 [1, 5], add 100 Arr = [100, 200, 200, 100, 100, 100] rangeUpdate1 [2, 3], add 100 Arr = [100, 200, 300, 200, 100, 100] Which is the final updated array. This problem can be solved using segment tree with lazy updates in O(log N) time per query but we can do better here, as update operation is not given. We can process each query in constant time using this logic when a query to add V is given in range [a, b] we will add V to arr[a] and –V to arr[b+1] now if we want to get the actual values of the array we will convert the above array into prefix sum array. See below example to understand: Arr = [0, 0, 0, 0, 0, 0] rangeUpdate1 [0, 2], add 100 Arr = [100, 0, 0, -100, 0, 0] rangeUpdate1 [1, 5], add 100. Arr = [100, 100, 0, -100, 0, 0] Note: You can not add -100 at 6th index because array length is 6. rangeUpdate1 [2, 3], add 100 Arr = [100, 100, 100, -100, -100, 0] Now we will convert above operation array to prefix sum array as shown below, Arr = [100, 200, 300, 200, 100, 100] Which is the final updated array. So in effect, when we add a value V to specific index of the array, It represents adding V to all elements right to this index, that is why we add –V after range to remove its effect after its range of add query. Please note in below code, if range spans till the last index, the addition of –V is omitted to be in memory limit of the array. C++ Java Python3 C# PHP Javascript // C++ program to get updated array after many array range// add operation#include <bits/stdc++.h>using namespace std; // Utility method to add value val, to range [lo, hi]void add(int arr[], int N, int lo, int hi, int val){ arr[lo] += val; if (hi != N - 1) arr[hi + 1] -= val;} // Utility method to get actual array from operation arrayvoid updateArray(int arr[], int N){ // convert array into prefix sum array for (int i = 1; i < N; i++) arr[i] += arr[i - 1];} // method to print final updated arrayvoid printArr(int arr[], int N){ updateArray(arr, N); for (int i = 0; i < N; i++) cout << arr[i] << " "; cout << endl;} // Driver codeint main(){ int N = 6; int arr[N] = {0}; // Range add Queries add(arr, N, 0, 2, 100); add(arr, N, 1, 5, 100); add(arr, N, 2, 3, 100); printArr(arr, N); return 0;} // Java program to get updated array after// many array range add operationimport java.io.*; class GFG { // Utility method to add value val, // to range [lo, hi] static void add(int arr[], int N, int lo, int hi, int val) { arr[lo] += val; if (hi != N - 1) arr[hi + 1] -= val; } // Utility method to get actual array from // operation array static void updateArray(int arr[], int N) { // convert array into prefix sum array for (int i = 1; i < N; i++) arr[i] += arr[i - 1]; } // method to print final updated array static void printArr(int arr[], int N) { updateArray(arr, N); for (int i = 0; i < N; i++) System.out.print("" + arr[i] + " "); System.out.print("\n"); } // Driver code public static void main(String[] args) { int N = 6; int arr[] = new int[N]; // Range add Queries add(arr, N, 0, 2, 100); add(arr, N, 1, 5, 100); add(arr, N, 2, 3, 100); printArr(arr, N); }} // This code is contributed by Prakriti Gupta # Python3 program to get updated array# after many array range add operation # Utility method to add value# val, to range [lo, hi] def add(arr, N, lo, hi, val): arr[lo] += val if (hi != N - 1): arr[hi + 1] -= val # Utility method to get actual# array from operation array def updateArray(arr, N): # convert array into prefix sum array for i in range(1, N): arr[i] += arr[i - 1] # method to print final updated array def printArr(arr, N): updateArray(arr, N) for i in range(N): print(arr[i], end=" ") print() # Driver codeN = 6arr = [0 for i in range(N)] # Range add Queriesadd(arr, N, 0, 2, 100)add(arr, N, 1, 5, 100)add(arr, N, 2, 3, 100) printArr(arr, N) # This code is contributed by Anant Agarwal. // C# program to get updated array after// many array range add operationusing System; class GFG { // Utility method to add value val, // to range [lo, hi] static void add(int[] arr, int N, int lo, int hi, int val) { arr[lo] += val; if (hi != N - 1) arr[hi + 1] -= val; } // Utility method to get actual // array from operation array static void updateArray(int[] arr, int N) { // convert array into // prefix sum array for (int i = 1; i < N; i++) arr[i] += arr[i - 1]; } // method to print final updated array static void printArr(int[] arr, int N) { updateArray(arr, N); for (int i = 0; i < N; i++) Console.Write("" + arr[i] + " "); Console.Write("\n"); } // Driver code public static void Main() { int N = 6; int[] arr = new int[N]; // Range add Queries add(arr, N, 0, 2, 100); add(arr, N, 1, 5, 100); add(arr, N, 2, 3, 100); printArr(arr, N); }} // This code is contributed by Nitin Mittal. <?php// PHP program to get updated array after// many array range add operation // Utility method to add value val,// to range [lo, hi]function add(&$arr, $N, $lo, $hi, $val){ $arr[$lo] += $val; if ($hi != $N - 1) $arr[$hi + 1] -= $val;} // Utility method to get actual array// from operation arrayfunction updateArray(&$arr, $N){ // convert array into prefix sum array for ($i = 1; $i < $N; $i++) $arr[$i] += $arr[$i - 1];} // method to print final updated arrayfunction printArr(&$arr, $N){ updateArray($arr, $N); for ($i = 0; $i < $N; $i++) echo $arr[$i] . " "; echo "\n";} // Driver Code$N = 6;$arr = array_fill(0, $N, NULL); // Range add Queriesadd($arr, $N, 0, 2, 100);add($arr, $N, 1, 5, 100);add($arr, $N, 2, 3, 100); printArr($arr, $N); // This code is contributed by ita_c?> <script> // Javascript program to get updated array after// many array range add operation // Utility method to add value val, // to range [lo, hi] function add(arr,N,lo,hi,val) { arr[lo] += val; if (hi != N - 1) arr[hi + 1] -= val; } // Utility method to get actual array from // operation array function updateArray(arr,N) { // convert array into prefix sum array for (let i = 1; i < N; i++) arr[i] += arr[i - 1]; } // method to print final updated array function printArr(arr,N) { updateArray(arr, N); for (let i = 0; i < N; i++) document.write("" + arr[i] + " "); document.write("<br>"); } // Driver code let N = 6; let arr=new Array(N); for(let i=0;i<N;i++) { arr[i]=0; } // Range add Queries add(arr, N, 0, 2, 100); add(arr, N, 1, 5, 100); add(arr, N, 2, 3, 100); printArr(arr, N); // This code is contributed by rag2127 </script> 100 200 300 200 100 100 This article is contributed by Utkarsh Trivedi. If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above. nitin mittal ukasp PunjPrakash rag2127 array-range-queries Directi Arrays Directi Arrays Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments Stack Data Structure (Introduction and Program) Top 50 Array Coding Problems for Interviews Introduction to Arrays Linear Search Multidimensional Arrays in Java Maximum and minimum of an array using minimum number of comparisons Python | Using 2D arrays/lists the right way Queue | Set 1 (Introduction and Array Implementation) Linked List vs Array Given an array A[] and a number x, check for pair in A[] with sum as x (aka Two Sum)
[ { "code": null, "e": 24646, "s": 24618, "text": "\n19 Apr, 2021" }, { "code": null, "e": 24843, "s": 24646, "text": "Given an array of size N which is initialized with all zeros. We are given many ranges add queries, which should be applied to this array. We need to print the final updated array as our result. " }, { "code": null, "e": 24854, "s": 24843, "text": "Examples: " }, { "code": null, "e": 25111, "s": 24854, "text": "N = 6\nArr = [0, 0, 0, 0, 0, 0]\nrangeUpdate1 [0, 2], add 100\nArr = [100, 100, 100, 0, 0, 0]\nrangeUpdate1 [1, 5], add 100\nArr = [100, 200, 200, 100, 100, 100]\nrangeUpdate1 [2, 3], add 100\nArr = [100, 200, 300, 200, 100, 100]\nWhich is the final updated array." }, { "code": null, "e": 25522, "s": 25111, "text": "This problem can be solved using segment tree with lazy updates in O(log N) time per query but we can do better here, as update operation is not given. We can process each query in constant time using this logic when a query to add V is given in range [a, b] we will add V to arr[a] and –V to arr[b+1] now if we want to get the actual values of the array we will convert the above array into prefix sum array. " }, { "code": null, "e": 25555, "s": 25522, "text": "See below example to understand:" }, { "code": null, "e": 25993, "s": 25555, "text": "Arr = [0, 0, 0, 0, 0, 0]\n\nrangeUpdate1 [0, 2], add 100\nArr = [100, 0, 0, -100, 0, 0]\n\nrangeUpdate1 [1, 5], add 100. \nArr = [100, 100, 0, -100, 0, 0]\nNote: You can not add -100 at 6th index because array length is 6.\n\nrangeUpdate1 [2, 3], add 100\nArr = [100, 100, 100, -100, -100, 0] \n\nNow we will convert above operation array to prefix sum array as shown below,\nArr = [100, 200, 300, 200, 100, 100]\n\nWhich is the final updated array." }, { "code": null, "e": 26337, "s": 25993, "text": "So in effect, when we add a value V to specific index of the array, It represents adding V to all elements right to this index, that is why we add –V after range to remove its effect after its range of add query. Please note in below code, if range spans till the last index, the addition of –V is omitted to be in memory limit of the array. " }, { "code": null, "e": 26341, "s": 26337, "text": "C++" }, { "code": null, "e": 26346, "s": 26341, "text": "Java" }, { "code": null, "e": 26354, "s": 26346, "text": "Python3" }, { "code": null, "e": 26357, "s": 26354, "text": "C#" }, { "code": null, "e": 26361, "s": 26357, "text": "PHP" }, { "code": null, "e": 26372, "s": 26361, "text": "Javascript" }, { "code": "// C++ program to get updated array after many array range// add operation#include <bits/stdc++.h>using namespace std; // Utility method to add value val, to range [lo, hi]void add(int arr[], int N, int lo, int hi, int val){ arr[lo] += val; if (hi != N - 1) arr[hi + 1] -= val;} // Utility method to get actual array from operation arrayvoid updateArray(int arr[], int N){ // convert array into prefix sum array for (int i = 1; i < N; i++) arr[i] += arr[i - 1];} // method to print final updated arrayvoid printArr(int arr[], int N){ updateArray(arr, N); for (int i = 0; i < N; i++) cout << arr[i] << \" \"; cout << endl;} // Driver codeint main(){ int N = 6; int arr[N] = {0}; // Range add Queries add(arr, N, 0, 2, 100); add(arr, N, 1, 5, 100); add(arr, N, 2, 3, 100); printArr(arr, N); return 0;}", "e": 27245, "s": 26372, "text": null }, { "code": "// Java program to get updated array after// many array range add operationimport java.io.*; class GFG { // Utility method to add value val, // to range [lo, hi] static void add(int arr[], int N, int lo, int hi, int val) { arr[lo] += val; if (hi != N - 1) arr[hi + 1] -= val; } // Utility method to get actual array from // operation array static void updateArray(int arr[], int N) { // convert array into prefix sum array for (int i = 1; i < N; i++) arr[i] += arr[i - 1]; } // method to print final updated array static void printArr(int arr[], int N) { updateArray(arr, N); for (int i = 0; i < N; i++) System.out.print(\"\" + arr[i] + \" \"); System.out.print(\"\\n\"); } // Driver code public static void main(String[] args) { int N = 6; int arr[] = new int[N]; // Range add Queries add(arr, N, 0, 2, 100); add(arr, N, 1, 5, 100); add(arr, N, 2, 3, 100); printArr(arr, N); }} // This code is contributed by Prakriti Gupta", "e": 28373, "s": 27245, "text": null }, { "code": "# Python3 program to get updated array# after many array range add operation # Utility method to add value# val, to range [lo, hi] def add(arr, N, lo, hi, val): arr[lo] += val if (hi != N - 1): arr[hi + 1] -= val # Utility method to get actual# array from operation array def updateArray(arr, N): # convert array into prefix sum array for i in range(1, N): arr[i] += arr[i - 1] # method to print final updated array def printArr(arr, N): updateArray(arr, N) for i in range(N): print(arr[i], end=\" \") print() # Driver codeN = 6arr = [0 for i in range(N)] # Range add Queriesadd(arr, N, 0, 2, 100)add(arr, N, 1, 5, 100)add(arr, N, 2, 3, 100) printArr(arr, N) # This code is contributed by Anant Agarwal.", "e": 29124, "s": 28373, "text": null }, { "code": "// C# program to get updated array after// many array range add operationusing System; class GFG { // Utility method to add value val, // to range [lo, hi] static void add(int[] arr, int N, int lo, int hi, int val) { arr[lo] += val; if (hi != N - 1) arr[hi + 1] -= val; } // Utility method to get actual // array from operation array static void updateArray(int[] arr, int N) { // convert array into // prefix sum array for (int i = 1; i < N; i++) arr[i] += arr[i - 1]; } // method to print final updated array static void printArr(int[] arr, int N) { updateArray(arr, N); for (int i = 0; i < N; i++) Console.Write(\"\" + arr[i] + \" \"); Console.Write(\"\\n\"); } // Driver code public static void Main() { int N = 6; int[] arr = new int[N]; // Range add Queries add(arr, N, 0, 2, 100); add(arr, N, 1, 5, 100); add(arr, N, 2, 3, 100); printArr(arr, N); }} // This code is contributed by Nitin Mittal.", "e": 30237, "s": 29124, "text": null }, { "code": "<?php// PHP program to get updated array after// many array range add operation // Utility method to add value val,// to range [lo, hi]function add(&$arr, $N, $lo, $hi, $val){ $arr[$lo] += $val; if ($hi != $N - 1) $arr[$hi + 1] -= $val;} // Utility method to get actual array// from operation arrayfunction updateArray(&$arr, $N){ // convert array into prefix sum array for ($i = 1; $i < $N; $i++) $arr[$i] += $arr[$i - 1];} // method to print final updated arrayfunction printArr(&$arr, $N){ updateArray($arr, $N); for ($i = 0; $i < $N; $i++) echo $arr[$i] . \" \"; echo \"\\n\";} // Driver Code$N = 6;$arr = array_fill(0, $N, NULL); // Range add Queriesadd($arr, $N, 0, 2, 100);add($arr, $N, 1, 5, 100);add($arr, $N, 2, 3, 100); printArr($arr, $N); // This code is contributed by ita_c?>", "e": 31060, "s": 30237, "text": null }, { "code": "<script> // Javascript program to get updated array after// many array range add operation // Utility method to add value val, // to range [lo, hi] function add(arr,N,lo,hi,val) { arr[lo] += val; if (hi != N - 1) arr[hi + 1] -= val; } // Utility method to get actual array from // operation array function updateArray(arr,N) { // convert array into prefix sum array for (let i = 1; i < N; i++) arr[i] += arr[i - 1]; } // method to print final updated array function printArr(arr,N) { updateArray(arr, N); for (let i = 0; i < N; i++) document.write(\"\" + arr[i] + \" \"); document.write(\"<br>\"); } // Driver code let N = 6; let arr=new Array(N); for(let i=0;i<N;i++) { arr[i]=0; } // Range add Queries add(arr, N, 0, 2, 100); add(arr, N, 1, 5, 100); add(arr, N, 2, 3, 100); printArr(arr, N); // This code is contributed by rag2127 </script>", "e": 32095, "s": 31060, "text": null }, { "code": null, "e": 32120, "s": 32095, "text": "100 200 300 200 100 100 " }, { "code": null, "e": 32548, "s": 32120, "text": "This article is contributed by Utkarsh Trivedi. If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above. " }, { "code": null, "e": 32561, "s": 32548, "text": "nitin mittal" }, { "code": null, "e": 32567, "s": 32561, "text": "ukasp" }, { "code": null, "e": 32579, "s": 32567, "text": "PunjPrakash" }, { "code": null, "e": 32587, "s": 32579, "text": "rag2127" }, { "code": null, "e": 32607, "s": 32587, "text": "array-range-queries" }, { "code": null, "e": 32615, "s": 32607, "text": "Directi" }, { "code": null, "e": 32622, "s": 32615, "text": "Arrays" }, { "code": null, "e": 32630, "s": 32622, "text": "Directi" }, { "code": null, "e": 32637, "s": 32630, "text": "Arrays" }, { "code": null, "e": 32735, "s": 32637, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 32744, "s": 32735, "text": "Comments" }, { "code": null, "e": 32757, "s": 32744, "text": "Old Comments" }, { "code": null, "e": 32805, "s": 32757, "text": "Stack Data Structure (Introduction and Program)" }, { "code": null, "e": 32849, "s": 32805, "text": "Top 50 Array Coding Problems for Interviews" }, { "code": null, "e": 32872, "s": 32849, "text": "Introduction to Arrays" }, { "code": null, "e": 32886, "s": 32872, "text": "Linear Search" }, { "code": null, "e": 32918, "s": 32886, "text": "Multidimensional Arrays in Java" }, { "code": null, "e": 32986, "s": 32918, "text": "Maximum and minimum of an array using minimum number of comparisons" }, { "code": null, "e": 33031, "s": 32986, "text": "Python | Using 2D arrays/lists the right way" }, { "code": null, "e": 33085, "s": 33031, "text": "Queue | Set 1 (Introduction and Array Implementation)" }, { "code": null, "e": 33106, "s": 33085, "text": "Linked List vs Array" } ]
gmtime() Function in C/C++ - GeeksforGeeks
20 Jul, 2020 The gmtime() function in C++ change the time, which is given to UTC(Universal Time Coordinated) time (i.e., the time at the GMT timezone). The gmtime() is defined in ctime header file. Syntax: tm* gmtime ( const time_t* current_time ) The hours can be accessed using tm_hour The minutes can be accessed using tm_min The seconds can be accessed using tm_sec Parameters: The function accepts one mandatory parameter current_time : which specifies a pointer to a time_t object. Return Value: The function returns two type of values described below: On Success, returns a pointer to a tm object Otherwise, Null pointer is returned Below programs illustrate the above function. Program 1: // C++ program to illustrate the// gmtime() function#include <stdio.h>#include <time.h>#define CST (+8)#define IND (-5) int main(){ // object time_t current_time; // pointer struct tm* ptime; // use time function time(¤t_time); // gets the current-time ptime = gmtime(¤t_time); // print the current time printf("Current time:\n"); printf("Beijing ( China ):%2d:%02d:%02d\n", (ptime->tm_hour + CST) % 24, ptime->tm_min, ptime->tm_sec); printf("Delhi ( India ):%2d:%02d:%02d\n", (ptime->tm_hour + IND) % 24, ptime->tm_min, ptime->tm_sec); return 0;} Current time: Beijing ( China ):16:40:21 Delhi ( India ): 3:40:21 Program 2: // C++ program to illustrate the// gmtime() function#include <stdio.h>#include <time.h>#define UTC (0)#define ART (-3) int main(){ time_t current_time; struct tm* ptime; time(¤t_time); ptime = gmtime(¤t_time); printf("Current time:\n"); printf("Monrovia ( Liberia ) :%2d:%02d:%02d\n", (ptime->tm_hour + UTC) % 24, ptime->tm_min, ptime->tm_sec); printf("Buenos Aires ( Argentina ) :%2d:%02d:%02d\n", (ptime->tm_hour + ART) % 24, ptime->tm_min, ptime->tm_sec); return 0;} Current time: Monrovia ( Liberia ) : 8:40:22 Buenos Aires ( Argentina ) : 5:40:22 Akanksha_Rai C-Library CPP-Functions C Programs C++ Programs Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments C Program to read contents of Whole File Producer Consumer Problem in C C program to find the length of a string Exit codes in C/C++ with Examples Difference between break and continue statement in C C++ Program for QuickSort C++ program for hashing with chaining Sorting a Map by value in C++ STL cin in C++ delete keyword in C++
[ { "code": null, "e": 24539, "s": 24511, "text": "\n20 Jul, 2020" }, { "code": null, "e": 24724, "s": 24539, "text": "The gmtime() function in C++ change the time, which is given to UTC(Universal Time Coordinated) time (i.e., the time at the GMT timezone). The gmtime() is defined in ctime header file." }, { "code": null, "e": 24732, "s": 24724, "text": "Syntax:" }, { "code": null, "e": 24774, "s": 24732, "text": "tm* gmtime ( const time_t* current_time )" }, { "code": null, "e": 24814, "s": 24774, "text": "The hours can be accessed using tm_hour" }, { "code": null, "e": 24855, "s": 24814, "text": "The minutes can be accessed using tm_min" }, { "code": null, "e": 24896, "s": 24855, "text": "The seconds can be accessed using tm_sec" }, { "code": null, "e": 25014, "s": 24896, "text": "Parameters: The function accepts one mandatory parameter current_time : which specifies a pointer to a time_t object." }, { "code": null, "e": 25085, "s": 25014, "text": "Return Value: The function returns two type of values described below:" }, { "code": null, "e": 25130, "s": 25085, "text": "On Success, returns a pointer to a tm object" }, { "code": null, "e": 25166, "s": 25130, "text": "Otherwise, Null pointer is returned" }, { "code": null, "e": 25212, "s": 25166, "text": "Below programs illustrate the above function." }, { "code": null, "e": 25223, "s": 25212, "text": "Program 1:" }, { "code": "// C++ program to illustrate the// gmtime() function#include <stdio.h>#include <time.h>#define CST (+8)#define IND (-5) int main(){ // object time_t current_time; // pointer struct tm* ptime; // use time function time(¤t_time); // gets the current-time ptime = gmtime(¤t_time); // print the current time printf(\"Current time:\\n\"); printf(\"Beijing ( China ):%2d:%02d:%02d\\n\", (ptime->tm_hour + CST) % 24, ptime->tm_min, ptime->tm_sec); printf(\"Delhi ( India ):%2d:%02d:%02d\\n\", (ptime->tm_hour + IND) % 24, ptime->tm_min, ptime->tm_sec); return 0;}", "e": 25845, "s": 25223, "text": null }, { "code": null, "e": 25912, "s": 25845, "text": "Current time:\nBeijing ( China ):16:40:21\nDelhi ( India ): 3:40:21\n" }, { "code": null, "e": 25923, "s": 25912, "text": "Program 2:" }, { "code": "// C++ program to illustrate the// gmtime() function#include <stdio.h>#include <time.h>#define UTC (0)#define ART (-3) int main(){ time_t current_time; struct tm* ptime; time(¤t_time); ptime = gmtime(¤t_time); printf(\"Current time:\\n\"); printf(\"Monrovia ( Liberia ) :%2d:%02d:%02d\\n\", (ptime->tm_hour + UTC) % 24, ptime->tm_min, ptime->tm_sec); printf(\"Buenos Aires ( Argentina ) :%2d:%02d:%02d\\n\", (ptime->tm_hour + ART) % 24, ptime->tm_min, ptime->tm_sec); return 0;}", "e": 26440, "s": 25923, "text": null }, { "code": null, "e": 26523, "s": 26440, "text": "Current time:\nMonrovia ( Liberia ) : 8:40:22\nBuenos Aires ( Argentina ) : 5:40:22\n" }, { "code": null, "e": 26536, "s": 26523, "text": "Akanksha_Rai" }, { "code": null, "e": 26546, "s": 26536, "text": "C-Library" }, { "code": null, "e": 26560, "s": 26546, "text": "CPP-Functions" }, { "code": null, "e": 26571, "s": 26560, "text": "C Programs" }, { "code": null, "e": 26584, "s": 26571, "text": "C++ Programs" }, { "code": null, "e": 26682, "s": 26584, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 26691, "s": 26682, "text": "Comments" }, { "code": null, "e": 26704, "s": 26691, "text": "Old Comments" }, { "code": null, "e": 26745, "s": 26704, "text": "C Program to read contents of Whole File" }, { "code": null, "e": 26776, "s": 26745, "text": "Producer Consumer Problem in C" }, { "code": null, "e": 26817, "s": 26776, "text": "C program to find the length of a string" }, { "code": null, "e": 26851, "s": 26817, "text": "Exit codes in C/C++ with Examples" }, { "code": null, "e": 26904, "s": 26851, "text": "Difference between break and continue statement in C" }, { "code": null, "e": 26930, "s": 26904, "text": "C++ Program for QuickSort" }, { "code": null, "e": 26968, "s": 26930, "text": "C++ program for hashing with chaining" }, { "code": null, "e": 27002, "s": 26968, "text": "Sorting a Map by value in C++ STL" }, { "code": null, "e": 27013, "s": 27002, "text": "cin in C++" } ]
Read Properties File Using jproperties in Python - GeeksforGeeks
03 Jan, 2021 In this article, we are going to see how to read properties file in python using jproperties module. It is a Java Property file parser and writer for Python. For installation run this command into your terminal. pip install jproperties Various properties of this module: get() Method or Index-Based access to reading the values associated with the key. items() method to get the collection of all key-value pairs and iterate over it to read all keys — value pair from the properties. The file contains key-value pairs in each line (i.e it is a dictionary in python). This operator equals (=) works as a delimiter between the key and value We will use this properties file(example.properties) for demonstration: Example 1: Printing all properties details. Approach: Import the module Load the properties file into our properties object. Here items() method is to get the collection of the tuple, Which contains Keys and Corresponding PropertyTuple values Below is the implementation: Python3 from jproperties import Properties configs = Properties()with open('example.properties', 'rb') as read_prop: configs.load(read_prop) prop_view = configs.items()print(type(prop_view)) for item in prop_view: print(item) Output: Output Of The Program Using items() Method Example 2: Printing properties file In the basis of key, values pairs like in dictionary in Python Approach: Import the module Then we open the .properties file in ‘rb’ mode then we use load() function Then we use items() method to get the collection all key-value pairs here (i.e: print(type(prop_view)) prints the class type of the argument specified Below is the full implementation: Python3 from jproperties import Propertiesconfigs = Properties() with open('example.properties', 'rb') as read_prop: configs.load(read_prop) prop_view = configs.items()print(type(prop_view)) for item in prop_view: print(item[0], '=', item[1].data) Output: Example 3: Printing each specific values-data as we need Approach: Import the module Then we open the .properties file in ‘rb’ mode then we use load() function Use the get() method to return the value of the item with the specified key. Use len() function to get the count of properties of the file. Below is the full implementation: Python3 from jproperties import Propertiesconfigs = Properties() with open('example.properties', 'rb') as read_prop: configs.load(read_prop) print(configs.get("DB_User")) print(f'Database User: {configs.get("DB_User").data}') print(f'Database Password: {configs["DB_PWD"].data}') print(f'Properties Count: {len(configs)}') Output: Here Is The Output of Properties File Using get() Method Picked python-file-handling Python Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments How to Install PIP on Windows ? How to drop one or multiple columns in Pandas Dataframe How To Convert Python Dictionary To JSON? Check if element exists in list in Python Python | Pandas dataframe.groupby() Defaultdict in Python Python | Get unique values from a list Python Classes and Objects Python | os.path.join() method Create a directory in Python
[ { "code": null, "e": 23901, "s": 23873, "text": "\n03 Jan, 2021" }, { "code": null, "e": 24113, "s": 23901, "text": "In this article, we are going to see how to read properties file in python using jproperties module. It is a Java Property file parser and writer for Python. For installation run this command into your terminal." }, { "code": null, "e": 24137, "s": 24113, "text": "pip install jproperties" }, { "code": null, "e": 24172, "s": 24137, "text": "Various properties of this module:" }, { "code": null, "e": 24254, "s": 24172, "text": "get() Method or Index-Based access to reading the values associated with the key." }, { "code": null, "e": 24385, "s": 24254, "text": "items() method to get the collection of all key-value pairs and iterate over it to read all keys — value pair from the properties." }, { "code": null, "e": 24540, "s": 24385, "text": "The file contains key-value pairs in each line (i.e it is a dictionary in python). This operator equals (=) works as a delimiter between the key and value" }, { "code": null, "e": 24612, "s": 24540, "text": "We will use this properties file(example.properties) for demonstration:" }, { "code": null, "e": 24656, "s": 24612, "text": "Example 1: Printing all properties details." }, { "code": null, "e": 24666, "s": 24656, "text": "Approach:" }, { "code": null, "e": 24684, "s": 24666, "text": "Import the module" }, { "code": null, "e": 24737, "s": 24684, "text": "Load the properties file into our properties object." }, { "code": null, "e": 24855, "s": 24737, "text": "Here items() method is to get the collection of the tuple, Which contains Keys and Corresponding PropertyTuple values" }, { "code": null, "e": 24884, "s": 24855, "text": "Below is the implementation:" }, { "code": null, "e": 24892, "s": 24884, "text": "Python3" }, { "code": "from jproperties import Properties configs = Properties()with open('example.properties', 'rb') as read_prop: configs.load(read_prop) prop_view = configs.items()print(type(prop_view)) for item in prop_view: print(item)", "e": 25124, "s": 24892, "text": null }, { "code": null, "e": 25132, "s": 25124, "text": "Output:" }, { "code": null, "e": 25177, "s": 25132, "text": "Output Of The Program Using items() Method " }, { "code": null, "e": 25277, "s": 25177, "text": "Example 2: Printing properties file In the basis of key, values pairs like in dictionary in Python " }, { "code": null, "e": 25287, "s": 25277, "text": "Approach:" }, { "code": null, "e": 25305, "s": 25287, "text": "Import the module" }, { "code": null, "e": 25380, "s": 25305, "text": "Then we open the .properties file in ‘rb’ mode then we use load() function" }, { "code": null, "e": 25532, "s": 25380, "text": "Then we use items() method to get the collection all key-value pairs here (i.e: print(type(prop_view)) prints the class type of the argument specified" }, { "code": null, "e": 25566, "s": 25532, "text": "Below is the full implementation:" }, { "code": null, "e": 25574, "s": 25566, "text": "Python3" }, { "code": "from jproperties import Propertiesconfigs = Properties() with open('example.properties', 'rb') as read_prop: configs.load(read_prop) prop_view = configs.items()print(type(prop_view)) for item in prop_view: print(item[0], '=', item[1].data)", "e": 25828, "s": 25574, "text": null }, { "code": null, "e": 25836, "s": 25828, "text": "Output:" }, { "code": null, "e": 25894, "s": 25836, "text": "Example 3: Printing each specific values-data as we need " }, { "code": null, "e": 25904, "s": 25894, "text": "Approach:" }, { "code": null, "e": 25922, "s": 25904, "text": "Import the module" }, { "code": null, "e": 25997, "s": 25922, "text": "Then we open the .properties file in ‘rb’ mode then we use load() function" }, { "code": null, "e": 26074, "s": 25997, "text": "Use the get() method to return the value of the item with the specified key." }, { "code": null, "e": 26137, "s": 26074, "text": "Use len() function to get the count of properties of the file." }, { "code": null, "e": 26171, "s": 26137, "text": "Below is the full implementation:" }, { "code": null, "e": 26179, "s": 26171, "text": "Python3" }, { "code": "from jproperties import Propertiesconfigs = Properties() with open('example.properties', 'rb') as read_prop: configs.load(read_prop) print(configs.get(\"DB_User\")) print(f'Database User: {configs.get(\"DB_User\").data}') print(f'Database Password: {configs[\"DB_PWD\"].data}') print(f'Properties Count: {len(configs)}') ", "e": 26510, "s": 26179, "text": null }, { "code": null, "e": 26518, "s": 26510, "text": "Output:" }, { "code": null, "e": 26577, "s": 26518, "text": "Here Is The Output of Properties File Using get() Method " }, { "code": null, "e": 26584, "s": 26577, "text": "Picked" }, { "code": null, "e": 26605, "s": 26584, "text": "python-file-handling" }, { "code": null, "e": 26612, "s": 26605, "text": "Python" }, { "code": null, "e": 26710, "s": 26612, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 26719, "s": 26710, "text": "Comments" }, { "code": null, "e": 26732, "s": 26719, "text": "Old Comments" }, { "code": null, "e": 26764, "s": 26732, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 26820, "s": 26764, "text": "How to drop one or multiple columns in Pandas Dataframe" }, { "code": null, "e": 26862, "s": 26820, "text": "How To Convert Python Dictionary To JSON?" }, { "code": null, "e": 26904, "s": 26862, "text": "Check if element exists in list in Python" }, { "code": null, "e": 26940, "s": 26904, "text": "Python | Pandas dataframe.groupby()" }, { "code": null, "e": 26962, "s": 26940, "text": "Defaultdict in Python" }, { "code": null, "e": 27001, "s": 26962, "text": "Python | Get unique values from a list" }, { "code": null, "e": 27028, "s": 27001, "text": "Python Classes and Objects" }, { "code": null, "e": 27059, "s": 27028, "text": "Python | os.path.join() method" } ]
Bootstrap 5 Tutorial
Bootstrap 5 is the newest version of Bootstrap, which is the most popular HTML, CSS, and JavaScript framework for creating responsive, mobile-first websites. Bootstrap 5 is completely free to download and use! Start learning Bootstrap 5 now » Learn Bootstrap 5 This tutorial contains hundreds of Bootstrap 5 examples. With our online editor, you can edit the code, and click on a button to view the result. Resize this responsive page to see the effect! Lorem ipsum dolor sit amet, consectetur adipisicing elit... Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris... Lorem ipsum dolor sit amet, consectetur adipisicing elit... Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris... Lorem ipsum dolor sit amet, consectetur adipisicing elit... Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris... Click on the "Try it Yourself" button to see how it works. Bootstrap 5 is the newest version of Bootstrap; with new components, faster stylesheet and more responsiveness. Bootstrap 5 supports the latest, stable releases of all major browsers and platforms. However, Internet Explorer 11 and down is not supported. The main differences between Bootstrap 5 and Bootstrap 3 & 4, is that Bootstrap 5 has switched to JavaScript instead of jQuery. Note: Bootstrap 3 and Bootstrap 4 is still supported by the team for critical bugfixes and documentation changes, and it is perfectly safe to continue to use them. However, new features will NOT be added to them. Use a Bootstrap class to center the following text: <p class=""> Hello World!</p> Start the Exercise Test your Bootstrap 5 skills at W3Schools! Start Bootstrap 5 Quiz! We just launchedW3Schools videos Get certifiedby completinga course today! If you want to report an error, or if you want to make a suggestion, do not hesitate to send us an e-mail: help@w3schools.com Your message has been sent to W3Schools.
[ { "code": null, "e": 158, "s": 0, "text": "Bootstrap 5 is the newest version of Bootstrap, which is the most popular HTML, CSS, and JavaScript framework for creating responsive, mobile-first websites." }, { "code": null, "e": 210, "s": 158, "text": "Bootstrap 5 is completely free to download and use!" }, { "code": null, "e": 243, "s": 210, "text": "Start learning Bootstrap 5 now »" }, { "code": null, "e": 261, "s": 243, "text": "Learn Bootstrap 5" }, { "code": null, "e": 318, "s": 261, "text": "This tutorial contains hundreds of Bootstrap 5 examples." }, { "code": null, "e": 407, "s": 318, "text": "With our online editor, you can edit the code, and click on a button to view the result." }, { "code": null, "e": 454, "s": 407, "text": "Resize this responsive page to see the effect!" }, { "code": null, "e": 514, "s": 454, "text": "Lorem ipsum dolor sit amet, consectetur adipisicing elit..." }, { "code": null, "e": 584, "s": 514, "text": "Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris..." }, { "code": null, "e": 644, "s": 584, "text": "Lorem ipsum dolor sit amet, consectetur adipisicing elit..." }, { "code": null, "e": 714, "s": 644, "text": "Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris..." }, { "code": null, "e": 774, "s": 714, "text": "Lorem ipsum dolor sit amet, consectetur adipisicing elit..." }, { "code": null, "e": 844, "s": 774, "text": "Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris..." }, { "code": null, "e": 903, "s": 844, "text": "Click on the \"Try it Yourself\" button to see how it works." }, { "code": null, "e": 1015, "s": 903, "text": "Bootstrap 5 is the newest version of Bootstrap; with new components, faster stylesheet and more responsiveness." }, { "code": null, "e": 1159, "s": 1015, "text": "Bootstrap 5 supports the latest, stable releases of all major browsers and \nplatforms. However, Internet Explorer 11 and down is not supported." }, { "code": null, "e": 1288, "s": 1159, "text": "The main differences between Bootstrap 5 and Bootstrap 3 & 4, is that \nBootstrap 5 has switched to JavaScript instead of jQuery." }, { "code": null, "e": 1503, "s": 1288, "text": "Note: Bootstrap 3 and Bootstrap 4 is still supported by the team for critical bugfixes and documentation changes, \nand it is perfectly safe to continue to use them. However, new features will NOT be added to \nthem." }, { "code": null, "e": 1555, "s": 1503, "text": "Use a Bootstrap class to center the following text:" }, { "code": null, "e": 1586, "s": 1555, "text": "<p class=\"\"> Hello World!</p>\n" }, { "code": null, "e": 1605, "s": 1586, "text": "Start the Exercise" }, { "code": null, "e": 1648, "s": 1605, "text": "Test your Bootstrap 5 skills at W3Schools!" }, { "code": null, "e": 1672, "s": 1648, "text": "Start Bootstrap 5 Quiz!" }, { "code": null, "e": 1705, "s": 1672, "text": "We just launchedW3Schools videos" }, { "code": null, "e": 1747, "s": 1705, "text": "Get certifiedby completinga course today!" }, { "code": null, "e": 1854, "s": 1747, "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": 1873, "s": 1854, "text": "help@w3schools.com" } ]
Construct BST from Postorder | Practice | GeeksforGeeks
Given postorder traversal of a Binary Search Tree, you need to construct a BST from postorder traversal. The output will be inorder traversal of the constructed BST. Example 1: Input: 6 1 7 5 50 40 10 Output: 1 5 7 10 40 50 Explanation: Testcase 1: The BST for the given post order traversal is: Thus the inorder traversal of BST is: 1 5 7 10 40 50. Your Task: The task is to complete the function constructTree() which takes an array post[], size as as the argument and returns the root of BST. Expected Time Complexity: O(Height of the BST) Expected Auxiliary Space: O(Height of the BST) Constraints: 1 <= T <= 100 1 <= N <= 100 0 jerry2331 week ago 22 134 37 369 334 304 249 499 190 530 568 747 649 755 754 809 529 891 959 909 873 869 843 Can someone tell me how is this a postorder traversal of a Binary Search Tree? Isn't the first element in a postorder traversal of a BST is the smallest element? 0 linhnvhan1 month ago Node *constructTree (int post[], int size){//code here if (size == 0) return nullptr; stack<Node*> st; Node* root = new Node (post[size - 1]); Node* p = root; st.push (root); for (int i = size - 2; i >= 0; --i) { Node* node = new Node (post[i]); if (post[i] > p->data) { st.push (node); p->right = node; p = node; } else { while (!st.empty() && st.top()->data > post[i]) { p = st.top(); st.pop(); } p->left = node; st.push (node); p = node; } } return root;} 0 cshubham4391 month ago EASY JAVA SOUTION static Node root; public static Node construct(int arr[], int start, int end){ if(start>end) return null; int mid = (start+end)/2; Node node = new Node(arr[mid]); node.left = construct(arr,start,mid-1); node.right = construct(arr,mid+1,end); return node; } public static Node constructTree(int post[],int n) { //Add your code here. java.util.Arrays.sort(post); root = construct(post,0,n-1); return root; 0 jaatgfg111 month ago Node* inorderbst(Node *root1,int v[],int s,int e){ if(s>e){ return NULL; } int mid=(s+e)/2; root1=new Node(v[mid]); root1->left=inorderbst(root1->left,v,s,mid-1); root1->right=inorderbst(root1->right,v,mid+1,e); return root1; }Node *constructTree (int post[], int size){ sort(post,post+size); Node* root=NULL; int s=0; int e=size-1; return inorderbst(root,post,s,e);} 0 aasif23642 months ago Node *helper(int *post , int &postIdx , int key , int minVal , int maxVal){ if(postIdx < 0){ return NULL; } if(key < minVal or key > maxVal){ return NULL; } Node *root= new Node(key); postIdx-=1; if(postIdx >= 0){ root->right=helper(post , postIdx , post[postIdx] , key , maxVal); } if(postIdx >= 0){ root->left=helper(post , postIdx , post[postIdx] , minVal , key); } return root;}Node *constructTree (int post[], int size){ int idx=size-1; return helper(post , idx , post[idx] , INT_MIN , INT_MAX);} 0 sksbgp992 months ago Quick and easy solution....C++ Node * constructT(int post[], int s, int e){ if(s>e) { return NULL; } int m=(s+e)/2; Node * root=new Node(post[m]); root->left=constructT(post, s, m-1); root->right=constructT(post,m+1, e); return root; }Node *constructTree (int post[], int size){//code here sort(post,post+size); Node * root=constructT(post,0,size-1); return root;} +1 akashshuklaaio3 months ago Node *constructTree (int post[], int size){ if(size<=0){ return NULL; } Node* root=new Node(post[size-1]); int i=0; while(i<size-1 && post[size-1]>post[i]){ i++; } root->left=constructTree(post+0,i); root->right=constructTree(post+i,size-i-1); return root; } 0 ileon3 months ago Python class Solution: def constructTree(self,post,n): # code here if len(post) == 0: return post.sort() for x in post: print(x, end=" ") +1 dawsonquadros3 months ago Recursive Solution: Time Taken : 0.0/1.1 Node* Tree(int in[] , int left , int right , int post[] , int lb , int rb){ if(left > right || lb > rb)return NULL; Node* root = new Node(post[rb]); int pivot = left; while(root->data != in[pivot])pivot++; root->left = Tree(in , left , pivot-1 , post , lb , lb+pivot-left-1); root->right = Tree(in , pivot+1 , right , post , lb+pivot-left , rb-1); return root; } Node *constructTree (int post[], int size){ int in[size]; for(int i = 0 ; i < size ; i++){ in[i] = post[i]; } sort(in , in+size); return Tree(in , 0 , size-1 , post , 0 , size-1); } 0 aniketaggarwal123454 months ago class GFG{ public static Node constructTree(int post[],int n) { //Add your code here. idx = n-1; return construct(post , Integer.MIN_VALUE , Integer.MAX_VALUE); } static int idx; public static Node construct(int[] post , int min , int max) { if(idx < 0 || post[idx] < min || post[idx]> max) { return null; } int val = post[idx]; Node node = new Node(val); idx--; node.right = construct(post , val + 1 , max); node.left = construct(post , min , val - 1); return node; }} 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": 404, "s": 238, "text": "Given postorder traversal of a Binary Search Tree, you need to construct a BST from postorder traversal. The output will be inorder traversal of the constructed BST." }, { "code": null, "e": 417, "s": 406, "text": "Example 1:" }, { "code": null, "e": 594, "s": 417, "text": "Input:\n6\n1 7 5 50 40 10\n\nOutput:\n1 5 7 10 40 50\n\nExplanation:\nTestcase 1: The BST for the given post order traversal is:\n\n\nThus the inorder traversal of BST is: 1 5 7 10 40 50." }, { "code": null, "e": 743, "s": 596, "text": "Your Task:\nThe task is to complete the function constructTree() which takes an array post[], size as as the argument and returns the root of BST. " }, { "code": null, "e": 839, "s": 745, "text": "Expected Time Complexity: O(Height of the BST)\nExpected Auxiliary Space: O(Height of the BST)" }, { "code": null, "e": 882, "s": 841, "text": "Constraints:\n1 <= T <= 100\n1 <= N <= 100" }, { "code": null, "e": 884, "s": 882, "text": "0" }, { "code": null, "e": 903, "s": 884, "text": "jerry2331 week ago" }, { "code": null, "e": 907, "s": 903, "text": "22 " }, { "code": null, "e": 995, "s": 907, "text": "134 37 369 334 304 249 499 190 530 568 747 649 755 754 809 529 891 959 909 873 869 843 " }, { "code": null, "e": 1159, "s": 997, "text": "Can someone tell me how is this a postorder traversal of a Binary Search Tree? Isn't the first element in a postorder traversal of a BST is the smallest element?" }, { "code": null, "e": 1161, "s": 1159, "text": "0" }, { "code": null, "e": 1182, "s": 1161, "text": "linhnvhan1 month ago" }, { "code": null, "e": 1801, "s": 1182, "text": "Node *constructTree (int post[], int size){//code here if (size == 0) return nullptr; stack<Node*> st; Node* root = new Node (post[size - 1]); Node* p = root; st.push (root); for (int i = size - 2; i >= 0; --i) { Node* node = new Node (post[i]); if (post[i] > p->data) { st.push (node); p->right = node; p = node; } else { while (!st.empty() && st.top()->data > post[i]) { p = st.top(); st.pop(); } p->left = node; st.push (node); p = node; } } return root;}" }, { "code": null, "e": 1803, "s": 1801, "text": "0" }, { "code": null, "e": 1826, "s": 1803, "text": "cshubham4391 month ago" }, { "code": null, "e": 2317, "s": 1826, "text": "EASY JAVA SOUTION \nstatic Node root;\npublic static Node construct(int arr[], int start, int end){\n if(start>end)\n return null;\n int mid = (start+end)/2;\n Node node = new Node(arr[mid]);\n node.left = construct(arr,start,mid-1);\n node.right = construct(arr,mid+1,end);\n return node;\n}\n public static Node constructTree(int post[],int n)\n {\n //Add your code here.\n java.util.Arrays.sort(post);\n root = construct(post,0,n-1);\n return root;" }, { "code": null, "e": 2319, "s": 2317, "text": "0" }, { "code": null, "e": 2340, "s": 2319, "text": "jaatgfg111 month ago" }, { "code": null, "e": 2766, "s": 2340, "text": "Node* inorderbst(Node *root1,int v[],int s,int e){ if(s>e){ return NULL; } int mid=(s+e)/2; root1=new Node(v[mid]); root1->left=inorderbst(root1->left,v,s,mid-1); root1->right=inorderbst(root1->right,v,mid+1,e); return root1; }Node *constructTree (int post[], int size){ sort(post,post+size); Node* root=NULL; int s=0; int e=size-1; return inorderbst(root,post,s,e);}" }, { "code": null, "e": 2768, "s": 2766, "text": "0" }, { "code": null, "e": 2790, "s": 2768, "text": "aasif23642 months ago" }, { "code": null, "e": 3354, "s": 2790, "text": "Node *helper(int *post , int &postIdx , int key , int minVal , int maxVal){ if(postIdx < 0){ return NULL; } if(key < minVal or key > maxVal){ return NULL; } Node *root= new Node(key); postIdx-=1; if(postIdx >= 0){ root->right=helper(post , postIdx , post[postIdx] , key , maxVal); } if(postIdx >= 0){ root->left=helper(post , postIdx , post[postIdx] , minVal , key); } return root;}Node *constructTree (int post[], int size){ int idx=size-1; return helper(post , idx , post[idx] , INT_MIN , INT_MAX);}" }, { "code": null, "e": 3356, "s": 3354, "text": "0" }, { "code": null, "e": 3377, "s": 3356, "text": "sksbgp992 months ago" }, { "code": null, "e": 3408, "s": 3377, "text": "Quick and easy solution....C++" }, { "code": null, "e": 3769, "s": 3408, "text": "Node * constructT(int post[], int s, int e){ if(s>e) { return NULL; } int m=(s+e)/2; Node * root=new Node(post[m]); root->left=constructT(post, s, m-1); root->right=constructT(post,m+1, e); return root; }Node *constructTree (int post[], int size){//code here sort(post,post+size); Node * root=constructT(post,0,size-1); return root;}" }, { "code": null, "e": 3772, "s": 3769, "text": "+1" }, { "code": null, "e": 3799, "s": 3772, "text": "akashshuklaaio3 months ago" }, { "code": null, "e": 4100, "s": 3799, "text": "Node *constructTree (int post[], int size){ if(size<=0){ return NULL; } Node* root=new Node(post[size-1]); int i=0; while(i<size-1 && post[size-1]>post[i]){ i++; } root->left=constructTree(post+0,i); root->right=constructTree(post+i,size-i-1); return root; }" }, { "code": null, "e": 4102, "s": 4100, "text": "0" }, { "code": null, "e": 4120, "s": 4102, "text": "ileon3 months ago" }, { "code": null, "e": 4127, "s": 4120, "text": "Python" }, { "code": null, "e": 4317, "s": 4129, "text": "class Solution:\n \n def constructTree(self,post,n):\n # code here\n if len(post) == 0:\n return\n post.sort()\n for x in post:\n print(x, end=\" \")" }, { "code": null, "e": 4320, "s": 4317, "text": "+1" }, { "code": null, "e": 4346, "s": 4320, "text": "dawsonquadros3 months ago" }, { "code": null, "e": 4366, "s": 4346, "text": "Recursive Solution:" }, { "code": null, "e": 4387, "s": 4366, "text": "Time Taken : 0.0/1.1" }, { "code": null, "e": 5004, "s": 4387, "text": "Node* Tree(int in[] , int left , int right , int post[] , int lb , int rb){\n if(left > right || lb > rb)return NULL;\n Node* root = new Node(post[rb]);\n \n int pivot = left;\n while(root->data != in[pivot])pivot++;\n \n root->left = Tree(in , left , pivot-1 , post , lb , lb+pivot-left-1);\n root->right = Tree(in , pivot+1 , right , post , lb+pivot-left , rb-1);\n \n return root;\n}\n\nNode *constructTree (int post[], int size){\n int in[size];\n for(int i = 0 ; i < size ; i++){\n in[i] = post[i];\n }\n sort(in , in+size);\n return Tree(in , 0 , size-1 , post , 0 , size-1);\n}" }, { "code": null, "e": 5006, "s": 5004, "text": "0" }, { "code": null, "e": 5038, "s": 5006, "text": "aniketaggarwal123454 months ago" }, { "code": null, "e": 5611, "s": 5038, "text": "class GFG{ public static Node constructTree(int post[],int n) { //Add your code here. idx = n-1; return construct(post , Integer.MIN_VALUE , Integer.MAX_VALUE); } static int idx; public static Node construct(int[] post , int min , int max) { if(idx < 0 || post[idx] < min || post[idx]> max) { return null; } int val = post[idx]; Node node = new Node(val); idx--; node.right = construct(post , val + 1 , max); node.left = construct(post , min , val - 1); return node; }}" }, { "code": null, "e": 5757, "s": 5611, "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": 5793, "s": 5757, "text": " Login to access your submissions. " }, { "code": null, "e": 5803, "s": 5793, "text": "\nProblem\n" }, { "code": null, "e": 5813, "s": 5803, "text": "\nContest\n" }, { "code": null, "e": 5876, "s": 5813, "text": "Reset the IDE using the second button on the top right corner." }, { "code": null, "e": 6024, "s": 5876, "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": 6232, "s": 6024, "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": 6338, "s": 6232, "text": "You can access the hints to get an idea about what is expected of you as well as the final solution code." } ]
C# program to find maximum and minimum element in an array
Set the minimum and maximum element to the first element so that you can compare all the elements. For maximum. if(arr[i]>max) { max = arr[i]; } For minimum. if(arr[i]<min) { min = arr[i]; } You can try to run the following code to find maximum and minimum elements’ position. Live Demo using System; public class Demo { public static void Main() { int[] arr = new int[5] {99, 95, 93, 89, 87}; int i, max, min, n; // size of the array n = 5; max = arr[0]; min = arr[0]; for(i=1; i<n; i++) { if(arr[i]>max) { max = arr[i]; } if(arr[i]<min) { min = arr[i]; } } Console.Write("Maximum element = {0}\n", max); Console.Write("Minimum element = {0}\n\n", min); } } Maximum element = 99 Minimum element = 87
[ { "code": null, "e": 1161, "s": 1062, "text": "Set the minimum and maximum element to the first element so that you can compare all the elements." }, { "code": null, "e": 1174, "s": 1161, "text": "For maximum." }, { "code": null, "e": 1210, "s": 1174, "text": "if(arr[i]>max) {\n max = arr[i];\n}" }, { "code": null, "e": 1223, "s": 1210, "text": "For minimum." }, { "code": null, "e": 1259, "s": 1223, "text": "if(arr[i]<min) {\n min = arr[i];\n}" }, { "code": null, "e": 1345, "s": 1259, "text": "You can try to run the following code to find maximum and minimum elements’ position." }, { "code": null, "e": 1356, "s": 1345, "text": " Live Demo" }, { "code": null, "e": 1854, "s": 1356, "text": "using System;\npublic class Demo {\n public static void Main() {\n int[] arr = new int[5] {99, 95, 93, 89, 87};\n int i, max, min, n;\n // size of the array\n n = 5;\n max = arr[0];\n min = arr[0];\n for(i=1; i<n; i++) {\n if(arr[i]>max) {\n max = arr[i];\n }\n if(arr[i]<min) {\n min = arr[i];\n }\n }\n Console.Write(\"Maximum element = {0}\\n\", max);\n Console.Write(\"Minimum element = {0}\\n\\n\", min);\n }\n}" }, { "code": null, "e": 1896, "s": 1854, "text": "Maximum element = 99\nMinimum element = 87" } ]
Print all repeating adjacent pairs in sorted order from an array
01 Feb, 2021 Given an array arr[] consisting of N integers, the task is to print all adjacent integer pairs from the array which appears more than once in the given array. If the array contains more than one such pair, print all pairs in sorted order. Examples: Input: arr[] = {1, 2, 5, 1, 2}Output:1 2Explanation:1 2 is the only repeating integer pair in the array. Input: arr[] = {1, 2, 3, 4, 1, 2, 3, 4, 1, 2}Output:1 22 33 44 1Explanation:Since the array has more than one repeating pair, all the pairs are printed in the sorted order. Approach: The simplest approach is to traverse the array and store every adjacent pair in a Map. Print all such pairs having frequency greater than 1. Follow the steps below to solve the problem: Create a Map M to store all adjacent pairs in an array.Traverse the given array and store every adjacent pair in the Map M.After the above step, traverse the map, and if the frequency of any pair is at least one, then insert it into a vector V.Sort the vector v in ascending order and print all the pairs stored in it. Create a Map M to store all adjacent pairs in an array. Traverse the given array and store every adjacent pair in the Map M. After the above step, traverse the map, and if the frequency of any pair is at least one, then insert it into a vector V. Sort the vector v in ascending order and print all the pairs stored in it. Below is the implementation of the above approach: C++ Java Python3 // C++ program for the above approach #include <bits/stdc++.h>using namespace std; // Function to print adjacent pairs// in sorted ordervoid repeated_pairs(int arr[], int N){ // Store the frequency of all // the adjacent pairs map<pair<int, int>, int> m; // Stores the resultant pairs vector<pair<int, int> > v; int i, j; // Stores the count of all // adjacent pairs for (i = 0; i < N - 1; i++) { pair<int, int> p = { arr[i], arr[i + 1] }; // Increment the count of pair m[p]++; } // Store pairs that appears more // than once for (auto i = m.begin(); i != m.end(); i++) { // If frequency is at least 1 if (i->second > 1) { pair<int, int> p = i->first; // Insert pair into vector v.push_back(p); } } // Sort the vector sort(v.begin(), v.end()); // Print the pairs for (i = 0; i < v.size(); i++) { pair<int, int> p = v[i]; // Print the pair cout << p.first << " " << p.second << endl; }} // Driver Codeint main(){ // Given arr[] int arr[] = { 1, 2, 3, 4, 1, 2, 3, 4, 1, 2 }; int N = sizeof(arr) / sizeof(arr[0]); // Function call repeated_pairs(arr, N); return 0;} // Java code of above approachimport java.util.*;import java.lang.*; class pair{ int first, second; pair(int f, int s) { this.first = f; this.second = s; } @Override public boolean equals(Object obj) { // if both the object references are // referring to the same object. if(this == obj) return true; if(obj == null || obj.getClass() != this.getClass()) return false; // type casting of the argument. pair p = (pair) obj; return (p.first == this.first && p.second == this.second); } @Override public int hashCode() { return this.first + this.second/2; }}class GFG { // Function to print adjacent pairs // in sorted order static void repeated_pairs(int arr[], int N) { // Store the frequency of all // the adjacent pairs Map<pair, Integer> m=new HashMap<>(); // Stores the resultant pairs ArrayList<pair> v = new ArrayList<>(); int i, j; // Stores the count of all // adjacent pairs for (i = 0; i < N - 1; i++) { pair p = new pair(arr[i], arr[i + 1]); // Increment the count of pair m.put(p,m.getOrDefault(p, 0) + 1); } // Store pairs that appears more // than once for (Map.Entry<pair,Integer> k: m.entrySet()) { // If frequency is at least if (k.getValue() > 1) { // Insert pair into vector v.add(k.getKey()); } } // Sort the vector Collections.sort(v, (a, b)->a.first-b.first); // Print the pairs for (pair k:v) { // Print the pair System.out.println(k.first + " " + k.second); } } // Driver code public static void main(String[] args) { // Given arr[] int arr[] = { 1, 2, 3, 4, 1, 2, 3, 4, 1, 2 }; int N = arr.length; // Function call repeated_pairs(arr, N); }} // This code is contributed by offbeat # Python3 program for the above approach # Function to print adjacent pairs# in sorted orderdef repeated_pairs(arr, N): # Store the frequency of all # the adjacent pairs m = {} # Stores the resultant pairs v = [] # Stores the count of all # adjacent pairs for i in range(N - 1): p = (arr[i], arr[i + 1]) # Increment the count of pair m[p] = m.get(p, 0) + 1 # Store pairs that appears more # than once for i in m: # If frequency is at least 1 if (m[i] > 1): p = i # Insert pair into vector v.append(p) # Sort the vector v = sorted(v) # Print the pairs for i in range(len(v)): p = v[i] # Print the pair print(p[0], p[1]) # Driver Codeif __name__ == '__main__': # Given arr[] arr = [ 1, 2, 3, 4, 1, 2, 3, 4, 1, 2 ] N = len(arr) # Function call repeated_pairs(arr, N) # This code is contributed by mohit kumar 29 1 2 2 3 3 4 4 1 Time Complexity: O(N*log N)Auxiliary Space: O(N) mohit kumar 29 offbeat cpp-map frequency-counting Hash Arrays Hash Sorting Arrays Hash Sorting Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 28, "s": 0, "text": "\n01 Feb, 2021" }, { "code": null, "e": 267, "s": 28, "text": "Given an array arr[] consisting of N integers, the task is to print all adjacent integer pairs from the array which appears more than once in the given array. If the array contains more than one such pair, print all pairs in sorted order." }, { "code": null, "e": 277, "s": 267, "text": "Examples:" }, { "code": null, "e": 382, "s": 277, "text": "Input: arr[] = {1, 2, 5, 1, 2}Output:1 2Explanation:1 2 is the only repeating integer pair in the array." }, { "code": null, "e": 555, "s": 382, "text": "Input: arr[] = {1, 2, 3, 4, 1, 2, 3, 4, 1, 2}Output:1 22 33 44 1Explanation:Since the array has more than one repeating pair, all the pairs are printed in the sorted order." }, { "code": null, "e": 751, "s": 555, "text": "Approach: The simplest approach is to traverse the array and store every adjacent pair in a Map. Print all such pairs having frequency greater than 1. Follow the steps below to solve the problem:" }, { "code": null, "e": 1070, "s": 751, "text": "Create a Map M to store all adjacent pairs in an array.Traverse the given array and store every adjacent pair in the Map M.After the above step, traverse the map, and if the frequency of any pair is at least one, then insert it into a vector V.Sort the vector v in ascending order and print all the pairs stored in it." }, { "code": null, "e": 1126, "s": 1070, "text": "Create a Map M to store all adjacent pairs in an array." }, { "code": null, "e": 1195, "s": 1126, "text": "Traverse the given array and store every adjacent pair in the Map M." }, { "code": null, "e": 1317, "s": 1195, "text": "After the above step, traverse the map, and if the frequency of any pair is at least one, then insert it into a vector V." }, { "code": null, "e": 1392, "s": 1317, "text": "Sort the vector v in ascending order and print all the pairs stored in it." }, { "code": null, "e": 1443, "s": 1392, "text": "Below is the implementation of the above approach:" }, { "code": null, "e": 1447, "s": 1443, "text": "C++" }, { "code": null, "e": 1452, "s": 1447, "text": "Java" }, { "code": null, "e": 1460, "s": 1452, "text": "Python3" }, { "code": "// C++ program for the above approach #include <bits/stdc++.h>using namespace std; // Function to print adjacent pairs// in sorted ordervoid repeated_pairs(int arr[], int N){ // Store the frequency of all // the adjacent pairs map<pair<int, int>, int> m; // Stores the resultant pairs vector<pair<int, int> > v; int i, j; // Stores the count of all // adjacent pairs for (i = 0; i < N - 1; i++) { pair<int, int> p = { arr[i], arr[i + 1] }; // Increment the count of pair m[p]++; } // Store pairs that appears more // than once for (auto i = m.begin(); i != m.end(); i++) { // If frequency is at least 1 if (i->second > 1) { pair<int, int> p = i->first; // Insert pair into vector v.push_back(p); } } // Sort the vector sort(v.begin(), v.end()); // Print the pairs for (i = 0; i < v.size(); i++) { pair<int, int> p = v[i]; // Print the pair cout << p.first << \" \" << p.second << endl; }} // Driver Codeint main(){ // Given arr[] int arr[] = { 1, 2, 3, 4, 1, 2, 3, 4, 1, 2 }; int N = sizeof(arr) / sizeof(arr[0]); // Function call repeated_pairs(arr, N); return 0;}", "e": 2757, "s": 1460, "text": null }, { "code": "// Java code of above approachimport java.util.*;import java.lang.*; class pair{ int first, second; pair(int f, int s) { this.first = f; this.second = s; } @Override public boolean equals(Object obj) { // if both the object references are // referring to the same object. if(this == obj) return true; if(obj == null || obj.getClass() != this.getClass()) return false; // type casting of the argument. pair p = (pair) obj; return (p.first == this.first && p.second == this.second); } @Override public int hashCode() { return this.first + this.second/2; }}class GFG { // Function to print adjacent pairs // in sorted order static void repeated_pairs(int arr[], int N) { // Store the frequency of all // the adjacent pairs Map<pair, Integer> m=new HashMap<>(); // Stores the resultant pairs ArrayList<pair> v = new ArrayList<>(); int i, j; // Stores the count of all // adjacent pairs for (i = 0; i < N - 1; i++) { pair p = new pair(arr[i], arr[i + 1]); // Increment the count of pair m.put(p,m.getOrDefault(p, 0) + 1); } // Store pairs that appears more // than once for (Map.Entry<pair,Integer> k: m.entrySet()) { // If frequency is at least if (k.getValue() > 1) { // Insert pair into vector v.add(k.getKey()); } } // Sort the vector Collections.sort(v, (a, b)->a.first-b.first); // Print the pairs for (pair k:v) { // Print the pair System.out.println(k.first + \" \" + k.second); } } // Driver code public static void main(String[] args) { // Given arr[] int arr[] = { 1, 2, 3, 4, 1, 2, 3, 4, 1, 2 }; int N = arr.length; // Function call repeated_pairs(arr, N); }} // This code is contributed by offbeat", "e": 4608, "s": 2757, "text": null }, { "code": "# Python3 program for the above approach # Function to print adjacent pairs# in sorted orderdef repeated_pairs(arr, N): # Store the frequency of all # the adjacent pairs m = {} # Stores the resultant pairs v = [] # Stores the count of all # adjacent pairs for i in range(N - 1): p = (arr[i], arr[i + 1]) # Increment the count of pair m[p] = m.get(p, 0) + 1 # Store pairs that appears more # than once for i in m: # If frequency is at least 1 if (m[i] > 1): p = i # Insert pair into vector v.append(p) # Sort the vector v = sorted(v) # Print the pairs for i in range(len(v)): p = v[i] # Print the pair print(p[0], p[1]) # Driver Codeif __name__ == '__main__': # Given arr[] arr = [ 1, 2, 3, 4, 1, 2, 3, 4, 1, 2 ] N = len(arr) # Function call repeated_pairs(arr, N) # This code is contributed by mohit kumar 29", "e": 5618, "s": 4608, "text": null }, { "code": null, "e": 5634, "s": 5618, "text": "1 2\n2 3\n3 4\n4 1" }, { "code": null, "e": 5685, "s": 5636, "text": "Time Complexity: O(N*log N)Auxiliary Space: O(N)" }, { "code": null, "e": 5700, "s": 5685, "text": "mohit kumar 29" }, { "code": null, "e": 5708, "s": 5700, "text": "offbeat" }, { "code": null, "e": 5716, "s": 5708, "text": "cpp-map" }, { "code": null, "e": 5735, "s": 5716, "text": "frequency-counting" }, { "code": null, "e": 5740, "s": 5735, "text": "Hash" }, { "code": null, "e": 5747, "s": 5740, "text": "Arrays" }, { "code": null, "e": 5752, "s": 5747, "text": "Hash" }, { "code": null, "e": 5760, "s": 5752, "text": "Sorting" }, { "code": null, "e": 5767, "s": 5760, "text": "Arrays" }, { "code": null, "e": 5772, "s": 5767, "text": "Hash" }, { "code": null, "e": 5780, "s": 5772, "text": "Sorting" } ]
Python – Count elements in tuple list
27 Dec, 2019 Sometimes, while working with data in form of records, we can have a problem in which we need to find the count of all the records received. This is a very common application that can occur in Data Science domain. Let’s discuss certain ways in which this task can be performed. Method #1 : Using len() + generator expressionThis is the most basic method to achieve solution to this task. In this, we iterate over whole nested lists using generator expression and get the count using len(). # Python3 code to demonstrate working of# Tuple list elements count# using len() + generator expression # initialize list test_list = [(2, 4), (6, 7), (5, 1), (6, 10), (8, 7)] # printing original list print("The original list : " + str(test_list)) # Tuple list elements count# using len() + generator expressiontemp = list((int(j) for i in test_list for j in i))res = len(temp) # printing resultprint("The tuple list elements count : " + str(res)) The original list : [(2, 4), (6, 7), (5, 1), (6, 10), (8, 7)] The tuple list elements count : 10 Method #2 : Using len() + map() + chain.from_iterable()The combination of above methods can also be used to perform this task. In this, the extension of finding count is done by combination of map() and from_iterable(). # Python3 code to demonstrate working of# Tuple list elements count# using len() + map() + chain.from_iterable()from itertools import chain # initialize list test_list = [(2, 4), (6, 7), (5, 1), (6, 10), (8, 7)] # printing original list print("The original list : " + str(test_list)) # Tuple list elements count# using len() + map() + chain.from_iterable()res = len(list(map(int, chain.from_iterable(test_list)))) # printing resultprint("The tuple list elements count : " + str(res)) The original list : [(2, 4), (6, 7), (5, 1), (6, 10), (8, 7)] The tuple list elements count : 10 Python list-programs 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": "\n27 Dec, 2019" }, { "code": null, "e": 306, "s": 28, "text": "Sometimes, while working with data in form of records, we can have a problem in which we need to find the count of all the records received. This is a very common application that can occur in Data Science domain. Let’s discuss certain ways in which this task can be performed." }, { "code": null, "e": 518, "s": 306, "text": "Method #1 : Using len() + generator expressionThis is the most basic method to achieve solution to this task. In this, we iterate over whole nested lists using generator expression and get the count using len()." }, { "code": "# Python3 code to demonstrate working of# Tuple list elements count# using len() + generator expression # initialize list test_list = [(2, 4), (6, 7), (5, 1), (6, 10), (8, 7)] # printing original list print(\"The original list : \" + str(test_list)) # Tuple list elements count# using len() + generator expressiontemp = list((int(j) for i in test_list for j in i))res = len(temp) # printing resultprint(\"The tuple list elements count : \" + str(res))", "e": 970, "s": 518, "text": null }, { "code": null, "e": 1068, "s": 970, "text": "The original list : [(2, 4), (6, 7), (5, 1), (6, 10), (8, 7)]\nThe tuple list elements count : 10\n" }, { "code": null, "e": 1290, "s": 1070, "text": "Method #2 : Using len() + map() + chain.from_iterable()The combination of above methods can also be used to perform this task. In this, the extension of finding count is done by combination of map() and from_iterable()." }, { "code": "# Python3 code to demonstrate working of# Tuple list elements count# using len() + map() + chain.from_iterable()from itertools import chain # initialize list test_list = [(2, 4), (6, 7), (5, 1), (6, 10), (8, 7)] # printing original list print(\"The original list : \" + str(test_list)) # Tuple list elements count# using len() + map() + chain.from_iterable()res = len(list(map(int, chain.from_iterable(test_list)))) # printing resultprint(\"The tuple list elements count : \" + str(res))", "e": 1778, "s": 1290, "text": null }, { "code": null, "e": 1876, "s": 1778, "text": "The original list : [(2, 4), (6, 7), (5, 1), (6, 10), (8, 7)]\nThe tuple list elements count : 10\n" }, { "code": null, "e": 1897, "s": 1876, "text": "Python list-programs" }, { "code": null, "e": 1904, "s": 1897, "text": "Python" }, { "code": null, "e": 1920, "s": 1904, "text": "Python Programs" } ]
JavaScript | Split a string with multiple separators
26 Jul, 2021 Given a statement which contains the string and separators, the task is to split the string into substring.String split() Method: The str.split() function is used to split the given string into array of strings by separating it into substrings using a specified separator provided in the argument. Syntax: str.split(separator, limit) Parameters: This function accepts three parameters as mentioned above and described below: str: This parameter holds the string to be split. separator: It is optional parameter. It defines the character or the regular expression to use for breaking the string. If not used, the same string is returned (single item array). limit: It is optional parameter. It is an integer which specifies the number of splits. All the items after limit are discarded. Array join() function: The Array.join() function is used to join the elements of the array together into a string. This method adds the elements of an array into a string and returns the newly created string. The elements separates by a specific separator. Default separator used is comma (, ). Syntax: array.join(separator) Parameters: This function accepts two parameters as mentioned above and described below: array: The array to be joined. separator: It is optional parameter. It specifies the separator to be used. If not passes, the default separator comma is used. Example 1: This example splits a string by 2 separators Comma(, ) and space(‘ ‘) using .split() function. html <!DOCTYPE html><html> <head> <title> JavaScript | Split a string with multiple separators. </title> </head> <body style = "text-align:center;" id = "body"> <h1 style = "color:green;" > GeeksForGeeks </h1> <p id="GFG_UP" style="font-size:18px; font-weight:bold;"></p> <button onclick = "gfg_Run()"> split </button> <p id="GFG_DOWN" style="font-size:25px; font-weight:bold;"></p> <script> var el_up = document.getElementById("GFG_UP"); var el_down = document.getElementById("GFG_DOWN"); var str = "A, computer science, portal!"; el_up.innerHTML = str; function gfg_Run() { var arr = str.split(/[\s, ]+/) el_down.innerHTML = arr; } </script> </body></html> Output: Before clicking on the button: After clicking on the button: Example 2: This example split the string by number of separators like Comma(, ), equal(=) and colon(:) using multiple .join() and .split() method. html <!DOCTYPE html><html> <head> <title> JavaScript | Split a string with multiple separators. </title> </head> <body style = "text-align:center;" id = "body"> <h1 style = "color:green;" > GeeksForGeeks </h1> <p id = "GFG_UP" style = "font-size: 18px; font-weight: bold;"> </p> <button onclick = "gfg_Run()"> split </button> <p id = "GFG_DOWN" style = "font-size: 25px; font-weight: bold;"> </p> <script> var el_up = document.getElementById("GFG_UP"); var el_down = document.getElementById("GFG_DOWN"); var str = "A, computer=science:portal!"; el_up.innerHTML = str; function gfg_Run(){ var arr = str.split('=').join(', ').split(':').join(', ').split(', '); el_down.innerHTML = arr; } </script> </body></html> Output: Before clicking on the button: After clicking on the button: manikarora059 JavaScript Web Technologies Web technologies Questions Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 28, "s": 0, "text": "\n26 Jul, 2021" }, { "code": null, "e": 327, "s": 28, "text": "Given a statement which contains the string and separators, the task is to split the string into substring.String split() Method: The str.split() function is used to split the given string into array of strings by separating it into substrings using a specified separator provided in the argument. " }, { "code": null, "e": 337, "s": 327, "text": "Syntax: " }, { "code": null, "e": 365, "s": 337, "text": "str.split(separator, limit)" }, { "code": null, "e": 457, "s": 365, "text": "Parameters: This function accepts three parameters as mentioned above and described below: " }, { "code": null, "e": 507, "s": 457, "text": "str: This parameter holds the string to be split." }, { "code": null, "e": 689, "s": 507, "text": "separator: It is optional parameter. It defines the character or the regular expression to use for breaking the string. If not used, the same string is returned (single item array)." }, { "code": null, "e": 818, "s": 689, "text": "limit: It is optional parameter. It is an integer which specifies the number of splits. All the items after limit are discarded." }, { "code": null, "e": 1114, "s": 818, "text": "Array join() function: The Array.join() function is used to join the elements of the array together into a string. This method adds the elements of an array into a string and returns the newly created string. The elements separates by a specific separator. Default separator used is comma (, ). " }, { "code": null, "e": 1123, "s": 1114, "text": "Syntax: " }, { "code": null, "e": 1145, "s": 1123, "text": "array.join(separator)" }, { "code": null, "e": 1235, "s": 1145, "text": "Parameters: This function accepts two parameters as mentioned above and described below: " }, { "code": null, "e": 1266, "s": 1235, "text": "array: The array to be joined." }, { "code": null, "e": 1394, "s": 1266, "text": "separator: It is optional parameter. It specifies the separator to be used. If not passes, the default separator comma is used." }, { "code": null, "e": 1501, "s": 1394, "text": "Example 1: This example splits a string by 2 separators Comma(, ) and space(‘ ‘) using .split() function. " }, { "code": null, "e": 1506, "s": 1501, "text": "html" }, { "code": "<!DOCTYPE html><html> <head> <title> JavaScript | Split a string with multiple separators. </title> </head> <body style = \"text-align:center;\" id = \"body\"> <h1 style = \"color:green;\" > GeeksForGeeks </h1> <p id=\"GFG_UP\" style=\"font-size:18px; font-weight:bold;\"></p> <button onclick = \"gfg_Run()\"> split </button> <p id=\"GFG_DOWN\" style=\"font-size:25px; font-weight:bold;\"></p> <script> var el_up = document.getElementById(\"GFG_UP\"); var el_down = document.getElementById(\"GFG_DOWN\"); var str = \"A, computer science, portal!\"; el_up.innerHTML = str; function gfg_Run() { var arr = str.split(/[\\s, ]+/) el_down.innerHTML = arr; } </script> </body></html> ", "e": 2471, "s": 1506, "text": null }, { "code": null, "e": 2481, "s": 2471, "text": "Output: " }, { "code": null, "e": 2514, "s": 2481, "text": "Before clicking on the button: " }, { "code": null, "e": 2546, "s": 2514, "text": "After clicking on the button: " }, { "code": null, "e": 2695, "s": 2546, "text": "Example 2: This example split the string by number of separators like Comma(, ), equal(=) and colon(:) using multiple .join() and .split() method. " }, { "code": null, "e": 2700, "s": 2695, "text": "html" }, { "code": "<!DOCTYPE html><html> <head> <title> JavaScript | Split a string with multiple separators. </title> </head> <body style = \"text-align:center;\" id = \"body\"> <h1 style = \"color:green;\" > GeeksForGeeks </h1> <p id = \"GFG_UP\" style = \"font-size: 18px; font-weight: bold;\"> </p> <button onclick = \"gfg_Run()\"> split </button> <p id = \"GFG_DOWN\" style = \"font-size: 25px; font-weight: bold;\"> </p> <script> var el_up = document.getElementById(\"GFG_UP\"); var el_down = document.getElementById(\"GFG_DOWN\"); var str = \"A, computer=science:portal!\"; el_up.innerHTML = str; function gfg_Run(){ var arr = str.split('=').join(', ').split(':').join(', ').split(', '); el_down.innerHTML = arr; } </script> </body></html> ", "e": 3758, "s": 2700, "text": null }, { "code": null, "e": 3768, "s": 3758, "text": "Output: " }, { "code": null, "e": 3801, "s": 3768, "text": "Before clicking on the button: " }, { "code": null, "e": 3833, "s": 3801, "text": "After clicking on the button: " }, { "code": null, "e": 3847, "s": 3833, "text": "manikarora059" }, { "code": null, "e": 3858, "s": 3847, "text": "JavaScript" }, { "code": null, "e": 3875, "s": 3858, "text": "Web Technologies" }, { "code": null, "e": 3902, "s": 3875, "text": "Web technologies Questions" } ]
What does double underscore (__) in front of a variable in Node.js ?
09 Jul, 2021 In this article, we will see what does double underscore (__) in front of a variable in Node.js. NodeJS is primarily used for non-blocking, event-driven servers, due to its single-threaded nature. It is used for traditional websites and back-end API services but was designed with real-time, push-based architectures in mind. Prerequisite: You can learn how to install Nodejs from from here. Double underscore (__) in front of a variable is a convention. It is used for global variable (The following variables may appear to be global but are not, rather local to each module) in Nodejs meanwhile Underscore(_) used to define private variable. There were only two variables in (called global objects) with double underscores in Node. js. __dirname: The __dirname in a node script returns the path of the folder where the current JavaScript file resides. __filename: The __filename in the Node.js returns the filename of the code which is executed. It gives the absolute path of the code filename. 1. Underscore(_) – Private Variable Below is example of private variable. Javascript (function() { // Define two variable var _b = 456; var _a = 123; console.log("a =",_a); // => 123 console.log("b =",_b);})(); Output: a = 123 b = 456 2. Double underscore (__) – Global Variable. Below is example of both the variable The __dirname is an environment variable that tells you the absolute path of the directory containing the currently executing file. Syntax: console.log(__dirname) Return Value: It returns the absolute directory name of the current module. Example 1: Create a JavaScript file app.js and write down the following code. app.js // Node.js code to demonstrate the absolute// file name of the current Module.console.log("Directory Name of the current file is: ", __dirname); Output: C:\Users\Pallavi\Desktop\NODEJS PROJECTS\NodeJS-Projects\Express_Session The __filename in the Node.js returns the filename of the code that is executed. It gives the absolute path of the code file. The following approach covers how to implement __filename in the NodeJS project. Syntax: console.log(__filename) Return Value: It returns the absolute filename of the current module. Example 2: Create a JavaScript file app.js and write down the following code. Javascript // Node.js code to demonstrate the absolute// file name of the current Module.console.log("Filename of the current file is: ", __filename); Output: C:\Users\Pallavi\Desktop\NODEJS PROJECTS\NodeJS-Projects\Express_Session\app.js Reference: https://nodejs.org/api/globals.html#globals_filename Node.js-Methods NodeJS-Questions Picked Node.js Web Technologies Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. JWT Authentication with Node.js Installation of Node.js on Windows Difference between dependencies, devDependencies and peerDependencies Mongoose Populate() Method How to connect Node.js with React.js ? 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 ? Remove elements from a JavaScript Array
[ { "code": null, "e": 54, "s": 26, "text": "\n09 Jul, 2021" }, { "code": null, "e": 151, "s": 54, "text": "In this article, we will see what does double underscore (__) in front of a variable in Node.js." }, { "code": null, "e": 380, "s": 151, "text": "NodeJS is primarily used for non-blocking, event-driven servers, due to its single-threaded nature. It is used for traditional websites and back-end API services but was designed with real-time, push-based architectures in mind." }, { "code": null, "e": 446, "s": 380, "text": "Prerequisite: You can learn how to install Nodejs from from here." }, { "code": null, "e": 698, "s": 446, "text": "Double underscore (__) in front of a variable is a convention. It is used for global variable (The following variables may appear to be global but are not, rather local to each module) in Nodejs meanwhile Underscore(_) used to define private variable." }, { "code": null, "e": 794, "s": 700, "text": "There were only two variables in (called global objects) with double underscores in Node. js." }, { "code": null, "e": 911, "s": 794, "text": " __dirname: The __dirname in a node script returns the path of the folder where the current JavaScript file resides." }, { "code": null, "e": 1054, "s": 911, "text": "__filename: The __filename in the Node.js returns the filename of the code which is executed. It gives the absolute path of the code filename." }, { "code": null, "e": 1090, "s": 1054, "text": "1. Underscore(_) – Private Variable" }, { "code": null, "e": 1128, "s": 1090, "text": "Below is example of private variable." }, { "code": null, "e": 1139, "s": 1128, "text": "Javascript" }, { "code": "(function() { // Define two variable var _b = 456; var _a = 123; console.log(\"a =\",_a); // => 123 console.log(\"b =\",_b);})();", "e": 1284, "s": 1139, "text": null }, { "code": null, "e": 1292, "s": 1284, "text": "Output:" }, { "code": null, "e": 1308, "s": 1292, "text": "a = 123\nb = 456" }, { "code": null, "e": 1353, "s": 1308, "text": "2. Double underscore (__) – Global Variable." }, { "code": null, "e": 1391, "s": 1353, "text": "Below is example of both the variable" }, { "code": null, "e": 1523, "s": 1391, "text": "The __dirname is an environment variable that tells you the absolute path of the directory containing the currently executing file." }, { "code": null, "e": 1531, "s": 1523, "text": "Syntax:" }, { "code": null, "e": 1554, "s": 1531, "text": "console.log(__dirname)" }, { "code": null, "e": 1630, "s": 1554, "text": "Return Value: It returns the absolute directory name of the current module." }, { "code": null, "e": 1708, "s": 1630, "text": "Example 1: Create a JavaScript file app.js and write down the following code." }, { "code": null, "e": 1715, "s": 1708, "text": "app.js" }, { "code": "// Node.js code to demonstrate the absolute// file name of the current Module.console.log(\"Directory Name of the current file is: \", __dirname);", "e": 1863, "s": 1715, "text": null }, { "code": null, "e": 1871, "s": 1863, "text": "Output:" }, { "code": null, "e": 1944, "s": 1871, "text": "C:\\Users\\Pallavi\\Desktop\\NODEJS PROJECTS\\NodeJS-Projects\\Express_Session" }, { "code": null, "e": 2151, "s": 1944, "text": "The __filename in the Node.js returns the filename of the code that is executed. It gives the absolute path of the code file. The following approach covers how to implement __filename in the NodeJS project." }, { "code": null, "e": 2159, "s": 2151, "text": "Syntax:" }, { "code": null, "e": 2183, "s": 2159, "text": "console.log(__filename)" }, { "code": null, "e": 2253, "s": 2183, "text": "Return Value: It returns the absolute filename of the current module." }, { "code": null, "e": 2331, "s": 2253, "text": "Example 2: Create a JavaScript file app.js and write down the following code." }, { "code": null, "e": 2342, "s": 2331, "text": "Javascript" }, { "code": "// Node.js code to demonstrate the absolute// file name of the current Module.console.log(\"Filename of the current file is: \", __filename);", "e": 2485, "s": 2342, "text": null }, { "code": null, "e": 2493, "s": 2485, "text": "Output:" }, { "code": null, "e": 2573, "s": 2493, "text": "C:\\Users\\Pallavi\\Desktop\\NODEJS PROJECTS\\NodeJS-Projects\\Express_Session\\app.js" }, { "code": null, "e": 2637, "s": 2573, "text": "Reference: https://nodejs.org/api/globals.html#globals_filename" }, { "code": null, "e": 2653, "s": 2637, "text": "Node.js-Methods" }, { "code": null, "e": 2670, "s": 2653, "text": "NodeJS-Questions" }, { "code": null, "e": 2677, "s": 2670, "text": "Picked" }, { "code": null, "e": 2685, "s": 2677, "text": "Node.js" }, { "code": null, "e": 2702, "s": 2685, "text": "Web Technologies" }, { "code": null, "e": 2800, "s": 2702, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 2832, "s": 2800, "text": "JWT Authentication with Node.js" }, { "code": null, "e": 2867, "s": 2832, "text": "Installation of Node.js on Windows" }, { "code": null, "e": 2937, "s": 2867, "text": "Difference between dependencies, devDependencies and peerDependencies" }, { "code": null, "e": 2964, "s": 2937, "text": "Mongoose Populate() Method" }, { "code": null, "e": 3003, "s": 2964, "text": "How to connect Node.js with React.js ?" }, { "code": null, "e": 3065, "s": 3003, "text": "Top 10 Projects For Beginners To Practice HTML and CSS Skills" }, { "code": null, "e": 3126, "s": 3065, "text": "Difference between var, let and const keywords in JavaScript" }, { "code": null, "e": 3176, "s": 3126, "text": "How to insert spaces/tabs in text using HTML/CSS?" }, { "code": null, "e": 3219, "s": 3176, "text": "How to fetch data from an API in ReactJS ?" } ]
Combining DataFrames with Pandas
11 Dec, 2020 Pandas DataFrame consists of three principal components, the data, rows, and columns. To combine these DataFrames, pandas provides multiple functions like concat() and append(). Method #1: Using concat() method Initially, creating two datasets and converting them into dataframes. Python3 # import required moduleimport pandas as pd # making a datasetdata1 = { 'Serial_No.': ['1', '2', '3', '4', '5'], 'First': ['F0', 'F1', 'F2', 'F3', 'F4'], 'Second': ['S0', 'S1', 'S2', 'S3', 'S4'],} # creating a dataframedf1 = pd.DataFrame(data1, columns=['Serial_No.', 'First', 'Second']) # display dataframedf1 # making a datasetdata2 = { 'Serial_No.': ['6', '7', '8', '9', '10'], 'First': ['F10', 'F11', 'F12', 'F13', 'F14'], 'Second': ['S10', 'S11', 'S12', 'S13', 'S14'],} # creating a datasetdf2 = pd.DataFrame(data2, columns=['Serial_No.', 'First', 'Second']) # display datasetdf2 Output: Now, concatenating the two dataframes, we will use concat() to combine two dataframes. If ignore_index = True the index of df will be in a continuous order. Python3 # combining the two dataframesdf = pd.concat([df1, df2], ignore_index=True) # display combined dataframesdf Output: Using keys we can specify the labels of the dataframes. Python3 # we can also separate 2 datasets using keysframes = [df1, df2]df_keys = pd.concat(frames, keys=['x', 'y']) # display dataframedf_keys Output: Method #2: Using append() method Initially, creating two datasets and converting them into dataframes. Python3 # import required moduleimport pandas as pd # making a datasetdata1 = { 'Serial_No.': ['1', '2', '3', '4', '5'], 'First': ['F0', 'F1', 'F2', 'F3', 'F4'], 'Second': ['S0', 'S1', 'S2', 'S3', 'S4'],} # creating a dataframedf1 = pd.DataFrame(data1, columns=['Serial_No.', 'First', 'Second']) # display dataframedf1 # making a datasetdata2 = { 'Serial_No.': ['6', '7', '8', '9', '10'], 'First': ['F10', 'F11', 'F12', 'F13', 'F14'], 'Second': ['S10', 'S11', 'S12', 'S13', 'S14'],} # creating a datasetdf2 = pd.DataFrame(data2, columns=['Serial_No.', 'First', 'Second']) # display datasetdf2 Output: The dataframe.append() method performs the operation of combining two dataframes similar to that of the contcat() method. Python3 # combining dataframesresult = df1.append(df2, sort=False, ignore_index=True) # display combined dataframeresult Output: Python pandas-dataFrame Python-pandas Python Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 28, "s": 0, "text": "\n11 Dec, 2020" }, { "code": null, "e": 206, "s": 28, "text": "Pandas DataFrame consists of three principal components, the data, rows, and columns. To combine these DataFrames, pandas provides multiple functions like concat() and append()." }, { "code": null, "e": 239, "s": 206, "text": "Method #1: Using concat() method" }, { "code": null, "e": 310, "s": 239, "text": "Initially, creating two datasets and converting them into dataframes. " }, { "code": null, "e": 318, "s": 310, "text": "Python3" }, { "code": "# import required moduleimport pandas as pd # making a datasetdata1 = { 'Serial_No.': ['1', '2', '3', '4', '5'], 'First': ['F0', 'F1', 'F2', 'F3', 'F4'], 'Second': ['S0', 'S1', 'S2', 'S3', 'S4'],} # creating a dataframedf1 = pd.DataFrame(data1, columns=['Serial_No.', 'First', 'Second']) # display dataframedf1 # making a datasetdata2 = { 'Serial_No.': ['6', '7', '8', '9', '10'], 'First': ['F10', 'F11', 'F12', 'F13', 'F14'], 'Second': ['S10', 'S11', 'S12', 'S13', 'S14'],} # creating a datasetdf2 = pd.DataFrame(data2, columns=['Serial_No.', 'First', 'Second']) # display datasetdf2", "e": 1072, "s": 318, "text": null }, { "code": null, "e": 1081, "s": 1072, "text": "Output: " }, { "code": null, "e": 1239, "s": 1081, "text": "Now, concatenating the two dataframes, we will use concat() to combine two dataframes. If ignore_index = True the index of df will be in a continuous order. " }, { "code": null, "e": 1247, "s": 1239, "text": "Python3" }, { "code": "# combining the two dataframesdf = pd.concat([df1, df2], ignore_index=True) # display combined dataframesdf", "e": 1356, "s": 1247, "text": null }, { "code": null, "e": 1364, "s": 1356, "text": "Output:" }, { "code": null, "e": 1420, "s": 1364, "text": "Using keys we can specify the labels of the dataframes." }, { "code": null, "e": 1428, "s": 1420, "text": "Python3" }, { "code": "# we can also separate 2 datasets using keysframes = [df1, df2]df_keys = pd.concat(frames, keys=['x', 'y']) # display dataframedf_keys", "e": 1564, "s": 1428, "text": null }, { "code": null, "e": 1572, "s": 1564, "text": "Output:" }, { "code": null, "e": 1605, "s": 1572, "text": "Method #2: Using append() method" }, { "code": null, "e": 1676, "s": 1605, "text": "Initially, creating two datasets and converting them into dataframes. " }, { "code": null, "e": 1684, "s": 1676, "text": "Python3" }, { "code": "# import required moduleimport pandas as pd # making a datasetdata1 = { 'Serial_No.': ['1', '2', '3', '4', '5'], 'First': ['F0', 'F1', 'F2', 'F3', 'F4'], 'Second': ['S0', 'S1', 'S2', 'S3', 'S4'],} # creating a dataframedf1 = pd.DataFrame(data1, columns=['Serial_No.', 'First', 'Second']) # display dataframedf1 # making a datasetdata2 = { 'Serial_No.': ['6', '7', '8', '9', '10'], 'First': ['F10', 'F11', 'F12', 'F13', 'F14'], 'Second': ['S10', 'S11', 'S12', 'S13', 'S14'],} # creating a datasetdf2 = pd.DataFrame(data2, columns=['Serial_No.', 'First', 'Second']) # display datasetdf2", "e": 2438, "s": 1684, "text": null }, { "code": null, "e": 2447, "s": 2438, "text": "Output: " }, { "code": null, "e": 2569, "s": 2447, "text": "The dataframe.append() method performs the operation of combining two dataframes similar to that of the contcat() method." }, { "code": null, "e": 2577, "s": 2569, "text": "Python3" }, { "code": "# combining dataframesresult = df1.append(df2, sort=False, ignore_index=True) # display combined dataframeresult", "e": 2691, "s": 2577, "text": null }, { "code": null, "e": 2699, "s": 2691, "text": "Output:" }, { "code": null, "e": 2723, "s": 2699, "text": "Python pandas-dataFrame" }, { "code": null, "e": 2737, "s": 2723, "text": "Python-pandas" }, { "code": null, "e": 2744, "s": 2737, "text": "Python" } ]
How to Fill (initialize at once) an Array in Java? - GeeksforGeeks
04 Feb, 2022 An array is a group of like-typed variables that are referred to by a common name. An array can contain primitives (int, char, etc.) as well as the object (or non-primitive) references of a class depending on the definition of the array. In the case of primitive data types, the actual values are stored in contiguous memory locations. In the case of objects of a class, the actual objects are stored in the heap segment. There are six ways to fill an array in Java. They are as follows: Using for loop to fill the valueDeclare them at the time of the creationUsing Arrays.fill()Using Arrays.copyOf()Using Arrays.setAll()Using ArrayUtils.clone() Using for loop to fill the value Declare them at the time of the creation Using Arrays.fill() Using Arrays.copyOf() Using Arrays.setAll() Using ArrayUtils.clone() In this method, we run the empty array through the loop and place the value at each position. This is mostly used in programming as it helps the coder to place the desired value at each position. Java // Java program to fill the element in an arrayimport java.util.*; public class Gfg { // Main function public static void main(String args[]) throws Exception { // Array Declaration int array[] = new int[10]; // Adding elements in the array for (int i = 0; i < array.length; i++) { array[i] = i + 1; } // Printing the elements for (int i = 0; i < array.length; i++) { System.out.print(array[i] + " "); } }} 1 2 3 4 5 6 7 8 9 10 In this method, we declare the elements of the array at the time of the creation itself. Java // Java program to fill the element in an arrayimport java.util.*; public class GFG{ // Main function public static void main(String args[]) throws Exception { // Array Declaration with elements int array[] = { 1, 2, 3, 4, 5 }; // Printing the elements for (int i = 0; i < array.length; i++) { // Printing Elements System.out.print(array[i] + " "); } }} 1 2 3 4 5 java.util.Arrays.fill() method is in java.util.Arrays class. This method assigns the specified data type value to each element of the specified range of the specified array. You can learn more about from this article. Java // Java program to fill the element in an arrayimport java.util.*; public class Gfg { // Main function public static void main(String args[]) throws Exception { // Empty Array Declaration int array[] = new int[10]; // Filling the data Arrays.fill(array, 10); // Printing the data System.out.println("Array completely filled with 10\n" + Arrays.toString(array)); }} Array completely filled with 10 [10, 10, 10, 10, 10, 10, 10, 10, 10, 10] java.util.Arrays.copyOf() method is in java.util.Arrays class. It copies the specified array, truncating or padding with false (if necessary) so the copy has the specified length. You can learn more about from this article. Java // Java program to illustrate copyOf when new array// is of higher length.import java.util.Arrays; public class Gfg {public static void main(String args[]) { // initializing an array original int[] org = new int[] {1, 2 ,3}; System.out.println("Original Array : \n"); for (int i = 0; i < org.length; i++) System.out.print(org[i] + " "); // copying array org to copy // Here, new array has 5 elements - two // elements more than the original array int[] copy = Arrays.copyOf(org, 5); System.out.print("\New array copy (of higher length):\n"); for (int i = 0; i < copy.length; i++) System.out.print(copy[i] + " "); }} Original Array: 1 2 3 New array copy (of higher length): 1 2 3 0 0 It set all the element in the specified array in by the function which compute each element. You can learn more about from this article. Java // Java program to illustrate setAll to set valueimport java.util.Arrays; public class Gfg { // Main functionpublic static void main(String args[]) { // initializing an array int[] array = new int[10]; // Setting the value in the array Arrays.setAll(array, p -> p > 9 ? 0 : p); // Printing the array System.out.println("Array completely filled: \n" + Arrays.toString(array)); }} Array completely filled: [0, 1, 2, 3, 4, 5, 6, 7, 8, 9] The Java.util.ArrayList.clone() method is used to create a shallow copy of the mentioned array list. It just creates a copy of the list. You can learn more about from this article. Java // Java code to illustrate clone() method import java.io.*;import java.util.ArrayList; public class ArrayListDemo { public static void main(String args[]) { // Creating an empty ArrayList ArrayList<String> list = new ArrayList<String>(); // Use add() method // to add elements in the list list.add("Geeks"); list.add("for"); list.add("Geeks"); list.add("10"); list.add("20"); // Displaying the list System.out.println("First ArrayList: " + list); // Creating another linked list and copying ArrayList sec_list = new ArrayList(); sec_list = (ArrayList)list.clone(); // Displaying the other linked list System.out.println("Second ArrayList is: " + sec_list); }} First ArrayList: [Geeks, for, Geeks, 10, 20] Second ArrayList is: [Geeks, for, Geeks, 10, 20] sumitgumber28 Java-Array-Programs Java Java Programs Java Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments Constructors in Java Stream In Java Exceptions in Java Different ways of Reading a text file in Java Functional Interfaces in Java Convert a String to Character array in Java Java Programming Examples Convert Double to Integer in Java Implementing a Linked List in Java using Class How to Iterate HashMap in Java?
[ { "code": null, "e": 23868, "s": 23840, "text": "\n04 Feb, 2022" }, { "code": null, "e": 24356, "s": 23868, "text": "An array is a group of like-typed variables that are referred to by a common name. An array can contain primitives (int, char, etc.) as well as the object (or non-primitive) references of a class depending on the definition of the array. In the case of primitive data types, the actual values are stored in contiguous memory locations. In the case of objects of a class, the actual objects are stored in the heap segment. There are six ways to fill an array in Java. They are as follows:" }, { "code": null, "e": 24514, "s": 24356, "text": "Using for loop to fill the valueDeclare them at the time of the creationUsing Arrays.fill()Using Arrays.copyOf()Using Arrays.setAll()Using ArrayUtils.clone()" }, { "code": null, "e": 24547, "s": 24514, "text": "Using for loop to fill the value" }, { "code": null, "e": 24588, "s": 24547, "text": "Declare them at the time of the creation" }, { "code": null, "e": 24608, "s": 24588, "text": "Using Arrays.fill()" }, { "code": null, "e": 24630, "s": 24608, "text": "Using Arrays.copyOf()" }, { "code": null, "e": 24652, "s": 24630, "text": "Using Arrays.setAll()" }, { "code": null, "e": 24677, "s": 24652, "text": "Using ArrayUtils.clone()" }, { "code": null, "e": 24873, "s": 24677, "text": "In this method, we run the empty array through the loop and place the value at each position. This is mostly used in programming as it helps the coder to place the desired value at each position." }, { "code": null, "e": 24878, "s": 24873, "text": "Java" }, { "code": "// Java program to fill the element in an arrayimport java.util.*; public class Gfg { // Main function public static void main(String args[]) throws Exception { // Array Declaration int array[] = new int[10]; // Adding elements in the array for (int i = 0; i < array.length; i++) { array[i] = i + 1; } // Printing the elements for (int i = 0; i < array.length; i++) { System.out.print(array[i] + \" \"); } }}", "e": 25420, "s": 24878, "text": null }, { "code": null, "e": 25444, "s": 25423, "text": "1 2 3 4 5 6 7 8 9 10" }, { "code": null, "e": 25533, "s": 25444, "text": "In this method, we declare the elements of the array at the time of the creation itself." }, { "code": null, "e": 25542, "s": 25537, "text": "Java" }, { "code": "// Java program to fill the element in an arrayimport java.util.*; public class GFG{ // Main function public static void main(String args[]) throws Exception { // Array Declaration with elements int array[] = { 1, 2, 3, 4, 5 }; // Printing the elements for (int i = 0; i < array.length; i++) { // Printing Elements System.out.print(array[i] + \" \"); } }}", "e": 25994, "s": 25542, "text": null }, { "code": null, "e": 26007, "s": 25997, "text": "1 2 3 4 5" }, { "code": null, "e": 26225, "s": 26007, "text": "java.util.Arrays.fill() method is in java.util.Arrays class. This method assigns the specified data type value to each element of the specified range of the specified array. You can learn more about from this article." }, { "code": null, "e": 26234, "s": 26229, "text": "Java" }, { "code": "// Java program to fill the element in an arrayimport java.util.*; public class Gfg { // Main function public static void main(String args[]) throws Exception { // Empty Array Declaration int array[] = new int[10]; // Filling the data Arrays.fill(array, 10); // Printing the data System.out.println(\"Array completely filled with 10\\n\" + Arrays.toString(array)); }}", "e": 26708, "s": 26234, "text": null }, { "code": null, "e": 26784, "s": 26711, "text": "Array completely filled with 10\n[10, 10, 10, 10, 10, 10, 10, 10, 10, 10]" }, { "code": null, "e": 27008, "s": 26784, "text": "java.util.Arrays.copyOf() method is in java.util.Arrays class. It copies the specified array, truncating or padding with false (if necessary) so the copy has the specified length. You can learn more about from this article." }, { "code": null, "e": 27017, "s": 27012, "text": "Java" }, { "code": "// Java program to illustrate copyOf when new array// is of higher length.import java.util.Arrays; public class Gfg {public static void main(String args[]) { // initializing an array original int[] org = new int[] {1, 2 ,3}; System.out.println(\"Original Array : \\n\"); for (int i = 0; i < org.length; i++) System.out.print(org[i] + \" \"); // copying array org to copy // Here, new array has 5 elements - two // elements more than the original array int[] copy = Arrays.copyOf(org, 5); System.out.print(\"\\New array copy (of higher length):\\n\"); for (int i = 0; i < copy.length; i++) System.out.print(copy[i] + \" \"); }}", "e": 27701, "s": 27017, "text": null }, { "code": null, "e": 27772, "s": 27704, "text": "Original Array:\n1 2 3 \nNew array copy (of higher length):\n1 2 3 0 0" }, { "code": null, "e": 27909, "s": 27772, "text": "It set all the element in the specified array in by the function which compute each element. You can learn more about from this article." }, { "code": null, "e": 27918, "s": 27913, "text": "Java" }, { "code": "// Java program to illustrate setAll to set valueimport java.util.Arrays; public class Gfg { // Main functionpublic static void main(String args[]) { // initializing an array int[] array = new int[10]; // Setting the value in the array Arrays.setAll(array, p -> p > 9 ? 0 : p); // Printing the array System.out.println(\"Array completely filled: \\n\" + Arrays.toString(array)); }}", "e": 28355, "s": 27918, "text": null }, { "code": null, "e": 28415, "s": 28358, "text": "Array completely filled: \n[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]" }, { "code": null, "e": 28596, "s": 28415, "text": "The Java.util.ArrayList.clone() method is used to create a shallow copy of the mentioned array list. It just creates a copy of the list. You can learn more about from this article." }, { "code": null, "e": 28605, "s": 28600, "text": "Java" }, { "code": "// Java code to illustrate clone() method import java.io.*;import java.util.ArrayList; public class ArrayListDemo { public static void main(String args[]) { // Creating an empty ArrayList ArrayList<String> list = new ArrayList<String>(); // Use add() method // to add elements in the list list.add(\"Geeks\"); list.add(\"for\"); list.add(\"Geeks\"); list.add(\"10\"); list.add(\"20\"); // Displaying the list System.out.println(\"First ArrayList: \" + list); // Creating another linked list and copying ArrayList sec_list = new ArrayList(); sec_list = (ArrayList)list.clone(); // Displaying the other linked list System.out.println(\"Second ArrayList is: \" + sec_list); }}", "e": 29449, "s": 28605, "text": null }, { "code": null, "e": 29543, "s": 29449, "text": "First ArrayList: [Geeks, for, Geeks, 10, 20]\nSecond ArrayList is: [Geeks, for, Geeks, 10, 20]" }, { "code": null, "e": 29557, "s": 29543, "text": "sumitgumber28" }, { "code": null, "e": 29577, "s": 29557, "text": "Java-Array-Programs" }, { "code": null, "e": 29582, "s": 29577, "text": "Java" }, { "code": null, "e": 29596, "s": 29582, "text": "Java Programs" }, { "code": null, "e": 29601, "s": 29596, "text": "Java" }, { "code": null, "e": 29699, "s": 29601, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 29708, "s": 29699, "text": "Comments" }, { "code": null, "e": 29721, "s": 29708, "text": "Old Comments" }, { "code": null, "e": 29742, "s": 29721, "text": "Constructors in Java" }, { "code": null, "e": 29757, "s": 29742, "text": "Stream In Java" }, { "code": null, "e": 29776, "s": 29757, "text": "Exceptions in Java" }, { "code": null, "e": 29822, "s": 29776, "text": "Different ways of Reading a text file in Java" }, { "code": null, "e": 29852, "s": 29822, "text": "Functional Interfaces in Java" }, { "code": null, "e": 29896, "s": 29852, "text": "Convert a String to Character array in Java" }, { "code": null, "e": 29922, "s": 29896, "text": "Java Programming Examples" }, { "code": null, "e": 29956, "s": 29922, "text": "Convert Double to Integer in Java" }, { "code": null, "e": 30003, "s": 29956, "text": "Implementing a Linked List in Java using Class" } ]
What is the difference between g++ and gcc?
GNU C++ Compiler ( g++ ) is a compiler in Linux which is used to compile C++ programs. It compiles both files with extension .c and .cpp as C++ files. The following is the compiler command to compile C++ program. g++ program.cpp -o filename Here, filename − The name of file with .c or .cpp extension. The following is an example of using g++ compiler. Live Demo #include <iostream> using namespace std; int main() { int a = 20; cout << "The value of a : " << a; return 0; } $g++ -o main *.cpp $main The value of a : 20 GNU C Compiler ( gcc ) is a compiler in Linux which is used to compile C programs. It compiles files with extension “.c”. The following is the compiler command to compile C program. gcc program.c -o filename Here, filename − The name of file with .c extension. The following is an example of using gcc compiler. Live Demo #include <stdio.h> int main() { int a = 20; printf("The value of a : %d", a); return 0; } $gcc -o main *.c $main The value of a : 20
[ { "code": null, "e": 1213, "s": 1062, "text": "GNU C++ Compiler ( g++ ) is a compiler in Linux which is used to compile C++ programs. It compiles both files with extension .c and .cpp as C++ files." }, { "code": null, "e": 1275, "s": 1213, "text": "The following is the compiler command to compile C++ program." }, { "code": null, "e": 1303, "s": 1275, "text": "g++ program.cpp -o filename" }, { "code": null, "e": 1309, "s": 1303, "text": "Here," }, { "code": null, "e": 1364, "s": 1309, "text": "filename − The name of file with .c or .cpp extension." }, { "code": null, "e": 1415, "s": 1364, "text": "The following is an example of using g++ compiler." }, { "code": null, "e": 1426, "s": 1415, "text": " Live Demo" }, { "code": null, "e": 1547, "s": 1426, "text": "#include <iostream>\nusing namespace std;\nint main() {\n int a = 20;\n cout << \"The value of a : \" << a;\n return 0;\n}" }, { "code": null, "e": 1592, "s": 1547, "text": "$g++ -o main *.cpp\n$main\nThe value of a : 20" }, { "code": null, "e": 1714, "s": 1592, "text": "GNU C Compiler ( gcc ) is a compiler in Linux which is used to compile C programs. It compiles files with extension “.c”." }, { "code": null, "e": 1774, "s": 1714, "text": "The following is the compiler command to compile C program." }, { "code": null, "e": 1800, "s": 1774, "text": "gcc program.c -o filename" }, { "code": null, "e": 1806, "s": 1800, "text": "Here," }, { "code": null, "e": 1853, "s": 1806, "text": "filename − The name of file with .c extension." }, { "code": null, "e": 1904, "s": 1853, "text": "The following is an example of using gcc compiler." }, { "code": null, "e": 1915, "s": 1904, "text": " Live Demo" }, { "code": null, "e": 2014, "s": 1915, "text": "#include <stdio.h>\nint main() {\n int a = 20;\n printf(\"The value of a : %d\", a);\n return 0;\n}" }, { "code": null, "e": 2057, "s": 2014, "text": "$gcc -o main *.c\n$main\nThe value of a : 20" } ]
How to convert Java array or ArrayList to JsonArray using Gson in Java?
The Java Arrays are objects which store multiple variables of the same type, it holds primitive types and object references and an ArrayList can represent a resizable list of objects. We can add, remove, find, sort and replace elements using the list. A JsonArray can parse text from a string to produce a vector-like object. We can convert an array or ArrayList to JsonArray using the toJsonTree().getAsJsonArray() method of Gson class. public JsonElement toJsonTree(java.lang.Object src) import com.google.gson.*; import java.util.*; public class JavaArrayToJsonArrayTest { public static void main(String args[]) { String[][] strArray = {{"elem1-1", "elem1-2"}, {"elem2-1", "elem2-2"}}; ArrayList<ArrayList<String>> arrayList = new ArrayList<>(); for(int i = 0; i < strArray.length; i++) { ArrayList<String> nextElement = new ArrayList<>(); for(int j = 0; j < strArray[i].length; j++) { nextElement.add(strArray[i][j] + "-B"); } arrayList.add(nextElement); } JsonObject jsonObj = new JsonObject(); // array to JsonArray JsonArray jsonArray1 = new Gson().toJsonTree(strArray).getAsJsonArray(); // ArrayList to JsonArray JsonArray jsonArray2 = new Gson().toJsonTree(arrayList).getAsJsonArray(); jsonObj.add("jsonArray1", jsonArray1); jsonObj.add("jsonArray2", jsonArray2); System.out.println(jsonObj.toString()); } } {"jsonArray1":[["elem1-1","elem1-2"],["elem2-1","elem2-2"]],"jsonArray2":[["elem1-1-B","elem1-2-B"],["elem2-1-B","elem2-2-B"]]}
[ { "code": null, "e": 1500, "s": 1062, "text": "The Java Arrays are objects which store multiple variables of the same type, it holds primitive types and object references and an ArrayList can represent a resizable list of objects. We can add, remove, find, sort and replace elements using the list. A JsonArray can parse text from a string to produce a vector-like object. We can convert an array or ArrayList to JsonArray using the toJsonTree().getAsJsonArray() method of Gson class." }, { "code": null, "e": 1552, "s": 1500, "text": "public JsonElement toJsonTree(java.lang.Object src)" }, { "code": null, "e": 2505, "s": 1552, "text": "import com.google.gson.*;\nimport java.util.*;\npublic class JavaArrayToJsonArrayTest {\n public static void main(String args[]) {\n String[][] strArray = {{\"elem1-1\", \"elem1-2\"}, {\"elem2-1\", \"elem2-2\"}};\n ArrayList<ArrayList<String>> arrayList = new ArrayList<>();\n for(int i = 0; i < strArray.length; i++) {\n ArrayList<String> nextElement = new ArrayList<>();\n for(int j = 0; j < strArray[i].length; j++) {\n nextElement.add(strArray[i][j] + \"-B\");\n }\n arrayList.add(nextElement);\n }\n JsonObject jsonObj = new JsonObject();\n // array to JsonArray\n JsonArray jsonArray1 = new Gson().toJsonTree(strArray).getAsJsonArray();\n // ArrayList to JsonArray\n JsonArray jsonArray2 = new Gson().toJsonTree(arrayList).getAsJsonArray();\n jsonObj.add(\"jsonArray1\", jsonArray1);\n jsonObj.add(\"jsonArray2\", jsonArray2);\n System.out.println(jsonObj.toString());\n }\n}" }, { "code": null, "e": 2633, "s": 2505, "text": "{\"jsonArray1\":[[\"elem1-1\",\"elem1-2\"],[\"elem2-1\",\"elem2-2\"]],\"jsonArray2\":[[\"elem1-1-B\",\"elem1-2-B\"],[\"elem2-1-B\",\"elem2-2-B\"]]}" } ]
Java Internalization - Date Format Patterns
Followings is the use of characters in date formatting patterns. G To display Era. y To display Year. Valid values yy, yyyy. M To display Month. Valid values MM, MMM or MMMMM. d To display day of month. Valid values d, dd. h To display hour of day (1-12 AM/PM). Valid value hh. H To display hour of day (0-23). Valid value HH. m To display minute of hour (0-59). Valid value mm. s To display second of minute (0-59). Valid value ss. S To display milliseconds of minute (0-999). Valid value SSS. E To display Day in week (e.g Monday, Tuesday etc.) D To display Day in year (1-366). F To display Day of week in month (e.g. 1st Thursday of December). w To display Week in year (1-53). W To display Week in month (0-5) a To display AM / PM k To display Hour in day (1-24). K To display Hour in day, AM / PM (0-11). z To display Time Zone. In this example, we're formatting dates based on different patterns. IOTester.java import java.text.ParseException; import java.text.SimpleDateFormat; import java.util.Date; public class I18NTester { public static void main(String[] args) throws ParseException { String pattern = "dd-MM-yy"; SimpleDateFormat simpleDateFormat = new SimpleDateFormat(pattern); Date date = new Date(); System.out.println(simpleDateFormat.format(date)); pattern = "MM-dd-yyyy"; simpleDateFormat = new SimpleDateFormat(pattern); System.out.println(simpleDateFormat.format(date)); pattern = "yyyy-MM-dd HH:mm:ss"; simpleDateFormat = new SimpleDateFormat(pattern); System.out.println(simpleDateFormat.format(date)); pattern = "EEEEE MMMMM yyyy HH:mm:ss.SSSZ"; simpleDateFormat = new SimpleDateFormat(pattern); System.out.println(simpleDateFormat.format(date)); } } It will print the following result. 29-11-17 11-29-2017 2017-11-29 18:47:42 Wednesday November 2017 18:47:42.787+0530 16 Lectures 2 hours Malhar Lathkar 19 Lectures 5 hours Malhar Lathkar 25 Lectures 2.5 hours Anadi Sharma 126 Lectures 7 hours Tushar Kale 119 Lectures 17.5 hours Monica Mittal 76 Lectures 7 hours Arnab Chakraborty Print Add Notes Bookmark this page
[ { "code": null, "e": 2770, "s": 2705, "text": "Followings is the use of characters in date formatting patterns." }, { "code": null, "e": 2772, "s": 2770, "text": "G" }, { "code": null, "e": 2788, "s": 2772, "text": "To display Era." }, { "code": null, "e": 2790, "s": 2788, "text": "y" }, { "code": null, "e": 2830, "s": 2790, "text": "To display Year. Valid values yy, yyyy." }, { "code": null, "e": 2832, "s": 2830, "text": "M" }, { "code": null, "e": 2881, "s": 2832, "text": "To display Month. Valid values MM, MMM or MMMMM." }, { "code": null, "e": 2883, "s": 2881, "text": "d" }, { "code": null, "e": 2928, "s": 2883, "text": "To display day of month. Valid values d, dd." }, { "code": null, "e": 2930, "s": 2928, "text": "h" }, { "code": null, "e": 2983, "s": 2930, "text": "To display hour of day (1-12 AM/PM). Valid value hh." }, { "code": null, "e": 2985, "s": 2983, "text": "H" }, { "code": null, "e": 3032, "s": 2985, "text": "To display hour of day (0-23). Valid value HH." }, { "code": null, "e": 3034, "s": 3032, "text": "m" }, { "code": null, "e": 3084, "s": 3034, "text": "To display minute of hour (0-59). Valid value mm." }, { "code": null, "e": 3086, "s": 3084, "text": "s" }, { "code": null, "e": 3138, "s": 3086, "text": "To display second of minute (0-59). Valid value ss." }, { "code": null, "e": 3140, "s": 3138, "text": "S" }, { "code": null, "e": 3200, "s": 3140, "text": "To display milliseconds of minute (0-999). Valid value SSS." }, { "code": null, "e": 3202, "s": 3200, "text": "E" }, { "code": null, "e": 3252, "s": 3202, "text": "To display Day in week (e.g Monday, Tuesday etc.)" }, { "code": null, "e": 3254, "s": 3252, "text": "D" }, { "code": null, "e": 3286, "s": 3254, "text": "To display Day in year (1-366)." }, { "code": null, "e": 3288, "s": 3286, "text": "F" }, { "code": null, "e": 3353, "s": 3288, "text": "To display Day of week in month (e.g. 1st Thursday of December)." }, { "code": null, "e": 3355, "s": 3353, "text": "w" }, { "code": null, "e": 3387, "s": 3355, "text": "To display Week in year (1-53)." }, { "code": null, "e": 3389, "s": 3387, "text": "W" }, { "code": null, "e": 3420, "s": 3389, "text": "To display Week in month (0-5)" }, { "code": null, "e": 3422, "s": 3420, "text": "a" }, { "code": null, "e": 3441, "s": 3422, "text": "To display AM / PM" }, { "code": null, "e": 3443, "s": 3441, "text": "k" }, { "code": null, "e": 3474, "s": 3443, "text": "To display Hour in day (1-24)." }, { "code": null, "e": 3476, "s": 3474, "text": "K" }, { "code": null, "e": 3516, "s": 3476, "text": "To display Hour in day, AM / PM (0-11)." }, { "code": null, "e": 3518, "s": 3516, "text": "z" }, { "code": null, "e": 3540, "s": 3518, "text": "To display Time Zone." }, { "code": null, "e": 3609, "s": 3540, "text": "In this example, we're formatting dates based on different patterns." }, { "code": null, "e": 3623, "s": 3609, "text": "IOTester.java" }, { "code": null, "e": 4468, "s": 3623, "text": "import java.text.ParseException;\nimport java.text.SimpleDateFormat;\nimport java.util.Date;\n\npublic class I18NTester {\n public static void main(String[] args) throws ParseException {\n\n String pattern = \"dd-MM-yy\";\n SimpleDateFormat simpleDateFormat = new SimpleDateFormat(pattern);\n Date date = new Date();\n System.out.println(simpleDateFormat.format(date));\n\n pattern = \"MM-dd-yyyy\";\n simpleDateFormat = new SimpleDateFormat(pattern);\n System.out.println(simpleDateFormat.format(date));\n\n pattern = \"yyyy-MM-dd HH:mm:ss\";\n simpleDateFormat = new SimpleDateFormat(pattern);\n System.out.println(simpleDateFormat.format(date));\n\n pattern = \"EEEEE MMMMM yyyy HH:mm:ss.SSSZ\";\n simpleDateFormat = new SimpleDateFormat(pattern);\n System.out.println(simpleDateFormat.format(date));\n}\n}" }, { "code": null, "e": 4504, "s": 4468, "text": "It will print the following result." }, { "code": null, "e": 4587, "s": 4504, "text": "29-11-17\n11-29-2017\n2017-11-29 18:47:42\nWednesday November 2017 18:47:42.787+0530\n" }, { "code": null, "e": 4620, "s": 4587, "text": "\n 16 Lectures \n 2 hours \n" }, { "code": null, "e": 4636, "s": 4620, "text": " Malhar Lathkar" }, { "code": null, "e": 4669, "s": 4636, "text": "\n 19 Lectures \n 5 hours \n" }, { "code": null, "e": 4685, "s": 4669, "text": " Malhar Lathkar" }, { "code": null, "e": 4720, "s": 4685, "text": "\n 25 Lectures \n 2.5 hours \n" }, { "code": null, "e": 4734, "s": 4720, "text": " Anadi Sharma" }, { "code": null, "e": 4768, "s": 4734, "text": "\n 126 Lectures \n 7 hours \n" }, { "code": null, "e": 4782, "s": 4768, "text": " Tushar Kale" }, { "code": null, "e": 4819, "s": 4782, "text": "\n 119 Lectures \n 17.5 hours \n" }, { "code": null, "e": 4834, "s": 4819, "text": " Monica Mittal" }, { "code": null, "e": 4867, "s": 4834, "text": "\n 76 Lectures \n 7 hours \n" }, { "code": null, "e": 4886, "s": 4867, "text": " Arnab Chakraborty" }, { "code": null, "e": 4893, "s": 4886, "text": " Print" }, { "code": null, "e": 4904, "s": 4893, "text": " Add Notes" } ]
Count possible decoding of a given digit sequence with hidden characters - GeeksforGeeks
27 Sep, 2021 Given a string S containing digits and character ‘*’ i.e. hidden character, the task is to find the number of ways to decode this hidden character of the given string. Since the answer may be very large, return it modulo 109+7. A string containing letters from A-Z can be encoded into numbers using the following mapping: ‘A’ -> “1” ‘B’ -> “2” ‘C’ -> “3” ‘D’ -> “4” ... ... ‘Z’ -> “26” Note: Characters including 0 are not included in the problem like (J → 10). Examples: Input: s = “*”Output: 9Explanation: The encoded message can represent any of the encoded messages “1”, “2”, “3”, “4”, “5”, “6”, “7”, “8”, or “9”.Each of these can be decoded to the strings “A”, “B”, “C”, “D”, “E”, “F”, “G”, “H”, and “I” respectively.Hence, there are a total of 9 ways to decode “*”. Input: s = “1*”Output: 18Explanation: The encoded message can represent any of the encoded messages “11”, “12”, “13”, “14”, “15”, “16”, “17”, “18”, or “19”.Each of these encoded messages have 2 ways to be decoded (e.g. “11” can be decoded to “AA” or “K”).Hence, there are a total of 9 × 2 = 18 ways to decode “1*”. Approach: This problem can be solved by observing that any constant number can be either decoded in a character which is a single-digit number or it can be decoded into a double-digit number if (i-1)th character is ‘1’ or (i-1)th character is ‘2’ and ith character is between 1 and 6. Therefore, the current state depends on the previous state, and dynamic programming can be used to solve the problem. Follow the steps below to solve the problem: 1. Let dp[i] represent the number of ways to decode the string characters from 0 to i. 2. If the ith character is ‘*’ : dp[i] = dp[i-1]*9 considering ‘*’ can be 1 to 9, and it is considered alone as a character. Now, if the i and i-1 characters are combined, then,If (i-1)th character is ‘*’ then the two “**” together can form 15 possible characters(like 13 will form character ‘M’), so we add 15×dp[i-2] to dp[i].If (i-1)th character is ‘1’ then dp[i] = dp[i] + 9×dp[i-2] because the possible characters that can be decoded will be 11 to 19(K to S).If (i-1)th character is ‘2’ then dp[i] = dp[i] + 6×dp[i-2] as it can take value from 21 to 26. If (i-1)th character is ‘*’ then the two “**” together can form 15 possible characters(like 13 will form character ‘M’), so we add 15×dp[i-2] to dp[i]. If (i-1)th character is ‘1’ then dp[i] = dp[i] + 9×dp[i-2] because the possible characters that can be decoded will be 11 to 19(K to S). If (i-1)th character is ‘2’ then dp[i] = dp[i] + 6×dp[i-2] as it can take value from 21 to 26. 3. If the ith character is not ‘*’: dp[i] = dp[i] + dp[i-1] considering ith character alone as a number. Now, if it is possible to combine (i-1)th character and ith character together then add dp[i-2] to dp[i]. Below is the implementation of the above approach: C++ Java Python3 C# Javascript #include <bits/stdc++.h>using namespace std; int M = 1000000007;int waysOfDecoding(string s){ vector<int> dp((int)s.size()+1); dp[0] = 1; // check the first character of the string // if it is '*' then 9 ways dp[1] = s[0] == '*' ? 9 : s[0] == '0' ? 0 : 1; // traverse the string for (int i = 1; i < (int)s.size(); i++) { // If s[i] == '*' there can be // 9 possible values of * if (s[i] == '*') { dp[i + 1] = 9 * dp[i]; // If previous character is 1 // then words that can be formed // are K(11), L(12), M(13), N(14) // O(15), P(16), Q(17), R(18), S(19) if (s[i - 1] == '1') dp[i + 1] = (dp[i + 1] + 9 * dp[i - 1]) % M; // If previous character is 2 // then the words that can be formed // are U(21), V(22), W(23), X(24)Y(25), Z(26) else if (s[i - 1] == '2') dp[i + 1] = (dp[i + 1] + 6 * dp[i - 1]) % M; // If the previous digit is * then // all 15 2- digit characters can be // formed else if (s[i - 1] == '*') dp[i + 1] = (dp[i + 1] + 15 * dp[i - 1]) % M; } else { // taking the value from previous step dp[i + 1] = s[i] != '0' ? dp[i] : 0; // If previous character is 1 then // the i-1th character and ith // character can be decoded in // a single character therefore, // adding dp[i-1]. if (s[i - 1] == '1') dp[i + 1] = (dp[i + 1] + dp[i - 1]) % M; // If previous character is 2 // and ith character is less than // 6 // then the i-1th character and // ith character can be decoded in // a single character therefore, // adding dp[i-1]. else if (s[i - 1] == '2' && s[i] <= '6') dp[i + 1] = (dp[i + 1] + dp[i - 1]) % M; // If previous character is * then // it will contain the above 2 cases else if (s[i - 1] == '*') dp[i + 1] = (dp[i + 1] + (s[i] <= '6' ? 2 : 1) * dp[i - 1]) % M; } } return dp[(int)s.size()];} int main(){ string s = "12"; cout<<waysOfDecoding(s); return 0;} // This code is contributed by mohit kumar 29. // Java program for the above approach import java.io.*; class GFG { static int M = 1000000007; static int waysOfDecoding(String s) { long[] dp = new long[s.length() + 1]; dp[0] = 1; // check the first character of the string // if it is '*' then 9 ways dp[1] = s.charAt(0) == '*' ? 9 : s.charAt(0) == '0' ? 0 : 1; // traverse the string for (int i = 1; i < s.length(); i++) { // If s[i] == '*' there can be // 9 possible values of * if (s.charAt(i) == '*') { dp[i + 1] = 9 * dp[i]; // If previous character is 1 // then words that can be formed // are K(11), L(12), M(13), N(14) // O(15), P(16), Q(17), R(18), S(19) if (s.charAt(i - 1) == '1') dp[i + 1] = (dp[i + 1] + 9 * dp[i - 1]) % M; // If previous character is 2 // then the words that can be formed // are U(21), V(22), W(23), X(24)Y(25), Z(26) else if (s.charAt(i - 1) == '2') dp[i + 1] = (dp[i + 1] + 6 * dp[i - 1]) % M; // If the previous digit is * then // all 15 2- digit characters can be // formed else if (s.charAt(i - 1) == '*') dp[i + 1] = (dp[i + 1] + 15 * dp[i - 1]) % M; } else { // taking the value from previous step dp[i + 1] = s.charAt(i) != '0' ? dp[i] : 0; // If previous character is 1 then // the i-1th character and ith // character can be decoded in // a single character therefore, // adding dp[i-1]. if (s.charAt(i - 1) == '1') dp[i + 1] = (dp[i + 1] + dp[i - 1]) % M; // If previous character is 2 // and ith character is less than // 6 // then the i-1th character and // ith character can be decoded in // a single character therefore, // adding dp[i-1]. else if (s.charAt(i - 1) == '2' && s.charAt(i) <= '6') dp[i + 1] = (dp[i + 1] + dp[i - 1]) % M; // If previous character is * then // it will contain the above 2 cases else if (s.charAt(i - 1) == '*') dp[i + 1] = (dp[i + 1] + (s.charAt(i) <= '6' ? 2 : 1) * dp[i - 1]) % M; } } return (int)dp[s.length()]; } public static void main(String[] args) { String s = "12"; System.out.println(waysOfDecoding(s)); }} # Python program for the above approachM = 1000000007def waysOfDecoding(s): dp = [0]*(len(s)+1) dp[0] = 1 # check the first character of the string # if it is '*' then 9 ways if s[0] == '*': dp[1] = 9 elif s[0] == '0': dp[1] = 0 else: dp[1] = 1 # traverse the string for i in range(len(s)): # If s[i] == '*' there can be # 9 possible values of * if (s[i] == '*'): dp[i + 1] = 9 * dp[i] # If previous character is 1 # then words that can be formed # are K(11), L(12), M(13), N(14) # O(15), P(16), Q(17), R(18), S(19) if (s[i - 1] == '1'): dp[i + 1] = (dp[i + 1] + 9 * dp[i - 1]) % M # If previous character is 2 # then the words that can be formed # are U(21), V(22), W(23), X(24)Y(25), Z(26) elif (s[i - 1] == '2'): dp[i + 1] = (dp[i + 1] + 6 * dp[i - 1]) % M # If the previous digit is * then # all 15 2- digit characters can be # formed elif (s[i - 1] == '*'): dp[i + 1] = (dp[i + 1] + 15 * dp[i - 1]) % M else: # taking the value from previous step if s[i] != '0': dp[i+1] = dp[i] else: dp[i+1] = 0 # If previous character is 1 then # the i-1th character and ith # character can be decoded in # a single character therefore, # adding dp[i-1]. if (s[i - 1] == '1'): dp[i + 1] = (dp[i + 1] + dp[i - 1]) % M # If previous character is 2 # and ith character is less than # 6 # then the i-1th character and # ith character can be decoded in # a single character therefore, # adding dp[i-1]. elif (s[i - 1] == '2' and s[i] <= '6'): dp[i + 1] = (dp[i + 1] + dp[i - 1]) % M # If previous character is * then # it will contain the above 2 cases elif (s[i - 1] == '*'): if (s[i] <= '6'): dp[i + 1] = dp[i + 1] + 2 * dp[i - 1] else: dp[i + 1] = dp[i + 1] + 1 * dp[i - 1] dp[i+1] = dp[i+1] % M return dp[len(s)] if __name__ == "__main__": s = "12" print(waysOfDecoding(s)) # This code is contributed by ukasp. // C# program for the above approachusing System; class GFG{ static int M = 1000000007;static int waysOfDecoding(String s){ long[] dp = new long[s.Length + 1]; dp[0] = 1; // Check the first character of the string // if it is '*' then 9 ways dp[1] = s[0] == '*' ? 9 : s[0] == '0' ? 0 : 1; // Traverse the string for(int i = 1; i < s.Length; i++) { // If s[i] == '*' there can be // 9 possible values of * if (s[i] == '*') { dp[i + 1] = 9 * dp[i]; // If previous character is 1 // then words that can be formed // are K(11), L(12), M(13), N(14) // O(15), P(16), Q(17), R(18), S(19) if (s[i - 1] == '1') dp[i + 1] = (dp[i + 1] + 9 * dp[i - 1]) % M; // If previous character is 2 // then the words that can be formed // are U(21), V(22), W(23), X(24)Y(25), // Z(26) else if (s[i - 1] == '2') dp[i + 1] = (dp[i + 1] + 6 * dp[i - 1]) % M; // If the previous digit is * then // all 15 2- digit characters can be // formed else if (s[i - 1] == '*') dp[i + 1] = (dp[i + 1] + 15 * dp[i - 1]) % M; } else { // Taking the value from previous step dp[i + 1] = s[i] != '0' ? dp[i] : 0; // If previous character is 1 then // the i-1th character and ith // character can be decoded in // a single character therefore, // adding dp[i-1]. if (s[i - 1] == '1') dp[i + 1] = (dp[i + 1] + dp[i - 1]) % M; // If previous character is 2 // and ith character is less than // 6 // then the i-1th character and // ith character can be decoded in // a single character therefore, // adding dp[i-1]. else if (s[i - 1] == '2' && s[i] <= '6') dp[i + 1] = (dp[i + 1] + dp[i - 1]) % M; // If previous character is * then // it will contain the above 2 cases else if (s[i - 1] == '*') dp[i + 1] = (dp[i + 1] + (s[i] <= '6' ? 2 : 1) * dp[i - 1]) % M; } } return (int)dp[s.Length];} // Driver codepublic static void Main(){ String s = "12"; Console.WriteLine(waysOfDecoding(s));}} // This code is contributed by rishavmahato348 <script>// Javascript program for the above approach let M = 1000000007;function waysOfDecoding(s){ let dp = new Array(s.length + 1); for(let i=0;i<s.length+1;i++) dp[i] = 0; dp[0] = 1; // check the first character of the string // if it is '*' then 9 ways dp[1] = s[0] == '*' ? 9 : s[0] == '0' ? 0 : 1; // traverse the string for (let i = 1; i < s.length; i++) { // If s[i] == '*' there can be // 9 possible values of * if (s[i] == '*') { dp[i + 1] = 9 * dp[i]; // If previous character is 1 // then words that can be formed // are K(11), L(12), M(13), N(14) // O(15), P(16), Q(17), R(18), S(19) if (s[i-1] == '1') dp[i + 1] = (dp[i + 1] + 9 * dp[i - 1]) % M; // If previous character is 2 // then the words that can be formed // are U(21), V(22), W(23), X(24)Y(25), Z(26) else if (s[i-1] == '2') dp[i + 1] = (dp[i + 1] + 6 * dp[i - 1]) % M; // If the previous digit is * then // all 15 2- digit characters can be // formed else if (s[i-1] == '*') dp[i + 1] = (dp[i + 1] + 15 * dp[i - 1]) % M; } else { // taking the value from previous step dp[i + 1] = s[i] != '0' ? dp[i] : 0; // If previous character is 1 then // the i-1th character and ith // character can be decoded in // a single character therefore, // adding dp[i-1]. if (s[i-1] == '1') dp[i + 1] = (dp[i + 1] + dp[i - 1]) % M; // If previous character is 2 // and ith character is less than // 6 // then the i-1th character and // ith character can be decoded in // a single character therefore, // adding dp[i-1]. else if (s[i-1] == '2' && s[i] <= '6') dp[i + 1] = (dp[i + 1] + dp[i - 1]) % M; // If previous character is * then // it will contain the above 2 cases else if (s[i-1] == '*') dp[i + 1] = (dp[i + 1] + (s[i] <= '6' ? 2 : 1) * dp[i - 1]) % M; } } return dp[s.length];} let s = "12";document.write(waysOfDecoding(s)); // This code is contributed by unknown2108</script> 2 Time complexity: O(n)Auxiliary Space: O(n) Further optimization of space If the above code is observed carefully, it is observed that the value of dp[i] is found using dp[i-1] and dp[i-2]. So to optimize the space further, instead of creating an array of dp of length N, we can use three variables – second(stores the value of dp[i]), first(stores the value of dp[i-2]), and temp(stores the value of dp[i-1]). So after finding the value of the second(dp[i]), modify first = temp and temp = second and then calculate the value again of second(dp[i]) using the variable first and temp. C++ Java C# Javascript // C++ program for the above approach#include <bits/stdc++.h>using namespace std; int M = 1000000007;int waysOfDecoding(string s){ long first = 1, second = s[0] == '*' ? 9 : s[0] == '0' ? 0 : 1; for(int i = 1; i < s.size(); i++) { long temp = second; // If s[i] == '*' there can be // 9 possible values of * if (s[i] == '*') { second = 9 * second; // If previous character is 1 // then words that can be formed // are K(11), L(12), M(13), N(14) // O(15), P(16), Q(17), R(18), S(19) if (s[i - 1] == '1') second = (second + 9 * first) % M; // If previous character is 2 // then the words that can be formed // are U(21), V(22), W(23), X(24)Y(25), Z(26) else if (s[i - 1] == '2') second = (second + 6 * first) % M; // If the previous digit is * then // all 15 2- digit characters can be // formed else if (s[i - 1] == '*') second = (second + 15 * first) % M; } // If s[i] != '*' else { second = s[i] != '0' ? second : 0; // Adding first in second // if s[i-1]=1 if (s[i - 1] == '1') second = (second + first) % M; // Adding first in second if // s[i-1] == 2 and s[i]<='6' else if (s[i - 1] == '2' && s[i] <= '6') second = (second + first) % M; // If s[i-1] == '*' the union // of above 2 cases has to be done else if (s[i - 1] == '*') second = (second + (s[i] <= '6' ? 2 : 1) * first) % M; } first = temp; } return(int)second;} // Driver codeint main(){ string s = "*"; cout << waysOfDecoding(s); return 0;} // This code is contributed by rishavmahato348 // Java program for the above approachimport java.io.*; class GFG { static int M = 1000000007; static int waysOfDecoding(String s) { long first = 1, second = s.charAt(0) == '*' ? 9 : s.charAt(0) == '0' ? 0 : 1; for (int i = 1; i < s.length(); i++) { long temp = second; // If s[i] == '*' there can be // 9 possible values of * if (s.charAt(i) == '*') { second = 9 * second; // If previous character is 1 // then words that can be formed // are K(11), L(12), M(13), N(14) // O(15), P(16), Q(17), R(18), S(19) if (s.charAt(i - 1) == '1') second = (second + 9 * first) % M; // If previous character is 2 // then the words that can be formed // are U(21), V(22), W(23), X(24)Y(25), Z(26) else if (s.charAt(i - 1) == '2') second = (second + 6 * first) % M; // If the previous digit is * then // all 15 2- digit characters can be // formed else if (s.charAt(i - 1) == '*') second = (second + 15 * first) % M; } // If s[i] != '*' else { second = s.charAt(i) != '0' ? second : 0; // Adding first in second // if s[i-1]=1 if (s.charAt(i - 1) == '1') second = (second + first) % M; // Adding first in second if // s[i-1] == 2 and s[i]<='6' else if (s.charAt(i - 1) == '2' && s.charAt(i) <= '6') second = (second + first) % M; // if s[i-1] == '*' the union // of above 2 cases has to be done else if (s.charAt(i - 1) == '*') second = (second + (s.charAt(i) <= '6' ? 2 : 1) * first) % M; } first = temp; } return (int)second; } public static void main(String[] args) { String s = "*"; System.out.println(waysOfDecoding(s)); }} // C# program for the above approachusing System; class GFG{ static int M = 1000000007; static int waysOfDecoding(string s){ long first = 1, second = s[0] == '*' ? 9 : s[0] == '0' ? 0 : 1; for(int i = 1; i < s.Length; i++) { long temp = second; // If s[i] == '*' there can be // 9 possible values of * if (s[i] == '*') { second = 9 * second; // If previous character is 1 // then words that can be formed // are K(11), L(12), M(13), N(14) // O(15), P(16), Q(17), R(18), S(19) if (s[i - 1] == '1') second = (second + 9 * first) % M; // If previous character is 2 // then the words that can be formed // are U(21), V(22), W(23), X(24)Y(25), Z(26) else if (s[i - 1] == '2') second = (second + 6 * first) % M; // If the previous digit is * then // all 15 2- digit characters can be // formed else if (s[i - 1] == '*') second = (second + 15 * first) % M; } // If s[i] != '*' else { second = s[i] != '0' ? second : 0; // Adding first in second // if s[i-1]=1 if (s[i - 1] == '1') second = (second + first) % M; // Adding first in second if // s[i-1] == 2 and s[i]<='6' else if (s[i - 1] == '2' && s[i] <= '6') second = (second + first) % M; // if s[i-1] == '*' the union // of above 2 cases has to be done else if (s[i - 1] == '*') second = (second + (s[i] <= '6' ? 2 : 1) * first) % M; } first = temp; } return (int)second;} // Driver codestatic public void Main(){ string s = "*"; Console.WriteLine(waysOfDecoding(s));}} // This code is contributed by patel2127 <script> // JavaScript program for the above approachlet M = 1000000007; function waysOfDecoding(s){ let first = 1, second = s[0] == '*' ? 9 : s[0] == '0' ? 0 : 1; for(let i = 1; i < s.length; i++) { let temp = second; // If s[i] == '*' there can be // 9 possible values of * if (s[i] == '*') { second = 9 * second; // If previous character is 1 // then words that can be formed // are K(11), L(12), M(13), N(14) // O(15), P(16), Q(17), R(18), S(19) if (s[i - 1] == '1') second = (second + 9 * first) % M; // If previous character is 2 // then the words that can be formed // are U(21), V(22), W(23), X(24)Y(25), Z(26) else if (s[i - 1] == '2') second = (second + 6 * first) % M; // If the previous digit is * then // all 15 2- digit characters can be // formed else if (s[i - 1] == '*') second = (second + 15 * first) % M; } // If s[i] != '*' else { second = s[i] != '0' ? second : 0; // Adding first in second // if s[i-1]=1 if (s[i - 1] == '1') second = (second + first) % M; // Adding first in second if // s[i-1] == 2 and s[i]<='6' else if (s[i - 1] == '2' && s[i] <= '6') second = (second + first) % M; // if s[i-1] == '*' the union // of above 2 cases has to be done else if (s[i - 1] == '*') second = (second + (s[i] <= '6' ? 2 : 1) * first) % M; } first = temp; } return second;} // Driver Codelet s = "*"; document.write(waysOfDecoding(s)); // This code is contributed by code_hunt </script> 9 Time complexity: O(n)Auxiliary Space: O(1) mohit kumar 29 unknown2108 rishavmahato348 patel2127 code_hunt ukasp digit-DP Facebook interview-preparation Dynamic Programming Mathematical Strings Facebook Strings Dynamic Programming Mathematical Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments Optimal Substructure Property in Dynamic Programming | DP-2 Min Cost Path | DP-6 Maximum Subarray Sum using Divide and Conquer algorithm Optimal Binary Search Tree | DP-24 Greedy approach vs Dynamic programming Write a program to print all permutations of a given string C++ Data Types Set in C++ Standard Template Library (STL) Program to find sum of elements in a given array Modulo Operator (%) in C/C++ with Examples
[ { "code": null, "e": 24307, "s": 24279, "text": "\n27 Sep, 2021" }, { "code": null, "e": 24475, "s": 24307, "text": "Given a string S containing digits and character ‘*’ i.e. hidden character, the task is to find the number of ways to decode this hidden character of the given string." }, { "code": null, "e": 24535, "s": 24475, "text": "Since the answer may be very large, return it modulo 109+7." }, { "code": null, "e": 24629, "s": 24535, "text": "A string containing letters from A-Z can be encoded into numbers using the following mapping:" }, { "code": null, "e": 24769, "s": 24629, "text": "‘A’ -> “1” ‘B’ -> “2” ‘C’ -> “3” ‘D’ -> “4” ... ... ‘Z’ -> “26” Note: Characters including 0 are not included in the problem like (J → 10)." }, { "code": null, "e": 24780, "s": 24769, "text": "Examples: " }, { "code": null, "e": 25080, "s": 24780, "text": "Input: s = “*”Output: 9Explanation: The encoded message can represent any of the encoded messages “1”, “2”, “3”, “4”, “5”, “6”, “7”, “8”, or “9”.Each of these can be decoded to the strings “A”, “B”, “C”, “D”, “E”, “F”, “G”, “H”, and “I” respectively.Hence, there are a total of 9 ways to decode “*”." }, { "code": null, "e": 25396, "s": 25080, "text": "Input: s = “1*”Output: 18Explanation: The encoded message can represent any of the encoded messages “11”, “12”, “13”, “14”, “15”, “16”, “17”, “18”, or “19”.Each of these encoded messages have 2 ways to be decoded (e.g. “11” can be decoded to “AA” or “K”).Hence, there are a total of 9 × 2 = 18 ways to decode “1*”. " }, { "code": null, "e": 25407, "s": 25396, "text": "Approach: " }, { "code": null, "e": 25846, "s": 25407, "text": "This problem can be solved by observing that any constant number can be either decoded in a character which is a single-digit number or it can be decoded into a double-digit number if (i-1)th character is ‘1’ or (i-1)th character is ‘2’ and ith character is between 1 and 6. Therefore, the current state depends on the previous state, and dynamic programming can be used to solve the problem. Follow the steps below to solve the problem: " }, { "code": null, "e": 25933, "s": 25846, "text": "1. Let dp[i] represent the number of ways to decode the string characters from 0 to i." }, { "code": null, "e": 25966, "s": 25933, "text": "2. If the ith character is ‘*’ :" }, { "code": null, "e": 26058, "s": 25966, "text": "dp[i] = dp[i-1]*9 considering ‘*’ can be 1 to 9, and it is considered alone as a character." }, { "code": null, "e": 26492, "s": 26058, "text": "Now, if the i and i-1 characters are combined, then,If (i-1)th character is ‘*’ then the two “**” together can form 15 possible characters(like 13 will form character ‘M’), so we add 15×dp[i-2] to dp[i].If (i-1)th character is ‘1’ then dp[i] = dp[i] + 9×dp[i-2] because the possible characters that can be decoded will be 11 to 19(K to S).If (i-1)th character is ‘2’ then dp[i] = dp[i] + 6×dp[i-2] as it can take value from 21 to 26." }, { "code": null, "e": 26644, "s": 26492, "text": "If (i-1)th character is ‘*’ then the two “**” together can form 15 possible characters(like 13 will form character ‘M’), so we add 15×dp[i-2] to dp[i]." }, { "code": null, "e": 26781, "s": 26644, "text": "If (i-1)th character is ‘1’ then dp[i] = dp[i] + 9×dp[i-2] because the possible characters that can be decoded will be 11 to 19(K to S)." }, { "code": null, "e": 26876, "s": 26781, "text": "If (i-1)th character is ‘2’ then dp[i] = dp[i] + 6×dp[i-2] as it can take value from 21 to 26." }, { "code": null, "e": 26912, "s": 26876, "text": "3. If the ith character is not ‘*’:" }, { "code": null, "e": 26981, "s": 26912, "text": "dp[i] = dp[i] + dp[i-1] considering ith character alone as a number." }, { "code": null, "e": 27087, "s": 26981, "text": "Now, if it is possible to combine (i-1)th character and ith character together then add dp[i-2] to dp[i]." }, { "code": null, "e": 27139, "s": 27087, "text": "Below is the implementation of the above approach: " }, { "code": null, "e": 27143, "s": 27139, "text": "C++" }, { "code": null, "e": 27148, "s": 27143, "text": "Java" }, { "code": null, "e": 27156, "s": 27148, "text": "Python3" }, { "code": null, "e": 27159, "s": 27156, "text": "C#" }, { "code": null, "e": 27170, "s": 27159, "text": "Javascript" }, { "code": "#include <bits/stdc++.h>using namespace std; int M = 1000000007;int waysOfDecoding(string s){ vector<int> dp((int)s.size()+1); dp[0] = 1; // check the first character of the string // if it is '*' then 9 ways dp[1] = s[0] == '*' ? 9 : s[0] == '0' ? 0 : 1; // traverse the string for (int i = 1; i < (int)s.size(); i++) { // If s[i] == '*' there can be // 9 possible values of * if (s[i] == '*') { dp[i + 1] = 9 * dp[i]; // If previous character is 1 // then words that can be formed // are K(11), L(12), M(13), N(14) // O(15), P(16), Q(17), R(18), S(19) if (s[i - 1] == '1') dp[i + 1] = (dp[i + 1] + 9 * dp[i - 1]) % M; // If previous character is 2 // then the words that can be formed // are U(21), V(22), W(23), X(24)Y(25), Z(26) else if (s[i - 1] == '2') dp[i + 1] = (dp[i + 1] + 6 * dp[i - 1]) % M; // If the previous digit is * then // all 15 2- digit characters can be // formed else if (s[i - 1] == '*') dp[i + 1] = (dp[i + 1] + 15 * dp[i - 1]) % M; } else { // taking the value from previous step dp[i + 1] = s[i] != '0' ? dp[i] : 0; // If previous character is 1 then // the i-1th character and ith // character can be decoded in // a single character therefore, // adding dp[i-1]. if (s[i - 1] == '1') dp[i + 1] = (dp[i + 1] + dp[i - 1]) % M; // If previous character is 2 // and ith character is less than // 6 // then the i-1th character and // ith character can be decoded in // a single character therefore, // adding dp[i-1]. else if (s[i - 1] == '2' && s[i] <= '6') dp[i + 1] = (dp[i + 1] + dp[i - 1]) % M; // If previous character is * then // it will contain the above 2 cases else if (s[i - 1] == '*') dp[i + 1] = (dp[i + 1] + (s[i] <= '6' ? 2 : 1) * dp[i - 1]) % M; } } return dp[(int)s.size()];} int main(){ string s = \"12\"; cout<<waysOfDecoding(s); return 0;} // This code is contributed by mohit kumar 29.", "e": 29793, "s": 27170, "text": null }, { "code": "// Java program for the above approach import java.io.*; class GFG { static int M = 1000000007; static int waysOfDecoding(String s) { long[] dp = new long[s.length() + 1]; dp[0] = 1; // check the first character of the string // if it is '*' then 9 ways dp[1] = s.charAt(0) == '*' ? 9 : s.charAt(0) == '0' ? 0 : 1; // traverse the string for (int i = 1; i < s.length(); i++) { // If s[i] == '*' there can be // 9 possible values of * if (s.charAt(i) == '*') { dp[i + 1] = 9 * dp[i]; // If previous character is 1 // then words that can be formed // are K(11), L(12), M(13), N(14) // O(15), P(16), Q(17), R(18), S(19) if (s.charAt(i - 1) == '1') dp[i + 1] = (dp[i + 1] + 9 * dp[i - 1]) % M; // If previous character is 2 // then the words that can be formed // are U(21), V(22), W(23), X(24)Y(25), Z(26) else if (s.charAt(i - 1) == '2') dp[i + 1] = (dp[i + 1] + 6 * dp[i - 1]) % M; // If the previous digit is * then // all 15 2- digit characters can be // formed else if (s.charAt(i - 1) == '*') dp[i + 1] = (dp[i + 1] + 15 * dp[i - 1]) % M; } else { // taking the value from previous step dp[i + 1] = s.charAt(i) != '0' ? dp[i] : 0; // If previous character is 1 then // the i-1th character and ith // character can be decoded in // a single character therefore, // adding dp[i-1]. if (s.charAt(i - 1) == '1') dp[i + 1] = (dp[i + 1] + dp[i - 1]) % M; // If previous character is 2 // and ith character is less than // 6 // then the i-1th character and // ith character can be decoded in // a single character therefore, // adding dp[i-1]. else if (s.charAt(i - 1) == '2' && s.charAt(i) <= '6') dp[i + 1] = (dp[i + 1] + dp[i - 1]) % M; // If previous character is * then // it will contain the above 2 cases else if (s.charAt(i - 1) == '*') dp[i + 1] = (dp[i + 1] + (s.charAt(i) <= '6' ? 2 : 1) * dp[i - 1]) % M; } } return (int)dp[s.length()]; } public static void main(String[] args) { String s = \"12\"; System.out.println(waysOfDecoding(s)); }}", "e": 32832, "s": 29793, "text": null }, { "code": "# Python program for the above approachM = 1000000007def waysOfDecoding(s): dp = [0]*(len(s)+1) dp[0] = 1 # check the first character of the string # if it is '*' then 9 ways if s[0] == '*': dp[1] = 9 elif s[0] == '0': dp[1] = 0 else: dp[1] = 1 # traverse the string for i in range(len(s)): # If s[i] == '*' there can be # 9 possible values of * if (s[i] == '*'): dp[i + 1] = 9 * dp[i] # If previous character is 1 # then words that can be formed # are K(11), L(12), M(13), N(14) # O(15), P(16), Q(17), R(18), S(19) if (s[i - 1] == '1'): dp[i + 1] = (dp[i + 1] + 9 * dp[i - 1]) % M # If previous character is 2 # then the words that can be formed # are U(21), V(22), W(23), X(24)Y(25), Z(26) elif (s[i - 1] == '2'): dp[i + 1] = (dp[i + 1] + 6 * dp[i - 1]) % M # If the previous digit is * then # all 15 2- digit characters can be # formed elif (s[i - 1] == '*'): dp[i + 1] = (dp[i + 1] + 15 * dp[i - 1]) % M else: # taking the value from previous step if s[i] != '0': dp[i+1] = dp[i] else: dp[i+1] = 0 # If previous character is 1 then # the i-1th character and ith # character can be decoded in # a single character therefore, # adding dp[i-1]. if (s[i - 1] == '1'): dp[i + 1] = (dp[i + 1] + dp[i - 1]) % M # If previous character is 2 # and ith character is less than # 6 # then the i-1th character and # ith character can be decoded in # a single character therefore, # adding dp[i-1]. elif (s[i - 1] == '2' and s[i] <= '6'): dp[i + 1] = (dp[i + 1] + dp[i - 1]) % M # If previous character is * then # it will contain the above 2 cases elif (s[i - 1] == '*'): if (s[i] <= '6'): dp[i + 1] = dp[i + 1] + 2 * dp[i - 1] else: dp[i + 1] = dp[i + 1] + 1 * dp[i - 1] dp[i+1] = dp[i+1] % M return dp[len(s)] if __name__ == \"__main__\": s = \"12\" print(waysOfDecoding(s)) # This code is contributed by ukasp.", "e": 35316, "s": 32832, "text": null }, { "code": "// C# program for the above approachusing System; class GFG{ static int M = 1000000007;static int waysOfDecoding(String s){ long[] dp = new long[s.Length + 1]; dp[0] = 1; // Check the first character of the string // if it is '*' then 9 ways dp[1] = s[0] == '*' ? 9 : s[0] == '0' ? 0 : 1; // Traverse the string for(int i = 1; i < s.Length; i++) { // If s[i] == '*' there can be // 9 possible values of * if (s[i] == '*') { dp[i + 1] = 9 * dp[i]; // If previous character is 1 // then words that can be formed // are K(11), L(12), M(13), N(14) // O(15), P(16), Q(17), R(18), S(19) if (s[i - 1] == '1') dp[i + 1] = (dp[i + 1] + 9 * dp[i - 1]) % M; // If previous character is 2 // then the words that can be formed // are U(21), V(22), W(23), X(24)Y(25), // Z(26) else if (s[i - 1] == '2') dp[i + 1] = (dp[i + 1] + 6 * dp[i - 1]) % M; // If the previous digit is * then // all 15 2- digit characters can be // formed else if (s[i - 1] == '*') dp[i + 1] = (dp[i + 1] + 15 * dp[i - 1]) % M; } else { // Taking the value from previous step dp[i + 1] = s[i] != '0' ? dp[i] : 0; // If previous character is 1 then // the i-1th character and ith // character can be decoded in // a single character therefore, // adding dp[i-1]. if (s[i - 1] == '1') dp[i + 1] = (dp[i + 1] + dp[i - 1]) % M; // If previous character is 2 // and ith character is less than // 6 // then the i-1th character and // ith character can be decoded in // a single character therefore, // adding dp[i-1]. else if (s[i - 1] == '2' && s[i] <= '6') dp[i + 1] = (dp[i + 1] + dp[i - 1]) % M; // If previous character is * then // it will contain the above 2 cases else if (s[i - 1] == '*') dp[i + 1] = (dp[i + 1] + (s[i] <= '6' ? 2 : 1) * dp[i - 1]) % M; } } return (int)dp[s.Length];} // Driver codepublic static void Main(){ String s = \"12\"; Console.WriteLine(waysOfDecoding(s));}} // This code is contributed by rishavmahato348", "e": 37911, "s": 35316, "text": null }, { "code": "<script>// Javascript program for the above approach let M = 1000000007;function waysOfDecoding(s){ let dp = new Array(s.length + 1); for(let i=0;i<s.length+1;i++) dp[i] = 0; dp[0] = 1; // check the first character of the string // if it is '*' then 9 ways dp[1] = s[0] == '*' ? 9 : s[0] == '0' ? 0 : 1; // traverse the string for (let i = 1; i < s.length; i++) { // If s[i] == '*' there can be // 9 possible values of * if (s[i] == '*') { dp[i + 1] = 9 * dp[i]; // If previous character is 1 // then words that can be formed // are K(11), L(12), M(13), N(14) // O(15), P(16), Q(17), R(18), S(19) if (s[i-1] == '1') dp[i + 1] = (dp[i + 1] + 9 * dp[i - 1]) % M; // If previous character is 2 // then the words that can be formed // are U(21), V(22), W(23), X(24)Y(25), Z(26) else if (s[i-1] == '2') dp[i + 1] = (dp[i + 1] + 6 * dp[i - 1]) % M; // If the previous digit is * then // all 15 2- digit characters can be // formed else if (s[i-1] == '*') dp[i + 1] = (dp[i + 1] + 15 * dp[i - 1]) % M; } else { // taking the value from previous step dp[i + 1] = s[i] != '0' ? dp[i] : 0; // If previous character is 1 then // the i-1th character and ith // character can be decoded in // a single character therefore, // adding dp[i-1]. if (s[i-1] == '1') dp[i + 1] = (dp[i + 1] + dp[i - 1]) % M; // If previous character is 2 // and ith character is less than // 6 // then the i-1th character and // ith character can be decoded in // a single character therefore, // adding dp[i-1]. else if (s[i-1] == '2' && s[i] <= '6') dp[i + 1] = (dp[i + 1] + dp[i - 1]) % M; // If previous character is * then // it will contain the above 2 cases else if (s[i-1] == '*') dp[i + 1] = (dp[i + 1] + (s[i] <= '6' ? 2 : 1) * dp[i - 1]) % M; } } return dp[s.length];} let s = \"12\";document.write(waysOfDecoding(s)); // This code is contributed by unknown2108</script>", "e": 40827, "s": 37911, "text": null }, { "code": null, "e": 40829, "s": 40827, "text": "2" }, { "code": null, "e": 40872, "s": 40829, "text": "Time complexity: O(n)Auxiliary Space: O(n)" }, { "code": null, "e": 40903, "s": 40872, "text": "Further optimization of space " }, { "code": null, "e": 41415, "s": 40903, "text": "If the above code is observed carefully, it is observed that the value of dp[i] is found using dp[i-1] and dp[i-2]. So to optimize the space further, instead of creating an array of dp of length N, we can use three variables – second(stores the value of dp[i]), first(stores the value of dp[i-2]), and temp(stores the value of dp[i-1]). So after finding the value of the second(dp[i]), modify first = temp and temp = second and then calculate the value again of second(dp[i]) using the variable first and temp. " }, { "code": null, "e": 41419, "s": 41415, "text": "C++" }, { "code": null, "e": 41424, "s": 41419, "text": "Java" }, { "code": null, "e": 41427, "s": 41424, "text": "C#" }, { "code": null, "e": 41438, "s": 41427, "text": "Javascript" }, { "code": "// C++ program for the above approach#include <bits/stdc++.h>using namespace std; int M = 1000000007;int waysOfDecoding(string s){ long first = 1, second = s[0] == '*' ? 9 : s[0] == '0' ? 0 : 1; for(int i = 1; i < s.size(); i++) { long temp = second; // If s[i] == '*' there can be // 9 possible values of * if (s[i] == '*') { second = 9 * second; // If previous character is 1 // then words that can be formed // are K(11), L(12), M(13), N(14) // O(15), P(16), Q(17), R(18), S(19) if (s[i - 1] == '1') second = (second + 9 * first) % M; // If previous character is 2 // then the words that can be formed // are U(21), V(22), W(23), X(24)Y(25), Z(26) else if (s[i - 1] == '2') second = (second + 6 * first) % M; // If the previous digit is * then // all 15 2- digit characters can be // formed else if (s[i - 1] == '*') second = (second + 15 * first) % M; } // If s[i] != '*' else { second = s[i] != '0' ? second : 0; // Adding first in second // if s[i-1]=1 if (s[i - 1] == '1') second = (second + first) % M; // Adding first in second if // s[i-1] == 2 and s[i]<='6' else if (s[i - 1] == '2' && s[i] <= '6') second = (second + first) % M; // If s[i-1] == '*' the union // of above 2 cases has to be done else if (s[i - 1] == '*') second = (second + (s[i] <= '6' ? 2 : 1) * first) % M; } first = temp; } return(int)second;} // Driver codeint main(){ string s = \"*\"; cout << waysOfDecoding(s); return 0;} // This code is contributed by rishavmahato348", "e": 43406, "s": 41438, "text": null }, { "code": "// Java program for the above approachimport java.io.*; class GFG { static int M = 1000000007; static int waysOfDecoding(String s) { long first = 1, second = s.charAt(0) == '*' ? 9 : s.charAt(0) == '0' ? 0 : 1; for (int i = 1; i < s.length(); i++) { long temp = second; // If s[i] == '*' there can be // 9 possible values of * if (s.charAt(i) == '*') { second = 9 * second; // If previous character is 1 // then words that can be formed // are K(11), L(12), M(13), N(14) // O(15), P(16), Q(17), R(18), S(19) if (s.charAt(i - 1) == '1') second = (second + 9 * first) % M; // If previous character is 2 // then the words that can be formed // are U(21), V(22), W(23), X(24)Y(25), Z(26) else if (s.charAt(i - 1) == '2') second = (second + 6 * first) % M; // If the previous digit is * then // all 15 2- digit characters can be // formed else if (s.charAt(i - 1) == '*') second = (second + 15 * first) % M; } // If s[i] != '*' else { second = s.charAt(i) != '0' ? second : 0; // Adding first in second // if s[i-1]=1 if (s.charAt(i - 1) == '1') second = (second + first) % M; // Adding first in second if // s[i-1] == 2 and s[i]<='6' else if (s.charAt(i - 1) == '2' && s.charAt(i) <= '6') second = (second + first) % M; // if s[i-1] == '*' the union // of above 2 cases has to be done else if (s.charAt(i - 1) == '*') second = (second + (s.charAt(i) <= '6' ? 2 : 1) * first) % M; } first = temp; } return (int)second; } public static void main(String[] args) { String s = \"*\"; System.out.println(waysOfDecoding(s)); }}", "e": 45761, "s": 43406, "text": null }, { "code": "// C# program for the above approachusing System; class GFG{ static int M = 1000000007; static int waysOfDecoding(string s){ long first = 1, second = s[0] == '*' ? 9 : s[0] == '0' ? 0 : 1; for(int i = 1; i < s.Length; i++) { long temp = second; // If s[i] == '*' there can be // 9 possible values of * if (s[i] == '*') { second = 9 * second; // If previous character is 1 // then words that can be formed // are K(11), L(12), M(13), N(14) // O(15), P(16), Q(17), R(18), S(19) if (s[i - 1] == '1') second = (second + 9 * first) % M; // If previous character is 2 // then the words that can be formed // are U(21), V(22), W(23), X(24)Y(25), Z(26) else if (s[i - 1] == '2') second = (second + 6 * first) % M; // If the previous digit is * then // all 15 2- digit characters can be // formed else if (s[i - 1] == '*') second = (second + 15 * first) % M; } // If s[i] != '*' else { second = s[i] != '0' ? second : 0; // Adding first in second // if s[i-1]=1 if (s[i - 1] == '1') second = (second + first) % M; // Adding first in second if // s[i-1] == 2 and s[i]<='6' else if (s[i - 1] == '2' && s[i] <= '6') second = (second + first) % M; // if s[i-1] == '*' the union // of above 2 cases has to be done else if (s[i - 1] == '*') second = (second + (s[i] <= '6' ? 2 : 1) * first) % M; } first = temp; } return (int)second;} // Driver codestatic public void Main(){ string s = \"*\"; Console.WriteLine(waysOfDecoding(s));}} // This code is contributed by patel2127", "e": 47724, "s": 45761, "text": null }, { "code": "<script> // JavaScript program for the above approachlet M = 1000000007; function waysOfDecoding(s){ let first = 1, second = s[0] == '*' ? 9 : s[0] == '0' ? 0 : 1; for(let i = 1; i < s.length; i++) { let temp = second; // If s[i] == '*' there can be // 9 possible values of * if (s[i] == '*') { second = 9 * second; // If previous character is 1 // then words that can be formed // are K(11), L(12), M(13), N(14) // O(15), P(16), Q(17), R(18), S(19) if (s[i - 1] == '1') second = (second + 9 * first) % M; // If previous character is 2 // then the words that can be formed // are U(21), V(22), W(23), X(24)Y(25), Z(26) else if (s[i - 1] == '2') second = (second + 6 * first) % M; // If the previous digit is * then // all 15 2- digit characters can be // formed else if (s[i - 1] == '*') second = (second + 15 * first) % M; } // If s[i] != '*' else { second = s[i] != '0' ? second : 0; // Adding first in second // if s[i-1]=1 if (s[i - 1] == '1') second = (second + first) % M; // Adding first in second if // s[i-1] == 2 and s[i]<='6' else if (s[i - 1] == '2' && s[i] <= '6') second = (second + first) % M; // if s[i-1] == '*' the union // of above 2 cases has to be done else if (s[i - 1] == '*') second = (second + (s[i] <= '6' ? 2 : 1) * first) % M; } first = temp; } return second;} // Driver Codelet s = \"*\"; document.write(waysOfDecoding(s)); // This code is contributed by code_hunt </script>", "e": 49616, "s": 47724, "text": null }, { "code": null, "e": 49618, "s": 49616, "text": "9" }, { "code": null, "e": 49661, "s": 49618, "text": "Time complexity: O(n)Auxiliary Space: O(1)" }, { "code": null, "e": 49678, "s": 49663, "text": "mohit kumar 29" }, { "code": null, "e": 49690, "s": 49678, "text": "unknown2108" }, { "code": null, "e": 49706, "s": 49690, "text": "rishavmahato348" }, { "code": null, "e": 49716, "s": 49706, "text": "patel2127" }, { "code": null, "e": 49726, "s": 49716, "text": "code_hunt" }, { "code": null, "e": 49732, "s": 49726, "text": "ukasp" }, { "code": null, "e": 49741, "s": 49732, "text": "digit-DP" }, { "code": null, "e": 49750, "s": 49741, "text": "Facebook" }, { "code": null, "e": 49772, "s": 49750, "text": "interview-preparation" }, { "code": null, "e": 49792, "s": 49772, "text": "Dynamic Programming" }, { "code": null, "e": 49805, "s": 49792, "text": "Mathematical" }, { "code": null, "e": 49813, "s": 49805, "text": "Strings" }, { "code": null, "e": 49822, "s": 49813, "text": "Facebook" }, { "code": null, "e": 49830, "s": 49822, "text": "Strings" }, { "code": null, "e": 49850, "s": 49830, "text": "Dynamic Programming" }, { "code": null, "e": 49863, "s": 49850, "text": "Mathematical" }, { "code": null, "e": 49961, "s": 49863, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 49970, "s": 49961, "text": "Comments" }, { "code": null, "e": 49983, "s": 49970, "text": "Old Comments" }, { "code": null, "e": 50043, "s": 49983, "text": "Optimal Substructure Property in Dynamic Programming | DP-2" }, { "code": null, "e": 50064, "s": 50043, "text": "Min Cost Path | DP-6" }, { "code": null, "e": 50120, "s": 50064, "text": "Maximum Subarray Sum using Divide and Conquer algorithm" }, { "code": null, "e": 50155, "s": 50120, "text": "Optimal Binary Search Tree | DP-24" }, { "code": null, "e": 50194, "s": 50155, "text": "Greedy approach vs Dynamic programming" }, { "code": null, "e": 50254, "s": 50194, "text": "Write a program to print all permutations of a given string" }, { "code": null, "e": 50269, "s": 50254, "text": "C++ Data Types" }, { "code": null, "e": 50312, "s": 50269, "text": "Set in C++ Standard Template Library (STL)" }, { "code": null, "e": 50361, "s": 50312, "text": "Program to find sum of elements in a given array" } ]
Final Destination | Practice | GeeksforGeeks
Consider a 2d plane and a Robot which is located at (0,0) who can move only one unit step at a time in any direction i.e. if its initial position is (x,y), he can go to positions (x + 1, y), (x - 1, y), (x, y + 1) or (x, y - 1). Now Given three integers a,b (denoting the final position where the robot has to reach), and x. Find out if the Robot can reach the final position in exactly x steps. Example 1: Input: a = 5, b = 5, x = 11 Output: 0 Explanation: No matter how the Robot moves, the Robot won't be able to reach point (5,5) in exactly 11 moves. Example 2: Input: a = 10, b = 15, x = 25 Output: 1 Explanation: The Robot can move 10 times towards positive x-axis and then 15 times towards positive y-axis to reach (10,15). Your Task: You don't need to read input or print anything. Your task is to complete the function canReach() which takes 3 Integers a,b and x as input and returns the answer. Expected Time Complexity: O(1) Expected Auxiliary Space: O(1) Constraints: -109 <= a,b <= 109 1 <= x <= 2*109 0 badgujarsachin831 week ago int canReach(long long a, long long b, long long x) { // code here int sum=abs(a)+abs(b); if(x<sum){ return 0; } int di=x-sum; return di%2==0; } 0 gaurav79161 week ago int canReach(long long a, long long b, long long x) { if(abs(a)+abs(b)<=x && (x-(a+b))%2==0) return 1; else return 0; } +1 bhaskarmaheshwari83 weeks ago // second last cell pe jaane ke baad agr even steps hue toh apn kitne bhi round marke aa skte draw u will understand long long min_moves = abs(a)+abs(b); if(x<min_moves) { return 0; } long long diff = x-min_moves; return diff%2==0; 0 bhaskarmaheshwari84 weeks ago what is wrong in this code?? i have applied dfs on grid bool isSafe(int row,int col,int m,int n) { if(row<0||col<0||row>m||col>n) return 0; return 1; } int dfs(int a,int b,int x,int cnt,int row,int col,vector<vector<int>> &vis) { if((row==a&&col==b)&&cnt==x) return 1; vis[row][col]=1; int dx[]={-1,1,0,0}; int dy[]={0,0,-1,1}; for(int i=0;i<4;i++) { if(isSafe(row+dx[i],col+dy[i],a,b)&&!vis[row+dx[i]][col+dy[i]]) { if(dfs(a,b,x,cnt+1,row+dx[i],col+dy[i],vis)) return 1; } } return 0; } int canReach(long long a, long long b, long long x) { // code here int cnt=0; vector<vector<int>> vis(a+1,vector<int>(b+1,0)); return dfs(a,b,x,cnt,0,0,vis); } 0 ervishnu19942 months ago class Solution { public: int canReach(long long a, long long b, long long x) { if(a<0)a*=-1; if(b<0)b*=-1; if(x>=(a+b)&&(x-(a+b))%2==0) return 1; return 0; }}; 0 hemantkrkrayla6 months ago C++ Solution class Solution { public: int canReach(long long a, long long b, long long x) { // code here long long min_moves = abs(a)+abs(b); if(x<min_moves) { return 0; } long long diff = x-min_moves; return diff%2==0; } }; 0 code_prime6 months ago int canReach(long long a, long long b, long long x) { long long min_steps = abs(a)+abs(b); if(x<min_steps) return 0; return (x-min_steps)%2==0; } 0 muhammedrameez141220017 months ago int canReach(long long a, long long b, long long x) { a=abs(a); b=abs(b); if(a+b>x) return 0; if(a+b==x) return 1; if((a+b)%2==0) return x%2==0?1:0; if((a+b)%2!=0) return x%2!=0?1:0; } 0 ANAS MALVAT7 months ago ANAS MALVAT a = abs(a); b = abs(b); if(a + b > x ) return 0; if(a + b == x) return 1; if((a + b) % 2 == 0 and x % 2 == 0) return 1; if((a + b) % 2 != 0 and x % 2 != 0) return 1; return 0; 0 Achintya Veer Singh8 months ago Achintya Veer Singh Java One-Liner: return (x-Math.abs(a)-Math.abs(b))%2 == 0 && (x-Math.abs(a)-Math.abs(b)) >= 0? 1 : 0; 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": 634, "s": 238, "text": "Consider a 2d plane and a Robot which is located at (0,0) who can move only one unit step at a time in any direction i.e. if its initial position is (x,y), he can go to positions (x + 1, y), (x - 1, y), (x, y + 1) or (x, y - 1). Now Given three integers a,b (denoting the final position where the robot has to reach), and x. Find out if the Robot can reach the final position in exactly x steps." }, { "code": null, "e": 647, "s": 636, "text": "Example 1:" }, { "code": null, "e": 795, "s": 647, "text": "Input:\na = 5, b = 5, x = 11\nOutput:\n0\nExplanation:\nNo matter how the Robot moves,\nthe Robot won't be able to reach\npoint (5,5) in exactly 11 moves." }, { "code": null, "e": 806, "s": 795, "text": "Example 2:" }, { "code": null, "e": 972, "s": 806, "text": "Input:\na = 10, b = 15, x = 25\nOutput:\n1\nExplanation:\nThe Robot can move 10 times towards\npositive x-axis and then 15 times\ntowards positive y-axis to reach (10,15).\n" }, { "code": null, "e": 1148, "s": 974, "text": "Your Task:\nYou don't need to read input or print anything. Your task is to complete the function canReach() which takes 3 Integers a,b and x as input and returns the answer." }, { "code": null, "e": 1212, "s": 1150, "text": "Expected Time Complexity: O(1)\nExpected Auxiliary Space: O(1)" }, { "code": null, "e": 1262, "s": 1214, "text": "Constraints:\n-109 <= a,b <= 109\n1 <= x <= 2*109" }, { "code": null, "e": 1264, "s": 1262, "text": "0" }, { "code": null, "e": 1291, "s": 1264, "text": "badgujarsachin831 week ago" }, { "code": null, "e": 1500, "s": 1291, "text": "int canReach(long long a, long long b, long long x) {\n // code here\n int sum=abs(a)+abs(b);\n if(x<sum){\n return 0;\n }\n int di=x-sum;\n return di%2==0;\n }" }, { "code": null, "e": 1502, "s": 1500, "text": "0" }, { "code": null, "e": 1523, "s": 1502, "text": "gaurav79161 week ago" }, { "code": null, "e": 1685, "s": 1523, "text": " int canReach(long long a, long long b, long long x) {\n if(abs(a)+abs(b)<=x && (x-(a+b))%2==0)\n return 1;\n else\n return 0;\n }" }, { "code": null, "e": 1688, "s": 1685, "text": "+1" }, { "code": null, "e": 1718, "s": 1688, "text": "bhaskarmaheshwari83 weeks ago" }, { "code": null, "e": 1998, "s": 1718, "text": " // second last cell pe jaane ke baad agr even steps hue toh apn kitne bhi round marke aa skte draw u will understand long long min_moves = abs(a)+abs(b); if(x<min_moves) { return 0; } long long diff = x-min_moves; return diff%2==0;" }, { "code": null, "e": 2000, "s": 1998, "text": "0" }, { "code": null, "e": 2030, "s": 2000, "text": "bhaskarmaheshwari84 weeks ago" }, { "code": null, "e": 2059, "s": 2030, "text": "what is wrong in this code??" }, { "code": null, "e": 2086, "s": 2059, "text": "i have applied dfs on grid" }, { "code": null, "e": 2873, "s": 2088, "text": " bool isSafe(int row,int col,int m,int n) { if(row<0||col<0||row>m||col>n) return 0; return 1; } int dfs(int a,int b,int x,int cnt,int row,int col,vector<vector<int>> &vis) { if((row==a&&col==b)&&cnt==x) return 1; vis[row][col]=1; int dx[]={-1,1,0,0}; int dy[]={0,0,-1,1}; for(int i=0;i<4;i++) { if(isSafe(row+dx[i],col+dy[i],a,b)&&!vis[row+dx[i]][col+dy[i]]) { if(dfs(a,b,x,cnt+1,row+dx[i],col+dy[i],vis)) return 1; } } return 0; } int canReach(long long a, long long b, long long x) { // code here int cnt=0; vector<vector<int>> vis(a+1,vector<int>(b+1,0)); return dfs(a,b,x,cnt,0,0,vis); }" }, { "code": null, "e": 2875, "s": 2873, "text": "0" }, { "code": null, "e": 2900, "s": 2875, "text": "ervishnu19942 months ago" }, { "code": null, "e": 3098, "s": 2900, "text": "class Solution { public: int canReach(long long a, long long b, long long x) { if(a<0)a*=-1; if(b<0)b*=-1; if(x>=(a+b)&&(x-(a+b))%2==0) return 1; return 0; }};" }, { "code": null, "e": 3100, "s": 3098, "text": "0" }, { "code": null, "e": 3127, "s": 3100, "text": "hemantkrkrayla6 months ago" }, { "code": null, "e": 3140, "s": 3127, "text": "C++ Solution" }, { "code": null, "e": 3424, "s": 3142, "text": "class Solution {\n public:\n int canReach(long long a, long long b, long long x) {\n // code here\n long long min_moves = abs(a)+abs(b);\n if(x<min_moves) {\n return 0;\n }\n long long diff = x-min_moves;\n return diff%2==0;\n }\n};" }, { "code": null, "e": 3426, "s": 3424, "text": "0" }, { "code": null, "e": 3449, "s": 3426, "text": "code_prime6 months ago" }, { "code": null, "e": 3625, "s": 3449, "text": "int canReach(long long a, long long b, long long x) { long long min_steps = abs(a)+abs(b); if(x<min_steps) return 0; return (x-min_steps)%2==0; }" }, { "code": null, "e": 3627, "s": 3625, "text": "0" }, { "code": null, "e": 3662, "s": 3627, "text": "muhammedrameez141220017 months ago" }, { "code": null, "e": 3924, "s": 3662, "text": "int canReach(long long a, long long b, long long x) {\n a=abs(a);\n b=abs(b);\n if(a+b>x)\n return 0;\n if(a+b==x)\n return 1;\n \n if((a+b)%2==0)\n return x%2==0?1:0;\n \n if((a+b)%2!=0)\n return x%2!=0?1:0;\n }" }, { "code": null, "e": 3926, "s": 3924, "text": "0" }, { "code": null, "e": 3950, "s": 3926, "text": "ANAS MALVAT7 months ago" }, { "code": null, "e": 3962, "s": 3950, "text": "ANAS MALVAT" }, { "code": null, "e": 4234, "s": 3962, "text": " a = abs(a); b = abs(b); if(a + b > x ) return 0; if(a + b == x) return 1; if((a + b) % 2 == 0 and x % 2 == 0) return 1; if((a + b) % 2 != 0 and x % 2 != 0) return 1; return 0;" }, { "code": null, "e": 4236, "s": 4234, "text": "0" }, { "code": null, "e": 4268, "s": 4236, "text": "Achintya Veer Singh8 months ago" }, { "code": null, "e": 4288, "s": 4268, "text": "Achintya Veer Singh" }, { "code": null, "e": 4304, "s": 4288, "text": "Java One-Liner:" }, { "code": null, "e": 4390, "s": 4304, "text": "return (x-Math.abs(a)-Math.abs(b))%2 == 0 && (x-Math.abs(a)-Math.abs(b)) >= 0? 1 : 0;" }, { "code": null, "e": 4536, "s": 4390, "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": 4572, "s": 4536, "text": " Login to access your submissions. " }, { "code": null, "e": 4582, "s": 4572, "text": "\nProblem\n" }, { "code": null, "e": 4592, "s": 4582, "text": "\nContest\n" }, { "code": null, "e": 4655, "s": 4592, "text": "Reset the IDE using the second button on the top right corner." }, { "code": null, "e": 4803, "s": 4655, "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": 5011, "s": 4803, "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": 5117, "s": 5011, "text": "You can access the hints to get an idea about what is expected of you as well as the final solution code." } ]
Initialization of static variables in C
When static keyword is used, variable or data members or functions can not be modified again. It is allocated for the lifetime of program. Static functions can be called directly by using class name. Static variables are initialized only once. Compiler persist the variable till the end of the program. Static variable can be defined inside or outside the function. They are local to the block. The default value of static variable is zero. The static variables are alive till the execution of the program. Here is the syntax of static variables in C language, static datatype variable_name = value; Here, datatype − The datatype of variable like int, char, float etc. variable_name − This is the name of variable given by user. value − Any value to initialize the variable. By default, it is zero. Here is an example of static variables in C language, Live Demo #include <stdio.h> int main() { static int a = 8; int b = 10; printf("Value of static variable : %d\n", a); printf("Value of non-static variable : %d\n", b); return 0; } Value of static variable : 8 Value of non-static variable : 10 In the above program, two variables are declared, one is static and another is non-static. The variables are initialized with values and displayed as follows − static int a = 8; int b = 10; printf("Value of static variable : %d\n", a); printf("Value of non-static variable : %d\n", b);
[ { "code": null, "e": 1262, "s": 1062, "text": "When static keyword is used, variable or data members or functions can not be modified again. It is allocated for the lifetime of program. Static functions can be called directly by using class name." }, { "code": null, "e": 1569, "s": 1262, "text": "Static variables are initialized only once. Compiler persist the variable till the end of the program. Static variable can be defined inside or outside the function. They are local to the block. The default value of static variable is zero. The static variables are alive till the execution of the program." }, { "code": null, "e": 1623, "s": 1569, "text": "Here is the syntax of static variables in C language," }, { "code": null, "e": 1662, "s": 1623, "text": "static datatype variable_name = value;" }, { "code": null, "e": 1668, "s": 1662, "text": "Here," }, { "code": null, "e": 1731, "s": 1668, "text": "datatype − The datatype of variable like int, char, float etc." }, { "code": null, "e": 1791, "s": 1731, "text": "variable_name − This is the name of variable given by user." }, { "code": null, "e": 1861, "s": 1791, "text": "value − Any value to initialize the variable. By default, it is zero." }, { "code": null, "e": 1915, "s": 1861, "text": "Here is an example of static variables in C language," }, { "code": null, "e": 1926, "s": 1915, "text": " Live Demo" }, { "code": null, "e": 2111, "s": 1926, "text": "#include <stdio.h>\nint main() {\n static int a = 8;\n int b = 10;\n printf(\"Value of static variable : %d\\n\", a);\n printf(\"Value of non-static variable : %d\\n\", b);\n return 0;\n}" }, { "code": null, "e": 2174, "s": 2111, "text": "Value of static variable : 8\nValue of non-static variable : 10" }, { "code": null, "e": 2334, "s": 2174, "text": "In the above program, two variables are declared, one is static and another is non-static. The variables are initialized with values and displayed as follows −" }, { "code": null, "e": 2460, "s": 2334, "text": "static int a = 8;\nint b = 10;\nprintf(\"Value of static variable : %d\\n\", a);\nprintf(\"Value of non-static variable : %d\\n\", b);" } ]
How to read a text file from resources in Kotlin?
In this article, we will see how we can read a text file using Kotlin library functions. Kotlin is based on Java, hence we can use different Java library functions in Kotlin too. Go ahead and create a Kotlin file in your workspace and name it " ReadFile.kt". Keep a text file with some data in the same directory. For this example, our Text file looks like this − Welcome to the best tutorial website - www.tutorialsPoint.com This is the Text file that we want to read via Kotlin Execute the following piece of code to read the above text file. // importing java library function // to read files from different sources import java.io.File import java.io.BufferedReader fun main(args: Array<String>) { val bufferedReader: BufferedReader = File("Text.txt").bufferedReader() val inputString = bufferedReader.use { it.readText() } println(inputString) } The above program will read the text file in the same directory and give us the following output Running] cd "<<Your workspace>>" && kotlinc readFile.kt -include-runtime -d readFile.jar && java -jar readFile.jar Welcome to the best tutorial website - www.tutorialsPoint.com This is the Text file that we want to read via Kotlin File information can be read using another library function, that is, InputStream. In the following example, we will read the same text file using InputStream. import java.io.File import java.io.InputStream fun main(args: Array<String>) { val inputStream: InputStream = File("Text.txt").inputStream() val inputString = inputStream.bufferedReader().use { it.readText() } println(inputString) } It will produce the following output [Running] cd "<<Your workspace>>" && kotlinc readFile.kt -include-runtime -d readFile.jar && java -jar readFile.jar Welcome to the best tutorial website - www.tutorialsPoint.com This is the Text file that we want to read via Kotlin
[ { "code": null, "e": 1241, "s": 1062, "text": "In this article, we will see how we can read a text file using Kotlin library functions. Kotlin is based on Java, hence we can use different Java library functions in Kotlin too." }, { "code": null, "e": 1426, "s": 1241, "text": "Go ahead and create a Kotlin file in your workspace and name it \" ReadFile.kt\". Keep a text file with some data in the same directory. For this example, our Text file looks like this −" }, { "code": null, "e": 1542, "s": 1426, "text": "Welcome to the best tutorial website - www.tutorialsPoint.com\nThis is the Text file that we want to read via Kotlin" }, { "code": null, "e": 1607, "s": 1542, "text": "Execute the following piece of code to read the above text file." }, { "code": null, "e": 1923, "s": 1607, "text": "// importing java library function\n// to read files from different sources\nimport java.io.File\nimport java.io.BufferedReader\n\nfun main(args: Array<String>) {\n val bufferedReader: BufferedReader = File(\"Text.txt\").bufferedReader()\n val inputString = bufferedReader.use { it.readText() }\n println(inputString)\n}" }, { "code": null, "e": 2020, "s": 1923, "text": "The above program will read the text file in the same directory and give us the following output" }, { "code": null, "e": 2251, "s": 2020, "text": "Running] cd \"<<Your workspace>>\" && kotlinc readFile.kt\n-include-runtime -d readFile.jar && java -jar readFile.jar\nWelcome to the best tutorial website - www.tutorialsPoint.com\nThis is the Text file that we want to read via Kotlin" }, { "code": null, "e": 2411, "s": 2251, "text": "File information can be read using another library function, that is, InputStream. In the following example, we will read the same text file using InputStream." }, { "code": null, "e": 2653, "s": 2411, "text": "import java.io.File\nimport java.io.InputStream\nfun main(args: Array<String>) {\n val inputStream: InputStream = File(\"Text.txt\").inputStream()\n val inputString = inputStream.bufferedReader().use { it.readText() }\n println(inputString)\n}" }, { "code": null, "e": 2690, "s": 2653, "text": "It will produce the following output" }, { "code": null, "e": 2922, "s": 2690, "text": "[Running] cd \"<<Your workspace>>\" && kotlinc readFile.kt\n-include-runtime -d readFile.jar && java -jar readFile.jar\nWelcome to the best tutorial website - www.tutorialsPoint.com\nThis is the Text file that we want to read via Kotlin" } ]
How to Build a Web App in 50 lines of code using Plotly and Dash | by François St-Amant | Towards Data Science
There are many tools out there for data visualization. However, few tools will take your data visualization game to the next level by allowing you to easily build web based applications with interactive high quality plots. That’s what Plotly and Dash offer, all of it in Python. That’s why you should 100% learn about it! In this article, I will show how to create basic interactive plots with Plotly and how to integrate them in a web based application using Dash. The data used will be the daily sales from a store, as well as a 7 day forecast. Here is what the daily sales data looks like: Plotly is a graphing library that makes interactive high quality graphs. The keyword is interactive. Here is the code to plot 2 lines, one for the daily sales, another for the forecast. #Import plotlyimport plotly.graph_objects as go#Initialize the plotfig_totalsales=go.Figure()#Add the linesfig_totalsales.add_trace(go.Scatter(x=sales[sales.columns[0]], y=sales[sales.columns[1]], visible=True, name='Sales'))fig_totalsales.add_trace(go.Scatter(x=fore['Date'],y=fore[fore.columns[0]],visible=True, name='Forecast'))#Add title/set graph sizefig_totalsales.update_layout(title = 'Daily Sales', width=850, height=400)fig_totalsales.show() Pretty neat right? The append.traces function allows us to easily add other lines to the graph. Plotly offers so much more. I will leave it at that in this article because I want to focus more on Dash. Still, I highly recommend that you check out the Plotly documentation: https://plotly.com/python/. The Dash platform allows us newbies to produce quality enterprise-ready analytic apps without the need for developers, JavaScript or anything more than basic Python skills for that matter. With Dash Open Source (the free version), Dash apps run on your local workstation. You cannot share the app itself but you can always share the code. Every complete Dash app has three parts: The layout, which describes what the application looks like.The Dash core components (called dcc), which is basically the content of the application (graphs, dropdown menus, checkboxes, etc.).The callbacks, which make the app interactive, by having the components interact with one another. The layout, which describes what the application looks like. The Dash core components (called dcc), which is basically the content of the application (graphs, dropdown menus, checkboxes, etc.). The callbacks, which make the app interactive, by having the components interact with one another. Here is all the code you need to create a Dash app that contains the table we created earlier: #Import librariesimport dashimport dash_core_components as dccimport dash_html_components as html#Create the appapp = dash.Dash()app.layout = html.Div([ dcc.Graph(figure=fig_totalsales)])app.run_server(debug=True, use_reloader=False) That’s all! As easy as it gets. We see that this app contains a layout as well as one core component, the figure. The html.div tag is what defines a new section in the app, where we can add any Dash Core Component we want (dcc.Graph here). Here is what the “app” looks like right now: Now of course, if someones wants to create an application, it’s not to show a single plot. You could have done that with any python library. What makes Dash great is that you can have different components interacting with one another. That’s where the third part of Dash, the callbacks, comes into play. A callback asks for an input, makes it go through a function and gives an output. Let’s see how we could improve our current app (there are a million things we could do, here’s a few). 1. Add a title. 2. Add the ability to filter through our figure to only show the data points for a specific range of dates. 3. Add an interactive text box, showing the sum of the sales for the selected period. Dash has a core component called DatePickerRange. All we need is a callback to link the figure and the text with this new core component. Here is the full code that does just that. Here is a block by block description of the code: The first html.div is there to create a section with the title of the app. The second html.div adds the DateRangePicker component as well as the 2 outputs that will be linked to it via the callback (a text element and a figure). The last part is the callback. It asks for 2 inputs, i.e. the two dates and it gives 2 outputs, i.e. the figure and the text. Inside the update_output function, the data is selected based on the dates provided. Then, the sales total is calculated and the figure is created. Here is a short video showing what the app looks like now: There you have it, a decent looking web-based application in less than 50 lines of code! Check this out for more information on Dash: https://dash.plotly.com/. Thanks a lot for reading!
[ { "code": null, "e": 394, "s": 171, "text": "There are many tools out there for data visualization. However, few tools will take your data visualization game to the next level by allowing you to easily build web based applications with interactive high quality plots." }, { "code": null, "e": 493, "s": 394, "text": "That’s what Plotly and Dash offer, all of it in Python. That’s why you should 100% learn about it!" }, { "code": null, "e": 637, "s": 493, "text": "In this article, I will show how to create basic interactive plots with Plotly and how to integrate them in a web based application using Dash." }, { "code": null, "e": 764, "s": 637, "text": "The data used will be the daily sales from a store, as well as a 7 day forecast. Here is what the daily sales data looks like:" }, { "code": null, "e": 950, "s": 764, "text": "Plotly is a graphing library that makes interactive high quality graphs. The keyword is interactive. Here is the code to plot 2 lines, one for the daily sales, another for the forecast." }, { "code": null, "e": 1402, "s": 950, "text": "#Import plotlyimport plotly.graph_objects as go#Initialize the plotfig_totalsales=go.Figure()#Add the linesfig_totalsales.add_trace(go.Scatter(x=sales[sales.columns[0]], y=sales[sales.columns[1]], visible=True, name='Sales'))fig_totalsales.add_trace(go.Scatter(x=fore['Date'],y=fore[fore.columns[0]],visible=True, name='Forecast'))#Add title/set graph sizefig_totalsales.update_layout(title = 'Daily Sales', width=850, height=400)fig_totalsales.show()" }, { "code": null, "e": 1498, "s": 1402, "text": "Pretty neat right? The append.traces function allows us to easily add other lines to the graph." }, { "code": null, "e": 1703, "s": 1498, "text": "Plotly offers so much more. I will leave it at that in this article because I want to focus more on Dash. Still, I highly recommend that you check out the Plotly documentation: https://plotly.com/python/." }, { "code": null, "e": 1892, "s": 1703, "text": "The Dash platform allows us newbies to produce quality enterprise-ready analytic apps without the need for developers, JavaScript or anything more than basic Python skills for that matter." }, { "code": null, "e": 2042, "s": 1892, "text": "With Dash Open Source (the free version), Dash apps run on your local workstation. You cannot share the app itself but you can always share the code." }, { "code": null, "e": 2083, "s": 2042, "text": "Every complete Dash app has three parts:" }, { "code": null, "e": 2374, "s": 2083, "text": "The layout, which describes what the application looks like.The Dash core components (called dcc), which is basically the content of the application (graphs, dropdown menus, checkboxes, etc.).The callbacks, which make the app interactive, by having the components interact with one another." }, { "code": null, "e": 2435, "s": 2374, "text": "The layout, which describes what the application looks like." }, { "code": null, "e": 2568, "s": 2435, "text": "The Dash core components (called dcc), which is basically the content of the application (graphs, dropdown menus, checkboxes, etc.)." }, { "code": null, "e": 2667, "s": 2568, "text": "The callbacks, which make the app interactive, by having the components interact with one another." }, { "code": null, "e": 2762, "s": 2667, "text": "Here is all the code you need to create a Dash app that contains the table we created earlier:" }, { "code": null, "e": 2999, "s": 2762, "text": "#Import librariesimport dashimport dash_core_components as dccimport dash_html_components as html#Create the appapp = dash.Dash()app.layout = html.Div([ dcc.Graph(figure=fig_totalsales)])app.run_server(debug=True, use_reloader=False)" }, { "code": null, "e": 3113, "s": 2999, "text": "That’s all! As easy as it gets. We see that this app contains a layout as well as one core component, the figure." }, { "code": null, "e": 3284, "s": 3113, "text": "The html.div tag is what defines a new section in the app, where we can add any Dash Core Component we want (dcc.Graph here). Here is what the “app” looks like right now:" }, { "code": null, "e": 3588, "s": 3284, "text": "Now of course, if someones wants to create an application, it’s not to show a single plot. You could have done that with any python library. What makes Dash great is that you can have different components interacting with one another. That’s where the third part of Dash, the callbacks, comes into play." }, { "code": null, "e": 3773, "s": 3588, "text": "A callback asks for an input, makes it go through a function and gives an output. Let’s see how we could improve our current app (there are a million things we could do, here’s a few)." }, { "code": null, "e": 3789, "s": 3773, "text": "1. Add a title." }, { "code": null, "e": 3897, "s": 3789, "text": "2. Add the ability to filter through our figure to only show the data points for a specific range of dates." }, { "code": null, "e": 3983, "s": 3897, "text": "3. Add an interactive text box, showing the sum of the sales for the selected period." }, { "code": null, "e": 4121, "s": 3983, "text": "Dash has a core component called DatePickerRange. All we need is a callback to link the figure and the text with this new core component." }, { "code": null, "e": 4164, "s": 4121, "text": "Here is the full code that does just that." }, { "code": null, "e": 4214, "s": 4164, "text": "Here is a block by block description of the code:" }, { "code": null, "e": 4289, "s": 4214, "text": "The first html.div is there to create a section with the title of the app." }, { "code": null, "e": 4443, "s": 4289, "text": "The second html.div adds the DateRangePicker component as well as the 2 outputs that will be linked to it via the callback (a text element and a figure)." }, { "code": null, "e": 4717, "s": 4443, "text": "The last part is the callback. It asks for 2 inputs, i.e. the two dates and it gives 2 outputs, i.e. the figure and the text. Inside the update_output function, the data is selected based on the dates provided. Then, the sales total is calculated and the figure is created." }, { "code": null, "e": 4776, "s": 4717, "text": "Here is a short video showing what the app looks like now:" }, { "code": null, "e": 4936, "s": 4776, "text": "There you have it, a decent looking web-based application in less than 50 lines of code! Check this out for more information on Dash: https://dash.plotly.com/." } ]
Customer Clustering using DBSCAN. In this blog, we will learn about one... | by Tarique Akhtar | Towards Data Science
In this blog, we will learn about one of my favorite clustering algorithm and that is the DBSCAN algorithm. We will first understand the theory then I will demonstrate the working of the DBSCAN with the help of a very simple example. The DBSCAN stands for density based spatial clustering of applications with noise. It was introduced around 1996 and has gained significant popularity in the community due to its effective clustering ability of recognizing different types of clustering shapes and also the ability to identify the clusters correctly even in the presence of noise. Let’s jump to some key terminologies that will help us understand the basic working of the algorithm. There are two parameters that play a vital role in the algorithm. 1) Min points and 2) Epsilon. The algorithm works by processing each and every data point individually in particular for each point. It will construct a kind of a circle with the point being in the center and having the radius equal to the Epsilon. MinPoints are the number of points that must exist within ɛ distance from the point. It is the distance or radius around each object. Considering below diagram, one circle is drawn whose center is the Query point and radius is ɛ. The query point will become Core point if number of points inside circle is more than MinPoints (in this case MinPoints = 2). So the query point has qualified to become Core point. If a query point has lesser than MinPoints within ɛ but has a core point within ɛ distance, then it is a Border point. A point which is neither a Core nor a Border point is called as Noise point. See below diagram. The DBSCAN will process each and every object/points in this fashion and at the end it will obtain categorization of all the points as either core, border or noise points. Once the categorization of the points are obtained, the next step is to use them to construct the clusters. DBSCAN take up a core point and then look at the points which are inside its Epsilon radius circle and assign a Cluster label to those points. So the key idea is to give the same label to all the points inside the circle of a core point. Multiple iterations will be run for different core points to assign Cluster label, please note algorithm will not assign new Cluster label to those points which have already be considered in earlier iteration. Problem Statement:You own the mall and want to understand the customers based their past purchasing data. This analysis will help marketing team to target customers with some strategies. Your data consist of columns like Customer ID, age, gender, annual income and spending score. Spending Score is something you assign to the customer based on your defined parameters like customer behavior and purchasing data. You can get this dataset from Kaggle.com. https://www.kaggle.com/vjchoudhary7/customer-segmentation-tutorial-in-python # DBSCAN Clustering# Importing the librariesimport numpy as npimport matplotlib.pyplot as pltimport pandas as pd# Importing the datasetdataset = pd.read_csv(Mall_customers.csv')data = dataset.iloc[:, [3, 4]].valuesdataset.head() # visualizing the datasetplt.scatter(data[:, 0], data[:, 1], s = 10, c = 'black') # Fitting DBSCAN to the dataset and predict the Cluster labelfrom sklearn.cluster import DBSCANdbscan = DBSCAN(eps=5.5, min_samples=4)labels = dbscan.fit_predict(data) np.unique(labels) # Visualising the clustersplt.scatter(data[labels == -1, 0], data[labels == -1, 1], s = 10, c = 'black')plt.scatter(data[labels == 0, 0], data[labels == 0, 1], s = 10, c = 'blue')plt.scatter(data[labels == 1, 0], data[labels == 1, 1], s = 10, c = 'red')plt.scatter(data[labels == 2, 0], data[labels == 2, 1], s = 10, c = 'green')plt.scatter(data[labels == 3, 0], data[labels == 3, 1], s = 10, c = 'brown')plt.scatter(data[labels == 4, 0], data[labels == 4, 1], s = 10, c = 'pink')plt.scatter(data[labels == 5, 0], data[labels == 5, 1], s = 10, c = 'yellow') plt.scatter(data[labels == 6, 0], data[labels == 6, 1], s = 10, c = 'silver')plt.xlabel('Annual Income')plt.ylabel('Spending Score')plt.show() Congratulation, your first iteration for Customer clustering is completed. As clustering is unsupervised learning, you need to analyze each cluster and have a definition with respect to business data because Clustering is always guided by some business rules. Once your clusters are close to business rules, your model will make sense. We can also change the value for eps and Min_sample to tune the model and make clusters better in shapes. Thank you for reading.
[ { "code": null, "e": 406, "s": 172, "text": "In this blog, we will learn about one of my favorite clustering algorithm and that is the DBSCAN algorithm. We will first understand the theory then I will demonstrate the working of the DBSCAN with the help of a very simple example." }, { "code": null, "e": 489, "s": 406, "text": "The DBSCAN stands for density based spatial clustering of applications with noise." }, { "code": null, "e": 753, "s": 489, "text": "It was introduced around 1996 and has gained significant popularity in the community due to its effective clustering ability of recognizing different types of clustering shapes and also the ability to identify the clusters correctly even in the presence of noise." }, { "code": null, "e": 855, "s": 753, "text": "Let’s jump to some key terminologies that will help us understand the basic working of the algorithm." }, { "code": null, "e": 951, "s": 855, "text": "There are two parameters that play a vital role in the algorithm. 1) Min points and 2) Epsilon." }, { "code": null, "e": 1170, "s": 951, "text": "The algorithm works by processing each and every data point individually in particular for each point. It will construct a kind of a circle with the point being in the center and having the radius equal to the Epsilon." }, { "code": null, "e": 1255, "s": 1170, "text": "MinPoints are the number of points that must exist within ɛ distance from the point." }, { "code": null, "e": 1304, "s": 1255, "text": "It is the distance or radius around each object." }, { "code": null, "e": 1581, "s": 1304, "text": "Considering below diagram, one circle is drawn whose center is the Query point and radius is ɛ. The query point will become Core point if number of points inside circle is more than MinPoints (in this case MinPoints = 2). So the query point has qualified to become Core point." }, { "code": null, "e": 1700, "s": 1581, "text": "If a query point has lesser than MinPoints within ɛ but has a core point within ɛ distance, then it is a Border point." }, { "code": null, "e": 1796, "s": 1700, "text": "A point which is neither a Core nor a Border point is called as Noise point. See below diagram." }, { "code": null, "e": 1968, "s": 1796, "text": "The DBSCAN will process each and every object/points in this fashion and at the end it will obtain categorization of all the points as either core, border or noise points." }, { "code": null, "e": 2219, "s": 1968, "text": "Once the categorization of the points are obtained, the next step is to use them to construct the clusters. DBSCAN take up a core point and then look at the points which are inside its Epsilon radius circle and assign a Cluster label to those points." }, { "code": null, "e": 2314, "s": 2219, "text": "So the key idea is to give the same label to all the points inside the circle of a core point." }, { "code": null, "e": 2524, "s": 2314, "text": "Multiple iterations will be run for different core points to assign Cluster label, please note algorithm will not assign new Cluster label to those points which have already be considered in earlier iteration." }, { "code": null, "e": 2711, "s": 2524, "text": "Problem Statement:You own the mall and want to understand the customers based their past purchasing data. This analysis will help marketing team to target customers with some strategies." }, { "code": null, "e": 2937, "s": 2711, "text": "Your data consist of columns like Customer ID, age, gender, annual income and spending score. Spending Score is something you assign to the customer based on your defined parameters like customer behavior and purchasing data." }, { "code": null, "e": 2979, "s": 2937, "text": "You can get this dataset from Kaggle.com." }, { "code": null, "e": 3056, "s": 2979, "text": "https://www.kaggle.com/vjchoudhary7/customer-segmentation-tutorial-in-python" }, { "code": null, "e": 3285, "s": 3056, "text": "# DBSCAN Clustering# Importing the librariesimport numpy as npimport matplotlib.pyplot as pltimport pandas as pd# Importing the datasetdataset = pd.read_csv(Mall_customers.csv')data = dataset.iloc[:, [3, 4]].valuesdataset.head()" }, { "code": null, "e": 3367, "s": 3285, "text": "# visualizing the datasetplt.scatter(data[:, 0], data[:, 1], s = 10, c = 'black')" }, { "code": null, "e": 3553, "s": 3367, "text": "# Fitting DBSCAN to the dataset and predict the Cluster labelfrom sklearn.cluster import DBSCANdbscan = DBSCAN(eps=5.5, min_samples=4)labels = dbscan.fit_predict(data) np.unique(labels)" }, { "code": null, "e": 4259, "s": 3553, "text": "# Visualising the clustersplt.scatter(data[labels == -1, 0], data[labels == -1, 1], s = 10, c = 'black')plt.scatter(data[labels == 0, 0], data[labels == 0, 1], s = 10, c = 'blue')plt.scatter(data[labels == 1, 0], data[labels == 1, 1], s = 10, c = 'red')plt.scatter(data[labels == 2, 0], data[labels == 2, 1], s = 10, c = 'green')plt.scatter(data[labels == 3, 0], data[labels == 3, 1], s = 10, c = 'brown')plt.scatter(data[labels == 4, 0], data[labels == 4, 1], s = 10, c = 'pink')plt.scatter(data[labels == 5, 0], data[labels == 5, 1], s = 10, c = 'yellow') plt.scatter(data[labels == 6, 0], data[labels == 6, 1], s = 10, c = 'silver')plt.xlabel('Annual Income')plt.ylabel('Spending Score')plt.show()" }, { "code": null, "e": 4334, "s": 4259, "text": "Congratulation, your first iteration for Customer clustering is completed." }, { "code": null, "e": 4595, "s": 4334, "text": "As clustering is unsupervised learning, you need to analyze each cluster and have a definition with respect to business data because Clustering is always guided by some business rules. Once your clusters are close to business rules, your model will make sense." }, { "code": null, "e": 4701, "s": 4595, "text": "We can also change the value for eps and Min_sample to tune the model and make clusters better in shapes." } ]
Borderless Tables Detection with Deep Learning and OpenCV | by Volodymyr Holomb | Towards Data Science
Document parsing is an initial step for transforming information into valuable business data. That information is often stored within commercial documents in tabular format or incidentally in data blocks without distinctive graphical borders. A borderless table may help to simplify the visual perception of semi-structured data for us, humans. From the machine-reading point of view, such presenting information on a page has quite a few shortcomings which make it difficult to separate the data belonging to a presumptive table structure from the surrounding textual context. Tabular data extraction as a business challenge may have several ad-hoc or heuristiс rules-based solutions which definitely will fail with a table of a bit different layout or style. On a large scale, one should use a more general approach for identifying table-like structures in an image, more specifically a deep learning-based object detection approach. Deep learning-based object detection Installation and setup of TF2 Object Detection API Data preparation Model configuration Model training and saving Table detection and cell recognition in a real-life image Adrian Rosebrock, a known CV researcher, states in his “Gentle guide to deep learning object detection” that: “object detection, regardless of whether performed via deep learning or other computer vision techniques, builds on image classification and seeks to localize precisely an area where an object appears”. One approach to build a custom object detector, as he suggests, is to choose any classifier and precede it with an algorithm to select and provide regions of an image that may contain an object. Within this method, you are free to decide whether to use a traditional ML algorithm for image classification (utilising or not CNN as a feature extractor) or train a simple neural network to handle arbitrary large datasets. Despite its proven efficiency, this two-stage object detection paradigm, known as R-CNN, still relies on heavy computations and is not suitable for real-time application. It is further said in the abovementioned post that “another approach is to treat a pre-trained classification network as a base (backbone) network in a multi-component deep learning object detection framework (such as Faster R-CNN, SSD, or YOLO)”. Thus you will benefit from its complete end-to-end trainable architecture. Whatever be the choice it will put you further to an issue of overlapping bounding boxes. Hereinafter we will touch upon performing non-maximum suppression for this purpose. Meanwhile please refer to the transfer-learning flow-chart (see in interactive view) of an object detector for an arbitrary new class: Due to its being quicker, less tedious and more accurate in general, the second approach has become widely adopted for table-like structures recognition in commercial and scientific papers. As an example, you can easily find implementations using YOLO, RetinaNet, Cascade R-CNN and other frameworks for the tabular data extraction from PDF documents. Moving forward with this tutorial you’ll learn how to use tools like TensorFlow (TF2) Object Detection API to build your custom object detectors using pre-trained state-of-the-art models with ease. Be aware it will not be an exhausting introduction to deep learning object detection, but rather a phase-by-phase description of interacting with TF2 Object detection API (and other tools) for solving a pronounced business problem (such as borderless table detection) within a specific development environment (Anaconda/Win10). Throughout the rest of this post, we will cover some aspects and the results of our modelling process in greater detail than others. Nonetheless, you’ll find the essential code examples to follow our experiment. To proceed you should have Anaconda and Tesseract installed and protobuf downloaded and added to PATH. Under a path of your choice create a new folder, that we will refer to hereinafter as a ‘project’s root folder’. From your terminal window run one-by-one the following commands: # from <project’s root folder>conda create -n <new environment name> \python=3.7 \tensorflow=2.3 \numpy=1.17.4 \tf_slim \cython \gitconda activate <new environment name>git clone https://github.com/tensorflow/models.gitpip install git+https://github.com/philferriere/cocoapi.git#subdirectory=PythonAPIcd models\research# from <project’s root folder>\models\researchprotoc object_detection\protos\*.proto — python_out=.copy object_detection\packages\tf2\setup.py .python setup.py installpython object_detection\builders\model_builder_tf2_test.pyconda install imutils pdf2image beautifulsoup4 typeguardpip install tf-imagecopy object_detection\model_main_tf2.py ..\..\workspace\.copy object_detection\exporter_main_v2.py ..\..\workspace\.cd ..\.. It will install core and some helper libraries into your local environment needed to use a TF2 Object Detection API and take care of your training dataset. From this step on you should be able to download a pretrained model from TF2 Model Garden and get inferences from it for respective pretrained classes. I hope you’ve succeeded so far! Please bear in mind that our final goal is to perform transfer learning using a pretrained model to detect a single ‘borderless’ class, which the model has no idea about while initial training. If you have studied our transfer-learning flow-chart you should have noticed that our starting point for the whole process is a dataset, whether annotated or not. If you need annotation, there are tons of solutions available. Pick the one that will give you annotations in XML, that is compatible with our example. The more annotated data we have the better (important: all table images for this post were selected from open data sources like this one and annotated/re-annotated by the author). But as soon as you’ll try your hands in manual data labelling you’ll understand how tedious this work is. Unfortunately, none of the popular python-libraries for image augmentation takes care of the selected bounding boxes. It is in our interest to multiply the initial dataset without the high cost of collecting and annotating new data. That is the case when a tf-image package will become handy. The above script will randomly transform the original image along with the object’s bounding boxes and save both the new image and corresponding XML file to disk. That is how our dataset looks after three-fold expansion: The next steps will include splitting the data into train and test sets. Models based on the TF2 Object Detection API need a special format for all input data, called TFRecord. You’ll find corresponding scripts to split and convert your data in the Github repository. At this step, we’ll create a Label Map file (.pbtxt) to link our class label (‘borderless’) to some integer value. The TF2 Object Detection API needs this file for training and detection purposes: item {id: 1name: ‘borderless’} The actual model configuration is happening in the corresponding pipeline.config file. You can read an intro to model configuration and decide whether to configure the file manually or by running a script from the Github repository. By now your project’s root folder might look something like this: 📦borderless_tbls_detection┣ 📂images┃ ┣ 📂processed┃ ┃ ┣ 📂all_annots┃ ┃ ┃ ┗ 📜...XML┃ ┃ ┗ 📂all_images┃ ┃ ┃ ┗ 📜...jpg┃ ┣ 📂splitted┃ ┃ ┣ 📂test_set┃ ┃ ┃ ┣ 📜...jpg┃ ┃ ┃ ┗ 📜...XML┃ ┃ ┣ 📂train_set┃ ┃ ┃ ┣ 📜...jpg┃ ┃ ┃ ┗ 📜...XML┃ ┃ ┗ 📂val_set┃ ┗ 📜xml_style.XML┣ 📂models┃ ┗ 📂...┣ 📂scripts┃ ┣ 📜...py┣ 📂train_logs┣ 📂workspace┃ ┣ 📂data┃ ┃ ┣ 📜label_map.pbtxt┃ ┃ ┣ 📜test.csv┃ ┃ ┣ 📜test.record┃ ┃ ┣ 📜train.csv┃ ┃ ┣ 📜train.record┃ ┃ ┣ 📜val.csv┃ ┃ ┗ 📜val.record┃ ┣ 📂models┃ ┃ ┗ 📂efficientdet_d1_coco17_tpu-32┃ ┃ ┃ ┗ 📂v1┃ ┃ ┃ ┃ ┗ 📜pipeline.config┃ ┣ 📂pretrained_models┃ ┃ ┗ 📂datasets┃ ┃ ┃ ┣ 📂efficientdet_d1_coco17_tpu-32┃ ┃ ┃ ┃ ┣ 📂checkpoint┃ ┃ ┃ ┃ ┃ ┣ 📜checkpoint┃ ┃ ┃ ┃ ┃ ┣ 📜ckpt-0.data-00000-of-00001┃ ┃ ┃ ┃ ┃ ┗ 📜ckpt-0.index┃ ┃ ┃ ┃ ┣ 📂saved_model┃ ┃ ┃ ┃ ┃ ┣ 📂assets┃ ┃ ┃ ┃ ┃ ┣ 📂variables┃ ┃ ┃ ┃ ┃ ┃ ┣ 📜variables.data-00000-of-00001┃ ┃ ┃ ┃ ┃ ┃ ┗ 📜variables.index┃ ┃ ┃ ┃ ┃ ┗ 📜saved_model.pb┃ ┃ ┃ ┃ ┗ 📜pipeline.config┃ ┃ ┃ ┗ 📜efficientdet_d1_coco17_tpu-32.tar.gz┃ ┣ 📜exporter_main_v2.py┃ ┗ 📜model_main_tf2.py┣ 📜config.py┗ 📜setup.py We’ve done a lot of work to get here and set all the things ready to start the training. Here is how to do that: # from <project’s root folder>tensorboard — logdir=<logs folder>set NUM_TRAIN_STEPS=1000set CHECKPOINT_EVERY_N=1000set PIPELINE_CONFIG_PATH=<path to model’s pipeline.config>set MODEL_DIR=<logs folder>set SAMPLE_1_OF_N_EVAL_EXAMPLES=1set NUM_WORKERS=1python workspace\model_main_tf2.py \ — pipeline_config_path=%PIPELINE_CONFIG_PATH% \ — model_dir=%MODEL_DIR% \ — checkpoint_every_n=%CHECKPOINT_EVERY_N% \ — num_workers=%NUM_WORKERS% \ — num_train_steps=%NUM_TRAIN_STEPS% \ — sample_1_of_n_eval_examples=%SAMPLE_1_OF_N_EVAL_EXAMPLES% \ — alsologtostderr# (optionally in parallel terminal window)python workspace\model_main_tf2.py \ — pipeline_config_path=%PIPELINE_CONFIG_PATH% \ — model_dir=%MODEL_DIR% \ — checkpoint_dir=%MODEL_DIR% Now you can monitor the training process in your browser at http://localhost:6006: To export your model after training is done just run the following command: # from <project’s root folder>python workspace\exporter_main_v2.py \ — input_type=image_tensor \ — pipeline_config_path=%PIPELINE_CONFIG_PATH% \ — trained_checkpoint_dir=%MODEL_DIR% \ — output_directory=saved_models\efficientdet_d1_coco17_tpu-32 As we have our newly fine-tuned model saved we can begin to detect tables in documents. Earlier we have mentioned an inescapable issue of an object detection system - overlapping bounding boxes. Considering the over-segmented nature of borderless tables we are dealing with, our model will occasionally output more bounding boxes for a single object than you would expect. After all, it’s a sign that our object detector is firing correctly. To handle the removal of overlapping bounding boxes (that refer to the same object) we can use non-maximum suppression. Неre is how inferences of our detector look like originally and after performing non-maximum suppression: It seems like we have successfully solved those issues with predicted overlapping rectangles enclosed an object, but our detections are still falling short of the ground-truth bounding boxes. It’s going to happen as no model is perfect. We can measure the accuracy of our detector with the Intersection over Union (IoU) ratio. As the numerator, we compute the area of overlap between the predicted bounding box and the ground-truth bounding box. As the denominator, we compute the area encompassed by both the predicted bounding box and the ground-truth bounding box. An IoU score > 0.5 is normally considered a ‘good’ prediction [Rosenbrock, 2016]. For some images from our test set we have the following metrics: These will be the final steps of our three-part algorithm: after the (1) table is detected, we are going to (2) recognize its cells with OpenCV (as the table is borderless) and thoroughly allocate them to proper rows and columns, to proceed further with (3) text extraction from each allocated cell through Optical Character Recognition (OCR) with pytesseract. Most cell recognition algorithms are based on the line structure of the table. Clear and detectable lines are necessary for the proper identification of cells. As our table has none, we will manually reconstruct the table grid searching for white vertical and horizontal gaps on a thresholded and resized image. This approach is somewhat similar to one utilised here. After this step is done we can find contours with OpenCV (i.e. our cells borders), sort and allocate them into a table-like structure with: The whole work-flow is shown on the chart: At this point, we have all our boxes and their values sorted in the right order. It only remains to take every image-based box, prepare it for OCR by dilating and eroding and let pytesseract recognize the containing strings: Ough, it’s been a long walk! Our custom object detector can recognize semi-structured blocks of information (aka borderless tables) in a document to further transform them into machine-readable text. Though this model turns out to be not as accurate as we might have expected. Hence we have lots of room for its improvement: make changes in a configuration file of our model play with other models from Model Garden perform more conservative data augmentation try to re-use models, previously trained on table data (though not available for TF2 Object Detection API)
[ { "code": null, "e": 750, "s": 172, "text": "Document parsing is an initial step for transforming information into valuable business data. That information is often stored within commercial documents in tabular format or incidentally in data blocks without distinctive graphical borders. A borderless table may help to simplify the visual perception of semi-structured data for us, humans. From the machine-reading point of view, such presenting information on a page has quite a few shortcomings which make it difficult to separate the data belonging to a presumptive table structure from the surrounding textual context." }, { "code": null, "e": 1108, "s": 750, "text": "Tabular data extraction as a business challenge may have several ad-hoc or heuristiс rules-based solutions which definitely will fail with a table of a bit different layout or style. On a large scale, one should use a more general approach for identifying table-like structures in an image, more specifically a deep learning-based object detection approach." }, { "code": null, "e": 1145, "s": 1108, "text": "Deep learning-based object detection" }, { "code": null, "e": 1196, "s": 1145, "text": "Installation and setup of TF2 Object Detection API" }, { "code": null, "e": 1213, "s": 1196, "text": "Data preparation" }, { "code": null, "e": 1233, "s": 1213, "text": "Model configuration" }, { "code": null, "e": 1259, "s": 1233, "text": "Model training and saving" }, { "code": null, "e": 1317, "s": 1259, "text": "Table detection and cell recognition in a real-life image" }, { "code": null, "e": 2221, "s": 1317, "text": "Adrian Rosebrock, a known CV researcher, states in his “Gentle guide to deep learning object detection” that: “object detection, regardless of whether performed via deep learning or other computer vision techniques, builds on image classification and seeks to localize precisely an area where an object appears”. One approach to build a custom object detector, as he suggests, is to choose any classifier and precede it with an algorithm to select and provide regions of an image that may contain an object. Within this method, you are free to decide whether to use a traditional ML algorithm for image classification (utilising or not CNN as a feature extractor) or train a simple neural network to handle arbitrary large datasets. Despite its proven efficiency, this two-stage object detection paradigm, known as R-CNN, still relies on heavy computations and is not suitable for real-time application." }, { "code": null, "e": 2544, "s": 2221, "text": "It is further said in the abovementioned post that “another approach is to treat a pre-trained classification network as a base (backbone) network in a multi-component deep learning object detection framework (such as Faster R-CNN, SSD, or YOLO)”. Thus you will benefit from its complete end-to-end trainable architecture." }, { "code": null, "e": 2718, "s": 2544, "text": "Whatever be the choice it will put you further to an issue of overlapping bounding boxes. Hereinafter we will touch upon performing non-maximum suppression for this purpose." }, { "code": null, "e": 2853, "s": 2718, "text": "Meanwhile please refer to the transfer-learning flow-chart (see in interactive view) of an object detector for an arbitrary new class:" }, { "code": null, "e": 3204, "s": 2853, "text": "Due to its being quicker, less tedious and more accurate in general, the second approach has become widely adopted for table-like structures recognition in commercial and scientific papers. As an example, you can easily find implementations using YOLO, RetinaNet, Cascade R-CNN and other frameworks for the tabular data extraction from PDF documents." }, { "code": null, "e": 3402, "s": 3204, "text": "Moving forward with this tutorial you’ll learn how to use tools like TensorFlow (TF2) Object Detection API to build your custom object detectors using pre-trained state-of-the-art models with ease." }, { "code": null, "e": 4045, "s": 3402, "text": "Be aware it will not be an exhausting introduction to deep learning object detection, but rather a phase-by-phase description of interacting with TF2 Object detection API (and other tools) for solving a pronounced business problem (such as borderless table detection) within a specific development environment (Anaconda/Win10). Throughout the rest of this post, we will cover some aspects and the results of our modelling process in greater detail than others. Nonetheless, you’ll find the essential code examples to follow our experiment. To proceed you should have Anaconda and Tesseract installed and protobuf downloaded and added to PATH." }, { "code": null, "e": 4223, "s": 4045, "text": "Under a path of your choice create a new folder, that we will refer to hereinafter as a ‘project’s root folder’. From your terminal window run one-by-one the following commands:" }, { "code": null, "e": 4968, "s": 4223, "text": "# from <project’s root folder>conda create -n <new environment name> \\python=3.7 \\tensorflow=2.3 \\numpy=1.17.4 \\tf_slim \\cython \\gitconda activate <new environment name>git clone https://github.com/tensorflow/models.gitpip install git+https://github.com/philferriere/cocoapi.git#subdirectory=PythonAPIcd models\\research# from <project’s root folder>\\models\\researchprotoc object_detection\\protos\\*.proto — python_out=.copy object_detection\\packages\\tf2\\setup.py .python setup.py installpython object_detection\\builders\\model_builder_tf2_test.pyconda install imutils pdf2image beautifulsoup4 typeguardpip install tf-imagecopy object_detection\\model_main_tf2.py ..\\..\\workspace\\.copy object_detection\\exporter_main_v2.py ..\\..\\workspace\\.cd ..\\.." }, { "code": null, "e": 5276, "s": 4968, "text": "It will install core and some helper libraries into your local environment needed to use a TF2 Object Detection API and take care of your training dataset. From this step on you should be able to download a pretrained model from TF2 Model Garden and get inferences from it for respective pretrained classes." }, { "code": null, "e": 5817, "s": 5276, "text": "I hope you’ve succeeded so far! Please bear in mind that our final goal is to perform transfer learning using a pretrained model to detect a single ‘borderless’ class, which the model has no idea about while initial training. If you have studied our transfer-learning flow-chart you should have noticed that our starting point for the whole process is a dataset, whether annotated or not. If you need annotation, there are tons of solutions available. Pick the one that will give you annotations in XML, that is compatible with our example." }, { "code": null, "e": 6396, "s": 5817, "text": "The more annotated data we have the better (important: all table images for this post were selected from open data sources like this one and annotated/re-annotated by the author). But as soon as you’ll try your hands in manual data labelling you’ll understand how tedious this work is. Unfortunately, none of the popular python-libraries for image augmentation takes care of the selected bounding boxes. It is in our interest to multiply the initial dataset without the high cost of collecting and annotating new data. That is the case when a tf-image package will become handy." }, { "code": null, "e": 6617, "s": 6396, "text": "The above script will randomly transform the original image along with the object’s bounding boxes and save both the new image and corresponding XML file to disk. That is how our dataset looks after three-fold expansion:" }, { "code": null, "e": 6885, "s": 6617, "text": "The next steps will include splitting the data into train and test sets. Models based on the TF2 Object Detection API need a special format for all input data, called TFRecord. You’ll find corresponding scripts to split and convert your data in the Github repository." }, { "code": null, "e": 7082, "s": 6885, "text": "At this step, we’ll create a Label Map file (.pbtxt) to link our class label (‘borderless’) to some integer value. The TF2 Object Detection API needs this file for training and detection purposes:" }, { "code": null, "e": 7113, "s": 7082, "text": "item {id: 1name: ‘borderless’}" }, { "code": null, "e": 7346, "s": 7113, "text": "The actual model configuration is happening in the corresponding pipeline.config file. You can read an intro to model configuration and decide whether to configure the file manually or by running a script from the Github repository." }, { "code": null, "e": 7412, "s": 7346, "text": "By now your project’s root folder might look something like this:" }, { "code": null, "e": 8425, "s": 7412, "text": "📦borderless_tbls_detection┣ 📂images┃ ┣ 📂processed┃ ┃ ┣ 📂all_annots┃ ┃ ┃ ┗ 📜...XML┃ ┃ ┗ 📂all_images┃ ┃ ┃ ┗ 📜...jpg┃ ┣ 📂splitted┃ ┃ ┣ 📂test_set┃ ┃ ┃ ┣ 📜...jpg┃ ┃ ┃ ┗ 📜...XML┃ ┃ ┣ 📂train_set┃ ┃ ┃ ┣ 📜...jpg┃ ┃ ┃ ┗ 📜...XML┃ ┃ ┗ 📂val_set┃ ┗ 📜xml_style.XML┣ 📂models┃ ┗ 📂...┣ 📂scripts┃ ┣ 📜...py┣ 📂train_logs┣ 📂workspace┃ ┣ 📂data┃ ┃ ┣ 📜label_map.pbtxt┃ ┃ ┣ 📜test.csv┃ ┃ ┣ 📜test.record┃ ┃ ┣ 📜train.csv┃ ┃ ┣ 📜train.record┃ ┃ ┣ 📜val.csv┃ ┃ ┗ 📜val.record┃ ┣ 📂models┃ ┃ ┗ 📂efficientdet_d1_coco17_tpu-32┃ ┃ ┃ ┗ 📂v1┃ ┃ ┃ ┃ ┗ 📜pipeline.config┃ ┣ 📂pretrained_models┃ ┃ ┗ 📂datasets┃ ┃ ┃ ┣ 📂efficientdet_d1_coco17_tpu-32┃ ┃ ┃ ┃ ┣ 📂checkpoint┃ ┃ ┃ ┃ ┃ ┣ 📜checkpoint┃ ┃ ┃ ┃ ┃ ┣ 📜ckpt-0.data-00000-of-00001┃ ┃ ┃ ┃ ┃ ┗ 📜ckpt-0.index┃ ┃ ┃ ┃ ┣ 📂saved_model┃ ┃ ┃ ┃ ┃ ┣ 📂assets┃ ┃ ┃ ┃ ┃ ┣ 📂variables┃ ┃ ┃ ┃ ┃ ┃ ┣ 📜variables.data-00000-of-00001┃ ┃ ┃ ┃ ┃ ┃ ┗ 📜variables.index┃ ┃ ┃ ┃ ┃ ┗ 📜saved_model.pb┃ ┃ ┃ ┃ ┗ 📜pipeline.config┃ ┃ ┃ ┗ 📜efficientdet_d1_coco17_tpu-32.tar.gz┃ ┣ 📜exporter_main_v2.py┃ ┗ 📜model_main_tf2.py┣ 📜config.py┗ 📜setup.py" }, { "code": null, "e": 8538, "s": 8425, "text": "We’ve done a lot of work to get here and set all the things ready to start the training. Here is how to do that:" }, { "code": null, "e": 9272, "s": 8538, "text": "# from <project’s root folder>tensorboard — logdir=<logs folder>set NUM_TRAIN_STEPS=1000set CHECKPOINT_EVERY_N=1000set PIPELINE_CONFIG_PATH=<path to model’s pipeline.config>set MODEL_DIR=<logs folder>set SAMPLE_1_OF_N_EVAL_EXAMPLES=1set NUM_WORKERS=1python workspace\\model_main_tf2.py \\ — pipeline_config_path=%PIPELINE_CONFIG_PATH% \\ — model_dir=%MODEL_DIR% \\ — checkpoint_every_n=%CHECKPOINT_EVERY_N% \\ — num_workers=%NUM_WORKERS% \\ — num_train_steps=%NUM_TRAIN_STEPS% \\ — sample_1_of_n_eval_examples=%SAMPLE_1_OF_N_EVAL_EXAMPLES% \\ — alsologtostderr# (optionally in parallel terminal window)python workspace\\model_main_tf2.py \\ — pipeline_config_path=%PIPELINE_CONFIG_PATH% \\ — model_dir=%MODEL_DIR% \\ — checkpoint_dir=%MODEL_DIR%" }, { "code": null, "e": 9355, "s": 9272, "text": "Now you can monitor the training process in your browser at http://localhost:6006:" }, { "code": null, "e": 9431, "s": 9355, "text": "To export your model after training is done just run the following command:" }, { "code": null, "e": 9677, "s": 9431, "text": "# from <project’s root folder>python workspace\\exporter_main_v2.py \\ — input_type=image_tensor \\ — pipeline_config_path=%PIPELINE_CONFIG_PATH% \\ — trained_checkpoint_dir=%MODEL_DIR% \\ — output_directory=saved_models\\efficientdet_d1_coco17_tpu-32" }, { "code": null, "e": 10239, "s": 9677, "text": "As we have our newly fine-tuned model saved we can begin to detect tables in documents. Earlier we have mentioned an inescapable issue of an object detection system - overlapping bounding boxes. Considering the over-segmented nature of borderless tables we are dealing with, our model will occasionally output more bounding boxes for a single object than you would expect. After all, it’s a sign that our object detector is firing correctly. To handle the removal of overlapping bounding boxes (that refer to the same object) we can use non-maximum suppression." }, { "code": null, "e": 10345, "s": 10239, "text": "Неre is how inferences of our detector look like originally and after performing non-maximum suppression:" }, { "code": null, "e": 10995, "s": 10345, "text": "It seems like we have successfully solved those issues with predicted overlapping rectangles enclosed an object, but our detections are still falling short of the ground-truth bounding boxes. It’s going to happen as no model is perfect. We can measure the accuracy of our detector with the Intersection over Union (IoU) ratio. As the numerator, we compute the area of overlap between the predicted bounding box and the ground-truth bounding box. As the denominator, we compute the area encompassed by both the predicted bounding box and the ground-truth bounding box. An IoU score > 0.5 is normally considered a ‘good’ prediction [Rosenbrock, 2016]." }, { "code": null, "e": 11060, "s": 10995, "text": "For some images from our test set we have the following metrics:" }, { "code": null, "e": 11421, "s": 11060, "text": "These will be the final steps of our three-part algorithm: after the (1) table is detected, we are going to (2) recognize its cells with OpenCV (as the table is borderless) and thoroughly allocate them to proper rows and columns, to proceed further with (3) text extraction from each allocated cell through Optical Character Recognition (OCR) with pytesseract." }, { "code": null, "e": 11789, "s": 11421, "text": "Most cell recognition algorithms are based on the line structure of the table. Clear and detectable lines are necessary for the proper identification of cells. As our table has none, we will manually reconstruct the table grid searching for white vertical and horizontal gaps on a thresholded and resized image. This approach is somewhat similar to one utilised here." }, { "code": null, "e": 11929, "s": 11789, "text": "After this step is done we can find contours with OpenCV (i.e. our cells borders), sort and allocate them into a table-like structure with:" }, { "code": null, "e": 11972, "s": 11929, "text": "The whole work-flow is shown on the chart:" }, { "code": null, "e": 12197, "s": 11972, "text": "At this point, we have all our boxes and their values sorted in the right order. It only remains to take every image-based box, prepare it for OCR by dilating and eroding and let pytesseract recognize the containing strings:" }, { "code": null, "e": 12522, "s": 12197, "text": "Ough, it’s been a long walk! Our custom object detector can recognize semi-structured blocks of information (aka borderless tables) in a document to further transform them into machine-readable text. Though this model turns out to be not as accurate as we might have expected. Hence we have lots of room for its improvement:" }, { "code": null, "e": 12572, "s": 12522, "text": "make changes in a configuration file of our model" }, { "code": null, "e": 12613, "s": 12572, "text": "play with other models from Model Garden" }, { "code": null, "e": 12657, "s": 12613, "text": "perform more conservative data augmentation" } ]
How to create fixed/sticky footer on the bottom using Tailwind CSS ? - GeeksforGeeks
12 May, 2021 In this article, we are going to create a fixed/sticky footer on the bottom using Tailwind CSS. Tailwind CSS is a highly customizable, utility-first CSS framework from which we can use utility classes to build any design. With Tailwind CSS we can create a design by simply adding classes. Installation: Method 1: Install Tailwind via npm Step 1:npm init -y Step 1: npm init -y Step 2:npm install tailwindcss Step 2: npm install tailwindcss Step 3: Now we have to add Tailwind to our CSS by using the @tailwind directive to inject Tailwind’s base, components, and utility styles into our CSS file. @tailwind base; @tailwind components; @tailwind utilities; Step 3: Now we have to add Tailwind to our CSS by using the @tailwind directive to inject Tailwind’s base, components, and utility styles into our CSS file. @tailwind base; @tailwind components; @tailwind utilities; Step 4: It is an optional step that is used to create a Tailwind config file.npx tailwindcss init Step 4: It is an optional step that is used to create a Tailwind config file. npx tailwindcss init Step 5:npx tailwindcss build styles.css -o output.css Step 5: npx tailwindcss build styles.css -o output.css Method 2: Using Tailwind via CDN <link href=”https://unpkg.com/tailwindcss@^2/dist/tailwind.min.css” rel=”stylesheet”> Example: In the following example, the following classes are used. The class bg-{color} is used for the background color of the element. Similarly, p-{size} is used for padding of the element, text-{size} is used for the font size of text, text-center is used to align the text to the center, text-{color} is for the font color of text, border-b-{width} is for the border in the bottom, border-t is for the border at the top, border-{color} is for border color of the element, fixed is for a fixed position of the elements, inset-x-0 is right and left properties of the element, bottom-0 is for the bottom property. HTML <!DOCTYPE html><html> <head> <meta charset="UTF-8" /> <link href="https://unpkg.com/tailwindcss@^2/dist/tailwind.min.css" rel="stylesheet"/> </head> <body style="height: 1000px"> <h1 style="color: green; text-align: center"> GeeksforGeeks </h1> <header class="text-2xl text-center text-green-800 border-b-2 border-grey-500"> Sticky footer using Tailwind CSS </header> <div> <p class="p-2 w-9/12"> </p> </div> <footer class="bg-green-700 text-3xl text-white text-center border-t-4 border-red-500 fixed inset-x-0 bottom-0 p-4"> This is sticky fixed Footer. </footer> </body></html> Output: Picked Tailwind CSS CSS Web Technologies Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments Primer CSS Flexbox Flex Direction HTML Course | First Web Page | Printing Hello World Design a web page using HTML and CSS Search Bar using HTML, CSS and JavaScript How to wrap the text around an image using HTML and CSS ? Express.js express.Router() Function Installation of Node.js on Linux How to set input type date in dd-mm-yyyy format using HTML ? Differences between Functional Components and Class Components in React How to float three div side by side using CSS?
[ { "code": null, "e": 24985, "s": 24957, "text": "\n12 May, 2021" }, { "code": null, "e": 25276, "s": 24985, "text": "In this article, we are going to create a fixed/sticky footer on the bottom using Tailwind CSS. Tailwind CSS is a highly customizable, utility-first CSS framework from which we can use utility classes to build any design. With Tailwind CSS we can create a design by simply adding classes. " }, { "code": null, "e": 25290, "s": 25276, "text": "Installation:" }, { "code": null, "e": 25325, "s": 25290, "text": "Method 1: Install Tailwind via npm" }, { "code": null, "e": 25344, "s": 25325, "text": "Step 1:npm init -y" }, { "code": null, "e": 25352, "s": 25344, "text": "Step 1:" }, { "code": null, "e": 25364, "s": 25352, "text": "npm init -y" }, { "code": null, "e": 25395, "s": 25364, "text": "Step 2:npm install tailwindcss" }, { "code": null, "e": 25403, "s": 25395, "text": "Step 2:" }, { "code": null, "e": 25427, "s": 25403, "text": "npm install tailwindcss" }, { "code": null, "e": 25647, "s": 25427, "text": "Step 3: Now we have to add Tailwind to our CSS by using the @tailwind directive to inject Tailwind’s base, components, and utility styles into our CSS file. @tailwind base; \n@tailwind components; \n@tailwind utilities;" }, { "code": null, "e": 25805, "s": 25647, "text": "Step 3: Now we have to add Tailwind to our CSS by using the @tailwind directive to inject Tailwind’s base, components, and utility styles into our CSS file. " }, { "code": null, "e": 25868, "s": 25805, "text": "@tailwind base; \n@tailwind components; \n@tailwind utilities;" }, { "code": null, "e": 25967, "s": 25868, "text": "Step 4: It is an optional step that is used to create a Tailwind config file.npx tailwindcss init " }, { "code": null, "e": 26045, "s": 25967, "text": "Step 4: It is an optional step that is used to create a Tailwind config file." }, { "code": null, "e": 26067, "s": 26045, "text": "npx tailwindcss init " }, { "code": null, "e": 26123, "s": 26067, "text": "Step 5:npx tailwindcss build styles.css -o output.css " }, { "code": null, "e": 26131, "s": 26123, "text": "Step 5:" }, { "code": null, "e": 26180, "s": 26131, "text": "npx tailwindcss build styles.css -o output.css " }, { "code": null, "e": 26213, "s": 26180, "text": "Method 2: Using Tailwind via CDN" }, { "code": null, "e": 26299, "s": 26213, "text": "<link href=”https://unpkg.com/tailwindcss@^2/dist/tailwind.min.css” rel=”stylesheet”>" }, { "code": null, "e": 26367, "s": 26299, "text": "Example: In the following example, the following classes are used. " }, { "code": null, "e": 26918, "s": 26367, "text": "The class bg-{color} is used for the background color of the element. Similarly, p-{size} is used for padding of the element, text-{size} is used for the font size of text, text-center is used to align the text to the center, text-{color} is for the font color of text, border-b-{width} is for the border in the bottom, border-t is for the border at the top, border-{color} is for border color of the element, fixed is for a fixed position of the elements, inset-x-0 is right and left properties of the element, bottom-0 is for the bottom property. " }, { "code": null, "e": 26923, "s": 26918, "text": "HTML" }, { "code": "<!DOCTYPE html><html> <head> <meta charset=\"UTF-8\" /> <link href=\"https://unpkg.com/tailwindcss@^2/dist/tailwind.min.css\" rel=\"stylesheet\"/> </head> <body style=\"height: 1000px\"> <h1 style=\"color: green; text-align: center\"> GeeksforGeeks </h1> <header class=\"text-2xl text-center text-green-800 border-b-2 border-grey-500\"> Sticky footer using Tailwind CSS </header> <div> <p class=\"p-2 w-9/12\"> </p> </div> <footer class=\"bg-green-700 text-3xl text-white text-center border-t-4 border-red-500 fixed inset-x-0 bottom-0 p-4\"> This is sticky fixed Footer. </footer> </body></html>", "e": 27715, "s": 26923, "text": null }, { "code": null, "e": 27723, "s": 27715, "text": "Output:" }, { "code": null, "e": 27730, "s": 27723, "text": "Picked" }, { "code": null, "e": 27743, "s": 27730, "text": "Tailwind CSS" }, { "code": null, "e": 27747, "s": 27743, "text": "CSS" }, { "code": null, "e": 27764, "s": 27747, "text": "Web Technologies" }, { "code": null, "e": 27862, "s": 27764, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 27871, "s": 27862, "text": "Comments" }, { "code": null, "e": 27884, "s": 27871, "text": "Old Comments" }, { "code": null, "e": 27918, "s": 27884, "text": "Primer CSS Flexbox Flex Direction" }, { "code": null, "e": 27970, "s": 27918, "text": "HTML Course | First Web Page | Printing Hello World" }, { "code": null, "e": 28007, "s": 27970, "text": "Design a web page using HTML and CSS" }, { "code": null, "e": 28049, "s": 28007, "text": "Search Bar using HTML, CSS and JavaScript" }, { "code": null, "e": 28107, "s": 28049, "text": "How to wrap the text around an image using HTML and CSS ?" }, { "code": null, "e": 28144, "s": 28107, "text": "Express.js express.Router() Function" }, { "code": null, "e": 28177, "s": 28144, "text": "Installation of Node.js on Linux" }, { "code": null, "e": 28238, "s": 28177, "text": "How to set input type date in dd-mm-yyyy format using HTML ?" }, { "code": null, "e": 28310, "s": 28238, "text": "Differences between Functional Components and Class Components in React" } ]
How to split JavaScript Number into individual digits?
To spilt a number into digits and print their sum, try to run the following code − Live Demo <!DOCTYPE html> <html> <body> <script> var a = 28573; var sum = 0; while(a > 0) { sum += a % 10; a = Math.floor(a / 10); } document.write("Sum of digits = "+sum); </script> </body> </html> Sum of digits = 25
[ { "code": null, "e": 1145, "s": 1062, "text": "To spilt a number into digits and print their sum, try to run the following code −" }, { "code": null, "e": 1155, "s": 1145, "text": "Live Demo" }, { "code": null, "e": 1431, "s": 1155, "text": "<!DOCTYPE html>\n<html>\n <body>\n <script>\n var a = 28573;\n var sum = 0;\n while(a > 0) {\n sum += a % 10;\n a = Math.floor(a / 10);\n }\n document.write(\"Sum of digits = \"+sum);\n </script>\n </body>\n</html>" }, { "code": null, "e": 1450, "s": 1431, "text": "Sum of digits = 25" } ]
R: rank vs. order. If you’re learning R you’ve come across... | by Rebecca Peltz | Towards Data Science
If you’re learning R you’ve come across the sort, rank and order functions. Because there is similarity and even overlap in the semantics, questions come up: what exactly does each do and what are the use cases for each? All three functions require that the values they operate on are comparable. Comparisons in R can apply to string, numeric, complex and logical date types. Sort, Rank, and Order are functions in R. They can be applied to a vector or a factor. If you are used to thinking of data in terms of rows and columns, a vector represents a column of data. A factor is created from a vector and represents discrete labeled values. In the R code below, X is loaded with data and then sorted, ranked, and ordered. R reports the results as vectors. X = c(3,2,1) X 3 2 1 sort(X)[1] 1 2 3rank(X)[1] 1 2 3order(X)[1] 1 2 3 It seems clear enough: you load data into a vector using the “c”ombine function when you view X it appears arranged as it was loaded when you sort X, you see a vector containing values from X arranged in ascending order when you rank X, you see a vector containing values from X arranged in ascending order (like sort) when you order X, you see a vector containing values from X arranged in ascending order (like sort) Now, let's apply a simple permutation when creating the X vector and run these functions. X = c(2,3,1) X 2 3 1sort(X)[1] 1 2 3rank(X)[1] 2 3 1order(X)[1] 3 1 2 In the output above the sort function affirms what we stated above, but the rank and order are more difficult to explain. Now, look at a different vector with a similar permutation on a different range of integers. X = c(5,6,4) X 5 6 4sort(X)[1] 4 5 6rank(X)[1] 2 3 1order(X)[1] 3 1 2 In the code above we see the same rank and order for “5, 6, 4” as we did for “2, 3, 1”. The reason that these two sequences have the same rank and order is that rank and order are reporting on relative locations as opposed to relative values. Rank and order are based on the results of an ascending sort of data in the vector. Specifically, the range of values returned by rank and order is the range of indexes of values in the original sequence. Rank references the position of the value in the sorted vector and is in the same order as the original sequence Order returns the position of the original value and is in the order of sorted sequence, that is smallest value to largest value The graphic below helps tie together the values reported by rank and order with the positions from which they come. The “1,2,3” sequence first presented that returned the vector “1,2,3” for both Rank and Order is actually a special sequence because these values and several other permutations of “1,2,3” cause rank and order to behave as involutory functions. An involuntary function is a function that is its own inverse. X = c(1,2,3)RANK(X) == ORDER(X) == XRANK(ORDER(X)) == XORDER(RANK(X)) == 1:length(X) In the code below, you can see all six of the permutations of “1,2,3” tested to see if they are involutive (a function that when applied twice will give you the starting value). The two permutations that do not result in involutive functionality can be identified by the cycles which they break down into. See the article rank vs order in R below for more information on involutive cycles. X = c(1,2,3)all(order(rank(X)) == X)[1] TRUEX = c(2,3,1)all(order(rank(X)) == X)[1] FALSEX = c(3,1,2)all(order(rank(X)) == X)[1] FALSEX = c(1,3,2)all(order(rank(X)) == X)[1] TRUEX = c(2,1,3)all(order(rank(X)) == X)[1] TRUEX = c(3,2,1)all(order(rank(X)) == X)[1] TRUEall(order(X)[rank(X)] == rank(x)[order(X)]) == 1:length(X)TRUE While it’s tempting when learning to look at simple data sets to help understand the behavior of functions, it can lead to confusing conclusions when the arrangement of the data affects the output of the functions. For any vector sequence in ascending order, the code below demonstrates the relationship between Order and Rank as they interact with each other. The Order of the Rank will always equal the Rank of the Order. X = c(100,200,300)all(order(X)[rank(X)] == rank(X)[order(X)])TRUE In addition, the code below verifies that for any sequence in ascending order both the Order of the Rank and the Rank of the Order will always equal a vector made up of the positions of the ordered elements. x = c(100,200,300)all(order(X)[rank(X)] == 1:length(X))TRUEall(rank(X)[order(X)] == 1:length(X))TRUE1:length(X)[1] 1 2 3 You can use the order function to sort a dataframe. The sort command can be used to create a new vector from any vector of comparable values into a vector arrange in an ascending sequence. The default sort order is ascending, but there are options to make it descending, as well as options for dealing with undefined values and specifying a sorting method. When you read data from a file system into a data frame or construct the data frame in code, you have a structure that contains rows and columns of data that may be of different types. In order to “sort” the row of a data frame by column values, whether it’s a single column or multiple columns, you must use the order command as the sort command only sorts vectors. To see how this works, the example below builds up a data frame from raw data loaded into vectors. This data could easily have been read in from a CSV or other formatted text file as well. Note: enclosing the last instruction in parentheses causes the data frame to be referenced by the test.data variable and displays what’s in the test.data variable. The first integer in the display is a counter identifier assigned by R to the rows in the data frame. size = 5sex=sample(c("male","female"),size,replace=T)age = sample(21:100, size, replace=T)degree = sample(c("BA","BS","MS","MBA"), size, replace=T)(test.data = data.frame(sex=sex, age=age, degree=degree))sex age degree1 female 30 BA2 male 49 BA3 male 39 MBA4 male 27 MS5 male 61 MS We can sort the data by age using the order command. The order function is passed the name of the column to order by and the order is ascending. The result of the order command is a vector where each value references the value of the position of the item in the original data frame and it, itself, is located in the sorted data’s position. For example, the 1st age in the original data frame is 30 and in the sorted data frame 30 will be in the 2nd position. Therefore, the value 1 is located in the 2nd position of the order vector. Once the order vector is obtained it is used to extract data from the original test.data. You can see the original counter id in the result and how it matches the order vector used to do the sort. R extracts data from a data frame (or matrix) using the square brackets with a Row, Column designation. order(test.data$age)[1] 4 1 3 2 5test.data[order(test.data$age),]sex age degree4 male 27 MS1 female 30 BA3 male 39 MBA2 male 49 BA5 male 61 MS The data frame can be sorted in descending order by using the negative sign in front of the column name specified by the order command. order(-test.data$age)[1] 5 2 3 1 4test.data[order(-test.data$age),]5 male 61 MS2 male 49 BA3 male 39 MBA1 female 30 BA4 male 27 MS We can also provide multi-column sorts by adding multiple columns to the order command. order(test.data$degree,-test.data$age)[1] 2 1 3 5 4test.data[order(test.data$degree,-test.data$age),]sex age degree2 male 49 BA1 female 30 BA3 male 39 MBA5 male 61 MS4 male 27 MS You can use the rank function to create a value that represents the relative standing of a value within its sequence. The IEEE provided a list of the top 10 programming languages for 2017. They are stored in a file, in my local file system, sorted in alphabetical order by language name. The code below will read them into a variable which references them by the name language.ieee and displays the contents. (language.ieee =read.csv(file="language-scores.csv")) X language score1 2 C 99.72 5 C# 87.73 4 C++ 97.14 9 Go 75.15 3 Java 99.56 7 JavaScript 85.67 8 PHP 81.28 1 Python 100.09 6 R 87.710 10 Swift 73.1 We can get a vector of the ranked data. The data in the rank vector appears as float because there is a tie: C# is tied with R for 5th and 6th place. There are options for dealing with ties in the rank function, but the default is to use the “average” method and assign each the average value. The values themselves represent the descending order of the corresponding value by the position of the value in the original data set. A higher rank value represents a larger data value. rank(language.ieee$score)9.0 5.5 7.0 2.0 8.0 4.0 3.0 10.0 5.5 1.0 I can use the rank vector to order the data by rank, that is, the descending order of scores, by supplying the negative rank to the order command. language.ieee[order(-rank(language.ieee$score)),] X language score8 1 Python 100.01 2 C 99.75 3 Java 99.53 4 C++ 97.12 5 C# 87.79 6 R 87.76 7 JavaScript 85.67 8 PHP 81.24 9 Go 75.110 10 Swift 73.1 Calculating rank is not only used for ordering data. Correlation of rankings can be used to test the null hypothesis of the relationship between two variables. Since variables may differ in type and scale, rank provides a sort of normalization. For example see studies on the use of Spearman’s Rank Correlation: https://geographyfieldwork.com/SpearmansRank.htm. R is a statistical programming language with many functions that help with formatting and processing data. Its services are made available through function calls. In addition to reading the documentation, it helps to run data sets through these functions to help figure out what exactly they do. Sort, Order, and Rank are semantically the same, but in practice, they have very different uses and sometimes work with each other to achieve the desired result.
[ { "code": null, "e": 393, "s": 172, "text": "If you’re learning R you’ve come across the sort, rank and order functions. Because there is similarity and even overlap in the semantics, questions come up: what exactly does each do and what are the use cases for each?" }, { "code": null, "e": 548, "s": 393, "text": "All three functions require that the values they operate on are comparable. Comparisons in R can apply to string, numeric, complex and logical date types." }, { "code": null, "e": 928, "s": 548, "text": "Sort, Rank, and Order are functions in R. They can be applied to a vector or a factor. If you are used to thinking of data in terms of rows and columns, a vector represents a column of data. A factor is created from a vector and represents discrete labeled values. In the R code below, X is loaded with data and then sorted, ranked, and ordered. R reports the results as vectors." }, { "code": null, "e": 999, "s": 928, "text": "X = c(3,2,1) X 3 2 1 sort(X)[1] 1 2 3rank(X)[1] 1 2 3order(X)[1] 1 2 3" }, { "code": null, "e": 1022, "s": 999, "text": "It seems clear enough:" }, { "code": null, "e": 1079, "s": 1022, "text": "you load data into a vector using the “c”ombine function" }, { "code": null, "e": 1132, "s": 1079, "text": "when you view X it appears arranged as it was loaded" }, { "code": null, "e": 1219, "s": 1132, "text": "when you sort X, you see a vector containing values from X arranged in ascending order" }, { "code": null, "e": 1318, "s": 1219, "text": "when you rank X, you see a vector containing values from X arranged in ascending order (like sort)" }, { "code": null, "e": 1418, "s": 1318, "text": "when you order X, you see a vector containing values from X arranged in ascending order (like sort)" }, { "code": null, "e": 1508, "s": 1418, "text": "Now, let's apply a simple permutation when creating the X vector and run these functions." }, { "code": null, "e": 1578, "s": 1508, "text": "X = c(2,3,1) X 2 3 1sort(X)[1] 1 2 3rank(X)[1] 2 3 1order(X)[1] 3 1 2" }, { "code": null, "e": 1793, "s": 1578, "text": "In the output above the sort function affirms what we stated above, but the rank and order are more difficult to explain. Now, look at a different vector with a similar permutation on a different range of integers." }, { "code": null, "e": 1863, "s": 1793, "text": "X = c(5,6,4) X 5 6 4sort(X)[1] 4 5 6rank(X)[1] 2 3 1order(X)[1] 3 1 2" }, { "code": null, "e": 2311, "s": 1863, "text": "In the code above we see the same rank and order for “5, 6, 4” as we did for “2, 3, 1”. The reason that these two sequences have the same rank and order is that rank and order are reporting on relative locations as opposed to relative values. Rank and order are based on the results of an ascending sort of data in the vector. Specifically, the range of values returned by rank and order is the range of indexes of values in the original sequence." }, { "code": null, "e": 2424, "s": 2311, "text": "Rank references the position of the value in the sorted vector and is in the same order as the original sequence" }, { "code": null, "e": 2553, "s": 2424, "text": "Order returns the position of the original value and is in the order of sorted sequence, that is smallest value to largest value" }, { "code": null, "e": 2669, "s": 2553, "text": "The graphic below helps tie together the values reported by rank and order with the positions from which they come." }, { "code": null, "e": 2976, "s": 2669, "text": "The “1,2,3” sequence first presented that returned the vector “1,2,3” for both Rank and Order is actually a special sequence because these values and several other permutations of “1,2,3” cause rank and order to behave as involutory functions. An involuntary function is a function that is its own inverse." }, { "code": null, "e": 3061, "s": 2976, "text": "X = c(1,2,3)RANK(X) == ORDER(X) == XRANK(ORDER(X)) == XORDER(RANK(X)) == 1:length(X)" }, { "code": null, "e": 3451, "s": 3061, "text": "In the code below, you can see all six of the permutations of “1,2,3” tested to see if they are involutive (a function that when applied twice will give you the starting value). The two permutations that do not result in involutive functionality can be identified by the cycles which they break down into. See the article rank vs order in R below for more information on involutive cycles." }, { "code": null, "e": 3780, "s": 3451, "text": "X = c(1,2,3)all(order(rank(X)) == X)[1] TRUEX = c(2,3,1)all(order(rank(X)) == X)[1] FALSEX = c(3,1,2)all(order(rank(X)) == X)[1] FALSEX = c(1,3,2)all(order(rank(X)) == X)[1] TRUEX = c(2,1,3)all(order(rank(X)) == X)[1] TRUEX = c(3,2,1)all(order(rank(X)) == X)[1] TRUEall(order(X)[rank(X)] == rank(x)[order(X)]) == 1:length(X)TRUE" }, { "code": null, "e": 3995, "s": 3780, "text": "While it’s tempting when learning to look at simple data sets to help understand the behavior of functions, it can lead to confusing conclusions when the arrangement of the data affects the output of the functions." }, { "code": null, "e": 4204, "s": 3995, "text": "For any vector sequence in ascending order, the code below demonstrates the relationship between Order and Rank as they interact with each other. The Order of the Rank will always equal the Rank of the Order." }, { "code": null, "e": 4270, "s": 4204, "text": "X = c(100,200,300)all(order(X)[rank(X)] == rank(X)[order(X)])TRUE" }, { "code": null, "e": 4478, "s": 4270, "text": "In addition, the code below verifies that for any sequence in ascending order both the Order of the Rank and the Rank of the Order will always equal a vector made up of the positions of the ordered elements." }, { "code": null, "e": 4599, "s": 4478, "text": "x = c(100,200,300)all(order(X)[rank(X)] == 1:length(X))TRUEall(rank(X)[order(X)] == 1:length(X))TRUE1:length(X)[1] 1 2 3" }, { "code": null, "e": 4651, "s": 4599, "text": "You can use the order function to sort a dataframe." }, { "code": null, "e": 4956, "s": 4651, "text": "The sort command can be used to create a new vector from any vector of comparable values into a vector arrange in an ascending sequence. The default sort order is ascending, but there are options to make it descending, as well as options for dealing with undefined values and specifying a sorting method." }, { "code": null, "e": 5323, "s": 4956, "text": "When you read data from a file system into a data frame or construct the data frame in code, you have a structure that contains rows and columns of data that may be of different types. In order to “sort” the row of a data frame by column values, whether it’s a single column or multiple columns, you must use the order command as the sort command only sorts vectors." }, { "code": null, "e": 5778, "s": 5323, "text": "To see how this works, the example below builds up a data frame from raw data loaded into vectors. This data could easily have been read in from a CSV or other formatted text file as well. Note: enclosing the last instruction in parentheses causes the data frame to be referenced by the test.data variable and displays what’s in the test.data variable. The first integer in the display is a counter identifier assigned by R to the rows in the data frame." }, { "code": null, "e": 6093, "s": 5778, "text": "size = 5sex=sample(c(\"male\",\"female\"),size,replace=T)age = sample(21:100, size, replace=T)degree = sample(c(\"BA\",\"BS\",\"MS\",\"MBA\"), size, replace=T)(test.data = data.frame(sex=sex, age=age, degree=degree))sex age degree1 female 30 BA2 male 49 BA3 male 39 MBA4 male 27 MS5 male 61 MS" }, { "code": null, "e": 6627, "s": 6093, "text": "We can sort the data by age using the order command. The order function is passed the name of the column to order by and the order is ascending. The result of the order command is a vector where each value references the value of the position of the item in the original data frame and it, itself, is located in the sorted data’s position. For example, the 1st age in the original data frame is 30 and in the sorted data frame 30 will be in the 2nd position. Therefore, the value 1 is located in the 2nd position of the order vector." }, { "code": null, "e": 6928, "s": 6627, "text": "Once the order vector is obtained it is used to extract data from the original test.data. You can see the original counter id in the result and how it matches the order vector used to do the sort. R extracts data from a data frame (or matrix) using the square brackets with a Row, Column designation." }, { "code": null, "e": 7103, "s": 6928, "text": "order(test.data$age)[1] 4 1 3 2 5test.data[order(test.data$age),]sex age degree4 male 27 MS1 female 30 BA3 male 39 MBA2 male 49 BA5 male 61 MS" }, { "code": null, "e": 7239, "s": 7103, "text": "The data frame can be sorted in descending order by using the negative sign in front of the column name specified by the order command." }, { "code": null, "e": 7402, "s": 7239, "text": "order(-test.data$age)[1] 5 2 3 1 4test.data[order(-test.data$age),]5 male 61 MS2 male 49 BA3 male 39 MBA1 female 30 BA4 male 27 MS" }, { "code": null, "e": 7490, "s": 7402, "text": "We can also provide multi-column sorts by adding multiple columns to the order command." }, { "code": null, "e": 7701, "s": 7490, "text": "order(test.data$degree,-test.data$age)[1] 2 1 3 5 4test.data[order(test.data$degree,-test.data$age),]sex age degree2 male 49 BA1 female 30 BA3 male 39 MBA5 male 61 MS4 male 27 MS" }, { "code": null, "e": 7819, "s": 7701, "text": "You can use the rank function to create a value that represents the relative standing of a value within its sequence." }, { "code": null, "e": 8110, "s": 7819, "text": "The IEEE provided a list of the top 10 programming languages for 2017. They are stored in a file, in my local file system, sorted in alphabetical order by language name. The code below will read them into a variable which references them by the name language.ieee and displays the contents." }, { "code": null, "e": 8406, "s": 8110, "text": "(language.ieee =read.csv(file=\"language-scores.csv\")) X language score1 2 C 99.72 5 C# 87.73 4 C++ 97.14 9 Go 75.15 3 Java 99.56 7 JavaScript 85.67 8 PHP 81.28 1 Python 100.09 6 R 87.710 10 Swift 73.1" }, { "code": null, "e": 8887, "s": 8406, "text": "We can get a vector of the ranked data. The data in the rank vector appears as float because there is a tie: C# is tied with R for 5th and 6th place. There are options for dealing with ties in the rank function, but the default is to use the “average” method and assign each the average value. The values themselves represent the descending order of the corresponding value by the position of the value in the original data set. A higher rank value represents a larger data value." }, { "code": null, "e": 8961, "s": 8887, "text": "rank(language.ieee$score)9.0 5.5 7.0 2.0 8.0 4.0 3.0 10.0 5.5 1.0" }, { "code": null, "e": 9108, "s": 8961, "text": "I can use the rank vector to order the data by rank, that is, the descending order of scores, by supplying the negative rank to the order command." }, { "code": null, "e": 9400, "s": 9108, "text": "language.ieee[order(-rank(language.ieee$score)),] X language score8 1 Python 100.01 2 C 99.75 3 Java 99.53 4 C++ 97.12 5 C# 87.79 6 R 87.76 7 JavaScript 85.67 8 PHP 81.24 9 Go 75.110 10 Swift 73.1" }, { "code": null, "e": 9762, "s": 9400, "text": "Calculating rank is not only used for ordering data. Correlation of rankings can be used to test the null hypothesis of the relationship between two variables. Since variables may differ in type and scale, rank provides a sort of normalization. For example see studies on the use of Spearman’s Rank Correlation: https://geographyfieldwork.com/SpearmansRank.htm." } ]
How to change the color of box of boxplot in base R?
To change the color of box of boxplot in base R, we can use col argument inside boxplot function. For example, if we have a vector called V and we want to create a boxplot of V without red colored box then we can use the following command − boxplot(x,col="red") To change the color of box of boxplot in base R, use the code given below − x<-rnorm(100) boxplot(x) If you execute the above given code, it generates the following output − To change the color of box of boxplot in base R, use the code given below − x<-rnorm(100) boxplot(x,col="blue") If you execute the above given code, it generates the following output − To change the color of box of boxplot in base R, use the code given below − x<-rnorm(100) boxplot(x,col="red") If you execute the above given code, it generates the following output −
[ { "code": null, "e": 1160, "s": 1062, "text": "To change the color of box of boxplot in base R, we can use col argument inside boxplot function." }, { "code": null, "e": 1303, "s": 1160, "text": "For example, if we have a vector called V and we want to create a boxplot of V without red colored box then we can use the following command −" }, { "code": null, "e": 1324, "s": 1303, "text": "boxplot(x,col=\"red\")" }, { "code": null, "e": 1400, "s": 1324, "text": "To change the color of box of boxplot in base R, use the code given below −" }, { "code": null, "e": 1425, "s": 1400, "text": "x<-rnorm(100)\nboxplot(x)" }, { "code": null, "e": 1498, "s": 1425, "text": "If you execute the above given code, it generates the following output −" }, { "code": null, "e": 1574, "s": 1498, "text": "To change the color of box of boxplot in base R, use the code given below −" }, { "code": null, "e": 1610, "s": 1574, "text": "x<-rnorm(100)\nboxplot(x,col=\"blue\")" }, { "code": null, "e": 1683, "s": 1610, "text": "If you execute the above given code, it generates the following output −" }, { "code": null, "e": 1759, "s": 1683, "text": "To change the color of box of boxplot in base R, use the code given below −" }, { "code": null, "e": 1794, "s": 1759, "text": "x<-rnorm(100)\nboxplot(x,col=\"red\")" }, { "code": null, "e": 1867, "s": 1794, "text": "If you execute the above given code, it generates the following output −" } ]
Tryit Editor v3.7
Tryit: HTML font-size
[]
Maximize sum after K negations | Practice | GeeksforGeeks
Given an array of integers of size N and a number K., Your must modify array arr[] exactly K number of times. Here modify array means in each operation you can replace any array element either arr[i] by -arr[i] or -arr[i] by arr[i]. You need to perform this operation in such a way that after K operations, the sum of the array must be maximum. Example 1: Input: N = 5, K = 1 arr[] = {1, 2, -3, 4, 5} Output: 15 Explanation: We have k=1 so we can change -3 to 3 and sum all the elements to produce 15 as output. Example 2: Input: N = 10, K = 5 arr[] = {5, -2, 5, -4, 5, -12, 5, 5, 5, 20} Output: 68 Explanation: Here we have k=5 so we turn -2, -4, -12 to 2, 4, and 12 respectively. Since we have performed 3 operations so k is now 2. To get maximum sum of array we can turn positive turned 2 into negative and then positive again so k is 0. Now sum is 5+5+4+5+12+5+5+5+20+2 = 68 Your Task: You don't have to print anything, print ting is done by the driver code itself. You have to complete the function maximizeSum() which takes the array A[], its size N, and an integer K as inputs and returns the maximum possible sum. Expected Time Complexity: O(N*logN) Expected Auxiliary Space: O(1) Constraints: 1 ≤ N,K ≤ 105 -109 ≤ Ai ≤ 109 0 harshvardhansingh4581 day ago A very simple java solution class Solution { public static long maximizeSum(long a[], int n, int k) { long res = 0; Arrays.sort(a); for(int i=0;i<n;i++){ if(k> 0 && a[i] < 0){ a[i] = -1 * a[i]; k--; } } Arrays.sort(a); for(int i=1;i<=k;i++) a[0] = -1 * a[0]; for(int i=0;i<n;i++) res += a[i]; return res; }} 0 nobugsanurag081 month ago Time Complexity: O(N*logN) Auxiliary Space: O(1) class Solution{ public: long long int maximizeSum(long long int a[], int n, int k) { long long int sum=0; sort(a,a+n); long long int cntneg=0; for(int i=0;i<n;i++){ if(a[i]>=0){ break; } else{ cntneg++; } } if(cntneg<=k){ long long int ntop=0; for(int i=0;i<n;i++){ if(ntop<cntneg){ a[i]=a[i]*-1; ntop++; k--; } else{ break; } } sort(a,a+n); if(k%2!=0){ a[0]=-1*a[0]; } } else{ long long int kp=0; for(int i=0;i<n;i++){ if(kp<k){ a[i]=a[i]*-1; kp++; } } } for(int i=0;i<n;i++){ sum+=a[i]; } return sum; }}; +2 sagrikasoni1 month ago Java Solution class Solution { public static long maximizeSum(long a[], int n, int k) { Arrays.sort(a); for(int i =0;i<n;i++){ if(a[i]<0 && k>0){ a[i] = -a[i]; k--; } } long sum =0,min =Integer.MAX_VALUE; for(int i =0;i<n;i++){ sum+=a[i]; min = Math.min(min,a[i]); } if(k%2!=0) sum = sum-2*min; return sum; } } 0 ashutoshrastogi2 months ago Easy Java Soln class Solution { public static long maximizeSum(long a[], int n, int k) { Arrays.sort(a); int i; long sum = 0; for(i=0;i<n;i++){ if(a[i]<0 && k>0){ k--; a[i] = Math.abs(a[i]); } sum += a[i]; } Arrays.sort(a); if(k==0) return sum; if(a[0]<0){ sum-=a[0]; if(k%2!=0) sum += Math.abs(a[0]); else sum += a[0]; } else if(a[0]==0){ return sum; } else{ sum-=a[0]; if(k%2!=0) sum -= a[0]; else sum += a[0]; } return sum; } } 0 waky2 months ago //Simple Approach long long int maximizeSum(long long int a[], int n, int k) { // Your code goes here sort(a,a+n); long long int mn = INT_MAX; long long int sum = 0; for(int i=0;i<n;i++){ mn = min(mn,abs(a[i])); if(a[i]<0&&k){ sum += -a[i]; k--; } else sum += a[i]; } if(k&1){ return sum -= 2*mn; } return sum; } 0 ashisbehera3 months ago simple java solution using greedy approach public static long maximizeSum(long a[], int n, int k) { // Your code goes here Arrays.sort(a); int neg = 0; for(int i=0;i<n;i++){//1st count how many -ve nos if(a[i] < 0) neg++; } int count =0; if(neg>0) { for (int i = 0; i < k && i < neg; i++) { // then make //them +ve a[i] = a[i] * (-1); count++; } } if(count<k){//if still we have not reached kth iteration //then make +ve to -ve k = k-count; Arrays.sort(a); int i=0; while(i<k){ a[i] = a[i]*(-1); k--; } } int sum = 0; for(int j=0;j<n;j++){//finaly find sum sum+=a[j]; } return sum; } 0 ghoshghoshbishal3 months ago public static long maximizeSum(long a[], int n, int k) { Queue<Long> q = new PriorityQueue<>((i, j) -> (int)(i - j)); for(int i = 0; i < n; i++){ q.add(a[i]); } for(int i = 0; i < k; i++){ long temp = q.poll(); temp *= -1; q.add(temp); } return q.stream().reduce((i, j) -> i + j).get(); } +1 chessnoobdj4 months ago C++ long long int maximizeSum(long long int a[], int n, int k) { int i = 0; sort(a, a+n); while(i<n && a[i] < 0 && k){ a[i] *= -1; i += 1; k -= 1; } if(i<n && a[i] != 0 && k%2 != 0) a[i] *= -1; if(i == n && k%2 != 0) a[n-1] *= -1; return accumulate(a, a+n, 0); } -1 manishmanimoney4 months ago SIMPLE PYTHON CODE class Solution: def maximizeSum(self, a, n, k): a=sorted(a) i=0 count=0 while i<k and i<n: if a[i]<0: count+=1 a[i]*=-1 i+=1 else: break if (k-count)%2==0: return(sum(a)) else: a=sorted(a) a[0]*=-1 return(sum(a)) +1 noob14prosometime4 months ago Simple C++ Solution- long long int maximizeSum(long long int a[], int n, int k) { // Your code goes here sort(a,a+n); int i=0; while(i<n){ if(k>0){ if(a[i]<0){ a[i]=-a[i]; k--; } } i++; } sort(a,a+n); while(k>0){ a[0]=-a[0]; k--; } long long int sum=0; for(int x=0;x<n;x++){ sum+=a[x]; } return sum; } We strongly recommend solving this problem on your own before viewing its editorial. Do you still want to view the editorial? Login to access your submissions. Problem Contest Reset the IDE using the second button on the top right corner. Avoid using static/global variables in your code as your code is tested against multiple test cases and these tend to retain their previous values. Passing the Sample/Custom Test cases does not guarantee the correctness of code. On submission, your code is tested against multiple test cases consisting of all possible corner cases and stress constraints. You can access the hints to get an idea about what is expected of you as well as the final solution code. You can view the solutions submitted by other users from the submission tab.
[ { "code": null, "e": 583, "s": 238, "text": "Given an array of integers of size N and a number K., Your must modify array arr[] exactly K number of times. Here modify array means in each operation you can replace any array element either arr[i] by -arr[i] or -arr[i] by arr[i]. You need to perform this operation in such a way that after K operations, the sum of the array must be maximum." }, { "code": null, "e": 595, "s": 583, "text": "\nExample 1:" }, { "code": null, "e": 751, "s": 595, "text": "Input:\nN = 5, K = 1\narr[] = {1, 2, -3, 4, 5}\nOutput:\n15\nExplanation:\nWe have k=1 so we can change -3 to 3 and\nsum all the elements to produce 15 as output." }, { "code": null, "e": 762, "s": 751, "text": "Example 2:" }, { "code": null, "e": 1119, "s": 762, "text": "Input:\nN = 10, K = 5\narr[] = {5, -2, 5, -4, 5, -12, 5, 5, 5, 20}\nOutput:\n68\nExplanation:\nHere we have k=5 so we turn -2, -4, -12 to\n2, 4, and 12 respectively. Since we have\nperformed 3 operations so k is now 2. To get\nmaximum sum of array we can turn positive\nturned 2 into negative and then positive\nagain so k is 0. Now sum is\n5+5+4+5+12+5+5+5+20+2 = 68" }, { "code": null, "e": 1363, "s": 1119, "text": "\nYour Task:\nYou don't have to print anything, print ting is done by the driver code itself. You have to complete the function maximizeSum() which takes the array A[], its size N, and an integer K as inputs and returns the maximum possible sum." }, { "code": null, "e": 1431, "s": 1363, "text": "\nExpected Time Complexity: O(N*logN)\nExpected Auxiliary Space: O(1)" }, { "code": null, "e": 1475, "s": 1431, "text": "\nConstraints:\n1 ≤ N,K ≤ 105\n-109 ≤ Ai ≤ 109" }, { "code": null, "e": 1477, "s": 1475, "text": "0" }, { "code": null, "e": 1507, "s": 1477, "text": "harshvardhansingh4581 day ago" }, { "code": null, "e": 1535, "s": 1507, "text": "A very simple java solution" }, { "code": null, "e": 1552, "s": 1535, "text": "class Solution {" }, { "code": null, "e": 1938, "s": 1552, "text": " public static long maximizeSum(long a[], int n, int k) { long res = 0; Arrays.sort(a); for(int i=0;i<n;i++){ if(k> 0 && a[i] < 0){ a[i] = -1 * a[i]; k--; } } Arrays.sort(a); for(int i=1;i<=k;i++) a[0] = -1 * a[0]; for(int i=0;i<n;i++) res += a[i]; return res; }}" }, { "code": null, "e": 1940, "s": 1938, "text": "0" }, { "code": null, "e": 1966, "s": 1940, "text": "nobugsanurag081 month ago" }, { "code": null, "e": 2015, "s": 1966, "text": "Time Complexity: O(N*logN) Auxiliary Space: O(1)" }, { "code": null, "e": 2978, "s": 2017, "text": "class Solution{ public: long long int maximizeSum(long long int a[], int n, int k) { long long int sum=0; sort(a,a+n); long long int cntneg=0; for(int i=0;i<n;i++){ if(a[i]>=0){ break; } else{ cntneg++; } } if(cntneg<=k){ long long int ntop=0; for(int i=0;i<n;i++){ if(ntop<cntneg){ a[i]=a[i]*-1; ntop++; k--; } else{ break; } } sort(a,a+n); if(k%2!=0){ a[0]=-1*a[0]; } } else{ long long int kp=0; for(int i=0;i<n;i++){ if(kp<k){ a[i]=a[i]*-1; kp++; } } } for(int i=0;i<n;i++){ sum+=a[i]; } return sum; }};" }, { "code": null, "e": 2981, "s": 2978, "text": "+2" }, { "code": null, "e": 3004, "s": 2981, "text": "sagrikasoni1 month ago" }, { "code": null, "e": 3018, "s": 3004, "text": "Java Solution" }, { "code": null, "e": 3466, "s": 3018, "text": "\nclass Solution {\n\n public static long maximizeSum(long a[], int n, int k)\n {\n Arrays.sort(a);\n for(int i =0;i<n;i++){\n if(a[i]<0 && k>0){\n a[i] = -a[i];\n k--;\n }\n }\n long sum =0,min =Integer.MAX_VALUE;\n for(int i =0;i<n;i++){\n sum+=a[i];\n min = Math.min(min,a[i]);\n }\n \n if(k%2!=0) sum = sum-2*min;\n return sum;\n }\n}" }, { "code": null, "e": 3468, "s": 3466, "text": "0" }, { "code": null, "e": 3496, "s": 3468, "text": "ashutoshrastogi2 months ago" }, { "code": null, "e": 3511, "s": 3496, "text": "Easy Java Soln" }, { "code": null, "e": 4310, "s": 3513, "text": "class Solution {\n\n public static long maximizeSum(long a[], int n, int k)\n {\n Arrays.sort(a);\n int i;\n long sum = 0;\n for(i=0;i<n;i++){\n if(a[i]<0 && k>0){\n k--;\n a[i] = Math.abs(a[i]); \n }\n \n sum += a[i];\n }\n Arrays.sort(a);\n if(k==0)\n return sum;\n if(a[0]<0){\n sum-=a[0];\n if(k%2!=0)\n sum += Math.abs(a[0]);\n else\n sum += a[0];\n }\n else if(a[0]==0){\n return sum; \n }\n else{\n sum-=a[0];\n if(k%2!=0)\n sum -= a[0];\n else\n sum += a[0];\n }\n \n return sum;\n }\n}" }, { "code": null, "e": 4312, "s": 4310, "text": "0" }, { "code": null, "e": 4329, "s": 4312, "text": "waky2 months ago" }, { "code": null, "e": 4826, "s": 4329, "text": "//Simple Approach\nlong long int maximizeSum(long long int a[], int n, int k)\n {\n // Your code goes here\n sort(a,a+n);\n long long int mn = INT_MAX;\n long long int sum = 0;\n for(int i=0;i<n;i++){\n mn = min(mn,abs(a[i]));\n if(a[i]<0&&k){\n sum += -a[i];\n k--;\n }\n else\n sum += a[i];\n }\n if(k&1){\n return sum -= 2*mn;\n }\n return sum;\n }" }, { "code": null, "e": 4828, "s": 4826, "text": "0" }, { "code": null, "e": 4852, "s": 4828, "text": "ashisbehera3 months ago" }, { "code": null, "e": 4895, "s": 4852, "text": "simple java solution using greedy approach" }, { "code": null, "e": 5751, "s": 4895, "text": " public static long maximizeSum(long a[], int n, int k)\n {\n // Your code goes here\n Arrays.sort(a);\n int neg = 0;\n for(int i=0;i<n;i++){//1st count how many -ve nos\n if(a[i] < 0)\n neg++;\n }\n int count =0;\n if(neg>0) {\n for (int i = 0; i < k && i < neg; i++) { // then make //them +ve\n a[i] = a[i] * (-1);\n count++;\n }\n }\n if(count<k){//if still we have not reached kth iteration //then make +ve to -ve\n k = k-count;\n Arrays.sort(a);\n int i=0;\n while(i<k){\n a[i] = a[i]*(-1);\n k--;\n }\n }\n int sum = 0;\n for(int j=0;j<n;j++){//finaly find sum\n sum+=a[j];\n }\n return sum;\n }" }, { "code": null, "e": 5753, "s": 5751, "text": "0" }, { "code": null, "e": 5782, "s": 5753, "text": "ghoshghoshbishal3 months ago" }, { "code": null, "e": 6158, "s": 5782, "text": "public static long maximizeSum(long a[], int n, int k) { Queue<Long> q = new PriorityQueue<>((i, j) -> (int)(i - j)); for(int i = 0; i < n; i++){ q.add(a[i]); } for(int i = 0; i < k; i++){ long temp = q.poll(); temp *= -1; q.add(temp); } return q.stream().reduce((i, j) -> i + j).get(); }" }, { "code": null, "e": 6161, "s": 6158, "text": "+1" }, { "code": null, "e": 6185, "s": 6161, "text": "chessnoobdj4 months ago" }, { "code": null, "e": 6189, "s": 6185, "text": "C++" }, { "code": null, "e": 6572, "s": 6189, "text": "long long int maximizeSum(long long int a[], int n, int k)\n {\n int i = 0;\n sort(a, a+n);\n while(i<n && a[i] < 0 && k){\n a[i] *= -1;\n i += 1;\n k -= 1;\n }\n if(i<n && a[i] != 0 && k%2 != 0)\n a[i] *= -1;\n if(i == n && k%2 != 0)\n a[n-1] *= -1;\n return accumulate(a, a+n, 0);\n }" }, { "code": null, "e": 6575, "s": 6572, "text": "-1" }, { "code": null, "e": 6603, "s": 6575, "text": "manishmanimoney4 months ago" }, { "code": null, "e": 6622, "s": 6603, "text": "SIMPLE PYTHON CODE" }, { "code": null, "e": 6989, "s": 6622, "text": "class Solution: def maximizeSum(self, a, n, k): a=sorted(a) i=0 count=0 while i<k and i<n: if a[i]<0: count+=1 a[i]*=-1 i+=1 else: break if (k-count)%2==0: return(sum(a)) else: a=sorted(a) a[0]*=-1 return(sum(a))" }, { "code": null, "e": 6992, "s": 6989, "text": "+1" }, { "code": null, "e": 7022, "s": 6992, "text": "noob14prosometime4 months ago" }, { "code": null, "e": 7043, "s": 7022, "text": "Simple C++ Solution-" }, { "code": null, "e": 7599, "s": 7043, "text": "long long int maximizeSum(long long int a[], int n, int k)\n {\n // Your code goes here\n sort(a,a+n);\n int i=0;\n while(i<n){\n if(k>0){\n if(a[i]<0){\n a[i]=-a[i];\n k--;\n }\n }\n i++;\n \n }\n \n sort(a,a+n);\n \n while(k>0){\n a[0]=-a[0];\n k--;\n }\n long long int sum=0;\n for(int x=0;x<n;x++){\n sum+=a[x];\n }\n return sum;\n }" }, { "code": null, "e": 7745, "s": 7599, "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": 7781, "s": 7745, "text": " Login to access your submissions. " }, { "code": null, "e": 7791, "s": 7781, "text": "\nProblem\n" }, { "code": null, "e": 7801, "s": 7791, "text": "\nContest\n" }, { "code": null, "e": 7864, "s": 7801, "text": "Reset the IDE using the second button on the top right corner." }, { "code": null, "e": 8012, "s": 7864, "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": 8220, "s": 8012, "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": 8326, "s": 8220, "text": "You can access the hints to get an idea about what is expected of you as well as the final solution code." } ]
Sum of all divisors from 1 to n
02 Nov, 2021 Given a positive integer n. Find the value of where function F(i) for number i be defined as the sum of all divisors of ‘i‘. Examples : Input: 4 Output: 15 Explanation F(1) = 1 F(2) = 1 + 2 = 3 F(3) = 1 + 3 = 4 F(4) = 1 + 2 + 4 = 7 ans = F(1) + F(2) + F(3) + F(4) = 1 + 3 + 4 + 7 = 15 Input: 5 Output: 21 Naive approach is to traverse for every number(1 to n), find all divisors and keep updating the sum with that divisor. See this to understand more. C++ Java Python3 C# PHP Javascript // C++ program to find sum of all// divisor of number up to 'n'#include<bits/stdc++.h>using namespace std; // Utility function to find sum of// all divisor of number up to 'n'int divisorSum(int n){ int sum = 0; for(int i = 1; i <= n; ++i) { // Find all divisors of i and add them for(int j = 1; j * j <= i; ++j) { if (i % j == 0) { if (i / j == j) sum += j; else sum += j + i / j; } } } return sum;} // Driver codeint main(){ int n = 4; cout << " " << divisorSum(n) << endl; n = 5; cout << " " << divisorSum(n); return 0;} // JAVA program to find sum of all// divisor of number up to 'n'import java.io.*; class GFG { // Utility function to find sum of // all divisor of number up to 'n' static int divisorSum(int n) { int sum = 0; for (int i = 1; i <= n; ++i) { // Find all divisors of i // and add them for (int j = 1; j * j <= i; ++j) { if (i % j == 0) { if (i / j == j) sum += j; else sum += j + i / j; } } } return sum; } // Driver code public static void main(String args[]) { int n = 4; System.out.println(divisorSum(n)); n = 5; System.out.println(divisorSum(n)); }} /*This code is contributed by Nikita tiwari.*/ # Python3 code to find sum of all# divisor of number up to 'n' # Utility function to find sum of# all divisor of number up to 'n'def divisorSum( n ): sum = 0 for i in range(1, n + 1): # Find all divisors of i # and add them j = 1 while j * j <= i: if i % j == 0: if i / j == j: sum += j else: sum += j + i / j j = j + 1 return int(sum) # Driver coden = 4print( divisorSum(n))n = 5print( divisorSum(n)) # This code is contributed by "Sharad_Bhardwaj". // C# program to find sum of all// divisor of number up to 'n'using System; class GFG { // Utility function to find sum of // all divisor of number up to 'n' static int divisorSum(int n) { int sum = 0; for (int i = 1; i <= n; ++i) { // Find all divisors of i // and add them for (int j = 1; j * j <= i; ++j) { if (i % j == 0) { if (i / j == j) sum += j; else sum += j + i / j; } } } return sum; } // Driver code public static void Main() { int n = 4; Console.WriteLine(divisorSum(n)); n = 5; Console.WriteLine(divisorSum(n)); }} /*This code is contributed by vt_m.*/ <?php// PHP program to find sum of all// divisor of number up to 'n' // Utility function to find sum of// all divisor of number up to 'n' function divisorSum($n){ $sum = 0; for ($i = 1; $i <= $n; ++$i) { // Find all divisors of i // and add them for ($j = 1; $j * $j <= $i; ++$j) { if ($i % $j == 0) { if ($i / $j == $j) $sum += $j; else $sum += $j + $i / $j; } } } return $sum;} // Driver code$n = 4;echo "\n", divisorSum($n), "\n";$n = 5;echo divisorSum($n), "\n"; // This code is contributed by aj_36?> <script>// Javascript program to find sum of all// divisor of number up to 'n' // Utility function to find sum of// all divisor of number up to 'n' function divisorSum(n){ let sum = 0; for (let i = 1; i <= n; ++i) { // Find all divisors of i // and add them for (let j = 1; j * j <= i; ++j) { if (i % j == 0) { if (i / j == j) sum += j; else sum += j + i / j; } } } return sum;} // Driver codelet n = 4;document.write(divisorSum(n) + "<br>");n = 5;document.write(divisorSum(n) + "<br>"); // This code is contributed by _saurabh_jaiswal</script> Output : 15 21 Time complexity: O(n√(n))) Auxiliary space: O(1) Efficient approach is to observe the function and co-relate the pattern. For a given number n, every number from 1 to n contributes its presence up to the highest multiple less than n. For instance, Let n = 6, => F(1) + F(2) + F(3) + F(4) + F(5) + F(6) => 1 will occurs 6 times in F(1), F(2), F(3), F(4), F(5) and F(6) => 2 will occurs 3 times in F(2), F(4) and F(6) => 3 will occur 2 times in F(3) and F(6) => 4 will occur 1 times in F(4) => 5 will occur 1 times in F(5) => 6 will occur 1 times in F(6) From the above observation, it can easily be observed that number i is occurring only in their multiples less than or equal to n. Thus, we just need to find the count of multiples and then multiply it with i for full contribution in the final sum. It can easily be done in O(1) time by taking the floor of (n / i) and then multiply it with i for the sum. C++ C Java Python3 C# PHP Javascript // C++ program to find sum of all// divisor of number up to 'n'#include<bits/stdc++.h>using namespace std; // Utility function to find sum of// all divisor of number up to 'n'int divisorSum(int n){ int sum = 0; for (int i = 1; i <= n; ++i) sum += (n / i) * i; return sum;} // Driver codeint main(){ int n = 4; cout <<" "<< divisorSum(n)<<endl; n = 5; cout <<" "<< divisorSum(n)<< endl; return 0;} // This code is contributed by shivanisinghss2110 // C program to find sum of all// divisor of number up to 'n'#include <stdio.h> // Utility function to find sum of// all divisor of number up to 'n'int divisorSum(int n){ int sum = 0; for (int i = 1; i <= n; ++i) sum += (n / i) * i; return sum;} // Driver codeint main(){ int n = 4; printf("%d\n", divisorSum(n)); n = 5; printf("%d", divisorSum(n)); return 0;} // Java program to find sum of all// divisor of number up to 'n'import java.io.*; class GFG { // Utility function to find sum of // all divisor of number up to 'n' static int divisorSum(int n) { int sum = 0; for (int i = 1; i <= n; ++i) sum += (n / i) * i; return sum; } // Driver code public static void main(String args[]) { int n = 4; System.out.println(divisorSum(n)); n = 5; System.out.println(divisorSum(n)); }} /*This code is contributed by Nikita Tiwari.*/ # Python3 code to find sum of all# divisor of number up to 'n' # Utility function to find sum of# all divisor of number up to 'n'def divisorSum( n ): sum = 0 for i in range(1, n + 1): sum += int(n / i) * i return int(sum) # Driver coden = 4print( divisorSum(n))n = 5print( divisorSum(n)) # This code is contributed by "Sharad_Bhardwaj". // C# program to find sum of all// divisor of number up to 'n'using System; class GFG { // Utility function to find sum of // all divisor of number up to 'n' static int divisorSum(int n) { int sum = 0; for (int i = 1; i <= n; ++i) sum += (n / i) * i; return sum; } // Driver code public static void Main() { int n = 4; Console.WriteLine(divisorSum(n)); n = 5; Console.WriteLine(divisorSum(n)); }} /*This code is contributed by vt_m.*/ <?php// PHP program to find sum of all// divisor of number up to 'n' // Utility function to find sum of// all divisor of number up to 'n'function divisorSum( $n){ $sum = 0; for ( $i = 1; $i <= $n; ++$i) $sum += floor($n / $i) * $i; return $sum;} // Driver code$n = 4;echo divisorSum($n),"\n";$n = 5;echo divisorSum($n),"\n"; // This code is contributed by anuj_67.?> // Javascript program to find sum of all// divisor of number up to 'n' // Utility function to find sum of// all divisor of number up to 'n'function divisorSum(n){ let sum = 0; for (let i = 1; i <= n; ++i) sum += Math.floor(n / i) * i; return sum;} // Driver codelet n = 4;document.write(divisorSum(n) + "<br>");n = 5;document.write(divisorSum(n) + "<br>"); // This code is contributed by _saurabh_jaiswal. Output : 15 21 Time complexity: O(n) Auxiliary space: O(1) More efficient solution: We need to calculate To evaluate the above expression in O(sqrt(N)) we make use of The Harmonic Lemma. Consider the harmonic sequence on integer division: {N/1, N/2, N/3, ..... ,N/N} The lemma states that the above sequence is non-increasing, and there are at most 2*sqrt(N) different elements. Consider floor(N/i) = k. Thus, k <= N/i < k+1. From this we get largest = floor(N/k). Therefore, we can find a range of values of i for which floor(N/i) is constant. And using The Harmonic Lemma we know that will be at most 2*sqrt(N) terms, thus we can calculate it programmatically in O(sqrt(N)) complexity. Consider the following example for better clarification. C++ Java Python3 C# Javascript // C++ program to calculate sum of divisors// of numbers from 1 to N in O(sqrt(N)) complexity#include <iostream>using namespace std; #define ll long long#define mod 1000000007 /*Function to calculate x^y usingModular exponentiationRefer to https://www.geeksforgeeks.org/modular-exponentiation-power-in-modular-arithmetic/*/ll power(ll x, ll y, ll p){ // re x^y if p not specified // else (x^y)%p ll res = 1; x = x % p; while (y > 0) { if (y & 1) res = (res * x) % p; y = y >> 1; x = (x * x) % p; } return (res + p) % p;} // Function to find modular// inverse of a under modulo m// Assumption: m is primell modinv(ll x){ return power(x, mod - 2, mod);} // Function to calculate sum from 1 to nll sum(ll n){ // sum 1 to n = (n*(n+1))/2 ll retval = ((((n % mod) * ((n + 1) % mod)) % mod) * modinv(2)) % mod; return retval;} ll divisorSum(ll n){ ll l = 1; ll ans = 0; while (l <= n) { ll k = n / l; ll r = n / k; k %= mod; // For i=l to i=r, floor(n/i) will be k ans += ((sum(r) - sum(l - 1) % mod) * k) % mod; // Since values can be very large // we need to take mod at every step ans %= mod; l = r + 1; } ans = ans % mod; // ans can be negative // for example n = 831367 ans would be -534577982 if (ans < 0){ return ans+mod; }else{ return ans; }} /* Driver program to test above function */int main(){ int n = 5; cout << "The sum of divisors of all \ numbers from 1 to " << n << " is: " \ << divisorSum(n) << '\n'; n = 14; cout << "The sum of divisors of all \ numbers from 1 to " << n << " is: " \ << divisorSum(n) << '\n';} // Java program to calculate// sum of divisors of numbers// from 1 to N in O(sqrt(N))// complexityimport java.util.*;class Main{ static int mod = 1000000007; /*Function to calculate x^y using Modular exponentiationRefer to https://www.geeksforgeeks.org/modular-exponentiation-power-in-modular-arithmetic/*/public static long power(long x, long y, long p){ // re x^y if p not specified // else (x^y)%p long res = 1; x = x % p; while (y > 0) { if ((y & 1) != 0) res = (res * x) % p; y = y >> 1; x = (x * x) % p; } return (res + p) % p;} // Function to find modular // inverse of a under modulo m// Assumption: m is primepublic static long modinv(long x){ return power(x, mod - 2, mod);} // Function to calculate sum// from 1 to npublic static long sum(long n){ // sum 1 to n = (n*(n+1))/2 long retval = ((((n % mod) * ((n + 1) % mod)) % mod) * modinv(2)) % mod; return retval;} public static long divisorSum(long n){ long l = 1; long ans = 0; while (l <= n) { long k = n / l; long r = n / k; k %= mod; // For i=l to i=r, // floor(n/i) will be k ans += ((sum(r) - sum(l - 1) % mod) * k) % mod; // Since values can be very // large we need to take mod // at every step ans %= mod; l = r + 1; } ans = ans % mod; return ans;} // Driver code public static void main(String[] args){ int n = 5; System.out.println("The sum of divisors of" + " all numbers from 1 to " + n + " is: " + divisorSum(n)); n = 14; System.out.println("The sum of divisors of all" + " numbers from 1 to " + n + " is: " + divisorSum(n));}} // This code is contributed by divyeshrabadiya07 # Python program to calculate# sum of divisors of numbers# from 1 to N in O(sqrt(N))# complexitymod = 1000000007; # Function to calculate x^y using Modular exponentiation Refer to# https:#www.geeksforgeeks.org/ modular-exponentiation-power-in-# modular-arithmetic/def power(x, y, p): # re x^y if p not specified # else (x^y)%p res = 1; x = x % p; while (y > 0): if ((y & 1) != 0): res = (res * x) % p; y = y >> 1; x = (x * x) % p; return (res + p) % p; # Function to find modular# inverse of a under modulo m# Assumption: m is primedef modinv(x): return power(x, mod - 2, mod); # Function to calculate sum# from 1 to ndef sum(n): # sum 1 to n = (n*(n+1))/2 retval = ((((n % mod) * ((n + 1) % mod)) % mod) * modinv(2)) % mod; return retval; def divisorSum(n): l = 1; ans = 0; while (l <= n): k = n // l; r = n // k; k %= mod; # For i=l to i=r, # floor(n/i) will be k ans += ((sum(r) - sum(l - 1) % mod) * k) % mod; # Since values can be very # large we need to take mod # at every step ans %= mod; l = r + 1; ans = ans % mod; return ans; # Driver codeif __name__ == '__main__': n = 5; print("The sum of divisors of all numbers from 1 to " , n , " is: " ,int( divisorSum(n))); n = 14; print("The sum of divisors of all numbers from 1 to ", n ," is: " , int(divisorSum(n))); # This code contributed by aashish1995 Write // C# program to calculate// sum of divisors of numbers// from 1 to N in O(sqrt(N))// complexityusing System; class GFG{ static int mod = 1000000007; /*Function to calculate x^y using Modular exponentiationRefer to https://www.geeksforgeeks.org/modular-exponentiation-power-in-modular-arithmetic/*/static long power(long x, long y, long p){ // re x^y if p not specified // else (x^y)%p long res = 1; x = x % p; while (y > 0) { if ((y & 1) != 0) res = (res * x) % p; y = y >> 1; x = (x * x) % p; } return (res + p) % p;} // Function to find modular // inverse of a under modulo m// Assumption: m is primestatic long modinv(long x){ return power(x, mod - 2, mod);} // Function to calculate sum// from 1 to nstatic long sum(long n){ // sum 1 to n = (n*(n+1))/2 long retval = ((((n % mod) * ((n + 1) % mod)) % mod) * modinv(2)) % mod; return retval;} static long divisorSum(long n){ long l = 1; long ans = 0; while (l <= n) { long k = n / l; long r = n / k; k %= mod; // For i=l to i=r, // floor(n/i) will be k ans += ((sum(r) - sum(l - 1) % mod) * k) % mod; // Since values can be very // large we need to take mod // at every step ans %= mod; l = r + 1; } ans = ans % mod; return ans;} // Driver codestatic void Main(){ int n = 5; Console.WriteLine("The sum of divisors of" + " all numbers from 1 to " + n + " is: " + divisorSum(n)); n = 14; Console.WriteLine("The sum of divisors of all" + " numbers from 1 to " + n + " is: " + divisorSum(n));}} // This code is contributed by divyesh072019 <script> // Javascript program to calculate// sum of divisors of numbers// from 1 to N in O(sqrt(N))// complexity var mod = 10007; /*Function to calculate x^y using Modular exponentiationRefer to https://www.geeksforgeeks.org/modular-exponentiation-power-in-modular-arithmetic/*/function power(x, y, p){ // re x^y if p not specified // else (x^y)%p var res = 1; x = x % p; while (y > 0) { if ((y & 1) != 0) res = (res * x) % p; y = y >> 1; x = (x * x) % p; } return (res + p) % p;} // Function to find modular // inverse of a under modulo m// Assumption: m is primefunction modinv(x){ return power(x, mod - 2, mod);} // Function to calculate sum// from 1 to nfunction sum(n){ // sum 1 to n = (n*(n+1))/2 var retval = Math.floor((((n % mod) * ((n + 1) % mod)) % mod) * modinv(2)) % mod; return retval;} function divisorSum(n){ var l = 1; var ans = 0; while (l <= n) { var k = n / l; var r = n / k; k %= mod; // For i=l to i=r, // floor(n/i) will be k ans += Math.floor((sum(r) - sum(l - 1) % mod) * k) % mod; // Since values can be very // large we need to take mod // at every step ans %= mod; l = r + 1; } ans = ans % mod; return ans;} // Driver code var n = 5; document.write("The sum of divisors of" + " all numbers from 1 to " + n + " is: " + divisorSum(n) +"<br>"); n = 14; document.write("The sum of divisors of all" + " numbers from 1 to " + n + " is: " + divisorSum(n)); // This code is contributed by shivanisinghss2110</script> Output: The sum of divisors of all numbers from 1 to 5 is: 21 The sum of divisors of all numbers from 1 to 14 is: 165 Time complexity: O(sqrt(N)) Auxiliary space: O(1) Another sqrt(n) approach: Anywhere division is used in the below article, it means integer division. Let’s start with an example assume that n = 20, now let’s see how each number from 1 to 20 appears as the factor of some other number. 1 : 1 * 1, 1 * 2, 1 * 3, 1 * 4..., 1 * (20 / 1) 2 : 2 * 1, 2 * 2, 2 * 3, 2 * 4,..., 2 * (20 / 2) 3 : 3 * 1, 3 * 2, 3 * 3, 3 * 4...., 3 * (20 / 3) our goal is to add every number each time it appears as the factor of some other number. For example 3 appears as the factor of (3 * 1), (3 * 2), (3 * 3)..., (3 * (20 / 3)). Now let’s start from 1 and add 1 to our sum each time it appears and also we will add all the numbers that appeared with 1, we’ll do the same thing with 2 and when we reach 3 we have already added 3 to our sum when it appeared with 1 and 2 so now we will only add 3 when it appears with numbers greater than 2 i.e. 3, 4, 5, 6 also we will add the numbers that appeared with 3 so we’ll add 4, 5 and 6 as well (notice here we will not add 3 twice because of 3 * 3). Similarly when we reach 4 we have already added 4 when it appeared with 1, 2 and 3 so we’ll add it only when it appears with numbers >= itself and add the numbers that appear with 4. Finally we can say that when we are at a number i, we have already processed numbers from1 to i – 1 and hence we have added i every time it appears with numbers 1 to i – 1 so this time we only need to add i every time it appears with numbers >= i also we have to add all the numbers that appear together with i and they are > i. Therefore for every number i we want to add the following terms to our sum t1 : (add i each time it appears with numbers >= itself) -> i * (num / i - (i - 1)) (recall i will appear with numbers 1 to num / i and we have already added i each time it appeared with a numbers less than itself) t2 : (add numbers that appear with i) -> (i + 1) + (i + 2) ... + (num / i) (numbers 1 to num / i will appear with i but we have already processed numbers 1 to i - 1 and added them when they appeared with i so now we only have to add the numbers that appear with i and are greater than i, here we will not add i itself because when i appears with itself it should be added only once and we have added it once in t1) we need to calculate t2 in O(1) time, here's how to do that t2 = (i + 1) + (i + 2) + (i + 3) + ... + (num / i) add and subtract 1 + 2 + 3 ... + i => t2 = 1 + 2 + 3 + ... + i + (i + 1) + (i + 2) + ... + (num / i) - (1 + 2 + 3 + ... + i) => t2 = (1 + 2 + 3 + .. + (num / i)) - (1 + 2 + 3 .. + i) => t2 = ((num / i) * (num / i + 1)) / 2 - (i * (i + 1)) / 2 Finally, let’s look at the numbers that are greater than sqrt(num). These numbers will only appear with numbers that are lesser than sqrt(num). Let’s say x is a number greater than sqrt(num) we have, x > sqrt(num) multiply sqrt(num) on both sides => x * sqrt(num) > sqrt(num) * sqrt(num) => x * sqrt(num) > num we want to add x each time it appears, from above proof we see that x multiplied by root of num itself is greater than num hence x will only appear with numbers less than root of num so if we process all the numbers from 1 to sqrt(num) we will add every time x appears. For example take n = 100 now consider 11, 11 * 10 > 100 so 11 appears only with 1 to 9 i.e. as a factor of 11, 22, 33,..., 99 same is true for rest of the numbers that are greater than 10 they will only appear with numbers lesser than 10 and hence we only need to process numbers from 1 to 10 to add the numbers greater than 10 for n = 100. Finally, our solution is this for each i in 1 to sqrt(num) //no need to visit numbers greater than the root add t1 and t2 to the sum below is the c++ code C++ Java Python3 C# Javascript #include <bits/stdc++.h>using namespace std;long long sum_all_divisors(long long num){ long long sum = 0; for (long long i = 1; i <= sqrt(num); i++) { long long t1 = i * (num / i - i + 1); // adding i every time it appears with numbers greater than or equal to itself long long t2 = (((num / i) * (num / i + 1)) / 2) - ((i * (i + 1)) / 2); // adding numbers that appear with i and are greater than i sum += t1 + t2; } return sum;}int main(){ int n; long long sum = sum_all_divisors(n); cout << sum << '\n'; return 0;} import java.io.*; class GFG { public static int sum_all_divisors(int num){ int sum = 0; for (int i = 1; i <= Math.sqrt(num); i++) { int t1 = i * (num / i - i + 1); // adding i every time it appears with numbers greater than or equal to itself int t2 = (((num / i) * (num / i + 1)) / 2) - ((i * (i + 1)) / 2); // adding numbers that appear with i and are greater than i sum += t1 + t2; } return sum;} // Driver code public static void main (String[] args){ int n = 1; int sum = sum_all_divisors(n); System.out.println(sum);}} // This code is contributed by shivanisinghss2110 import mathdef sum_all_divisors(num): sum = 0; for i in range(1,math.floor(math.sqrt(num))+1): t1 = i * (num / i - i + 1) # adding i every time it appears with numbers greater than or equal to itself t2 = (((num / i) * (num / i + 1)) / 2) - ((i * (i + 1)) / 2) # adding numbers that appear with i and are greater than i sum += t1 + t2; return sum; n = 1sum = sum_all_divisors(n)print(sum) # This code is contributed by shivanisinghss2110 using System; class GFG { public static int sum_all_divisors(int num){ int sum = 0; for (int i = 1; i <= Math.Sqrt(num); i++) { int t1 = i * (num / i - i + 1); // adding i every time it appears with numbers greater than or equal to itself int t2 = (((num / i) * (num / i + 1)) / 2) - ((i * (i + 1)) / 2); // adding numbers that appear with i and are greater than i sum += t1 + t2; } return sum;} // Driver code public static void Main (String[] args){ int n = 1; int sum = sum_all_divisors(n); Console.Write(sum);}} // This code is contributed by shivanisinghss2110 <script>function sum_all_divisors(num){ var sum = 0; for (var i = 1; i <= Math.sqrt(num); i++) { var t1 = i * (num / i - i + 1); // adding i every time it appears with numbers greater than or equal to itself var t2 = (((num / i) * (num / i + 1)) / 2) - ((i * (i + 1)) / 2); // adding numbers that appear with i and are greater than i sum += t1 + t2; } return sum;} var n; var sum = sum_all_divisors(n); document.write( sum ); // This code is contributed by shivanisinghss2110</script> Time complexity: O(sqrt(N)) Auxiliary space: O(1) jit_t vt_m shreyanshjain1 divyeshrabadiya07 divyesh072019 aashish1995 shivanisinghss2110 _saurabh_jaiswal abughalib raikaushik2000 ruhelaa48 surindertarika1234 divisors number-theory Mathematical number-theory Mathematical Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. 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 Coin Change | DP-7 Operators in C / C++ Prime Numbers Program to find GCD or HCF of two numbers Find minimum number of coins that make a given value
[ { "code": null, "e": 54, "s": 26, "text": "\n02 Nov, 2021" }, { "code": null, "e": 101, "s": 54, "text": "Given a positive integer n. Find the value of " }, { "code": null, "e": 183, "s": 103, "text": "where function F(i) for number i be defined as the sum of all divisors of ‘i‘. " }, { "code": null, "e": 195, "s": 183, "text": "Examples : " }, { "code": null, "e": 372, "s": 195, "text": "Input: 4\nOutput: 15\nExplanation\nF(1) = 1\nF(2) = 1 + 2 = 3\nF(3) = 1 + 3 = 4\nF(4) = 1 + 2 + 4 = 7\nans = F(1) + F(2) + F(3) + F(4)\n = 1 + 3 + 4 + 7\n = 15\nInput: 5\nOutput: 21" }, { "code": null, "e": 522, "s": 372, "text": " Naive approach is to traverse for every number(1 to n), find all divisors and keep updating the sum with that divisor. See this to understand more. " }, { "code": null, "e": 526, "s": 522, "text": "C++" }, { "code": null, "e": 531, "s": 526, "text": "Java" }, { "code": null, "e": 539, "s": 531, "text": "Python3" }, { "code": null, "e": 542, "s": 539, "text": "C#" }, { "code": null, "e": 546, "s": 542, "text": "PHP" }, { "code": null, "e": 557, "s": 546, "text": "Javascript" }, { "code": "// C++ program to find sum of all// divisor of number up to 'n'#include<bits/stdc++.h>using namespace std; // Utility function to find sum of// all divisor of number up to 'n'int divisorSum(int n){ int sum = 0; for(int i = 1; i <= n; ++i) { // Find all divisors of i and add them for(int j = 1; j * j <= i; ++j) { if (i % j == 0) { if (i / j == j) sum += j; else sum += j + i / j; } } } return sum;} // Driver codeint main(){ int n = 4; cout << \" \" << divisorSum(n) << endl; n = 5; cout << \" \" << divisorSum(n); return 0;}", "e": 1259, "s": 557, "text": null }, { "code": "// JAVA program to find sum of all// divisor of number up to 'n'import java.io.*; class GFG { // Utility function to find sum of // all divisor of number up to 'n' static int divisorSum(int n) { int sum = 0; for (int i = 1; i <= n; ++i) { // Find all divisors of i // and add them for (int j = 1; j * j <= i; ++j) { if (i % j == 0) { if (i / j == j) sum += j; else sum += j + i / j; } } } return sum; } // Driver code public static void main(String args[]) { int n = 4; System.out.println(divisorSum(n)); n = 5; System.out.println(divisorSum(n)); }} /*This code is contributed by Nikita tiwari.*/", "e": 2101, "s": 1259, "text": null }, { "code": "# Python3 code to find sum of all# divisor of number up to 'n' # Utility function to find sum of# all divisor of number up to 'n'def divisorSum( n ): sum = 0 for i in range(1, n + 1): # Find all divisors of i # and add them j = 1 while j * j <= i: if i % j == 0: if i / j == j: sum += j else: sum += j + i / j j = j + 1 return int(sum) # Driver coden = 4print( divisorSum(n))n = 5print( divisorSum(n)) # This code is contributed by \"Sharad_Bhardwaj\".", "e": 2693, "s": 2101, "text": null }, { "code": "// C# program to find sum of all// divisor of number up to 'n'using System; class GFG { // Utility function to find sum of // all divisor of number up to 'n' static int divisorSum(int n) { int sum = 0; for (int i = 1; i <= n; ++i) { // Find all divisors of i // and add them for (int j = 1; j * j <= i; ++j) { if (i % j == 0) { if (i / j == j) sum += j; else sum += j + i / j; } } } return sum; } // Driver code public static void Main() { int n = 4; Console.WriteLine(divisorSum(n)); n = 5; Console.WriteLine(divisorSum(n)); }} /*This code is contributed by vt_m.*/", "e": 3505, "s": 2693, "text": null }, { "code": "<?php// PHP program to find sum of all// divisor of number up to 'n' // Utility function to find sum of// all divisor of number up to 'n' function divisorSum($n){ $sum = 0; for ($i = 1; $i <= $n; ++$i) { // Find all divisors of i // and add them for ($j = 1; $j * $j <= $i; ++$j) { if ($i % $j == 0) { if ($i / $j == $j) $sum += $j; else $sum += $j + $i / $j; } } } return $sum;} // Driver code$n = 4;echo \"\\n\", divisorSum($n), \"\\n\";$n = 5;echo divisorSum($n), \"\\n\"; // This code is contributed by aj_36?>", "e": 4164, "s": 3505, "text": null }, { "code": "<script>// Javascript program to find sum of all// divisor of number up to 'n' // Utility function to find sum of// all divisor of number up to 'n' function divisorSum(n){ let sum = 0; for (let i = 1; i <= n; ++i) { // Find all divisors of i // and add them for (let j = 1; j * j <= i; ++j) { if (i % j == 0) { if (i / j == j) sum += j; else sum += j + i / j; } } } return sum;} // Driver codelet n = 4;document.write(divisorSum(n) + \"<br>\");n = 5;document.write(divisorSum(n) + \"<br>\"); // This code is contributed by _saurabh_jaiswal</script>", "e": 4862, "s": 4164, "text": null }, { "code": null, "e": 4871, "s": 4862, "text": "Output :" }, { "code": null, "e": 4877, "s": 4871, "text": "15\n21" }, { "code": null, "e": 4926, "s": 4877, "text": "Time complexity: O(n√(n))) Auxiliary space: O(1)" }, { "code": null, "e": 5126, "s": 4926, "text": "Efficient approach is to observe the function and co-relate the pattern. For a given number n, every number from 1 to n contributes its presence up to the highest multiple less than n. For instance, " }, { "code": null, "e": 5437, "s": 5126, "text": "Let n = 6,\n=> F(1) + F(2) + F(3) + F(4) + F(5) + F(6)\n=> 1 will occurs 6 times in F(1), F(2),\n F(3), F(4), F(5) and F(6)\n=> 2 will occurs 3 times in F(2), F(4) and\n F(6)\n=> 3 will occur 2 times in F(3) and F(6)\n=> 4 will occur 1 times in F(4)\n=> 5 will occur 1 times in F(5)\n=> 6 will occur 1 times in F(6)" }, { "code": null, "e": 5793, "s": 5437, "text": "From the above observation, it can easily be observed that number i is occurring only in their multiples less than or equal to n. Thus, we just need to find the count of multiples and then multiply it with i for full contribution in the final sum. It can easily be done in O(1) time by taking the floor of (n / i) and then multiply it with i for the sum. " }, { "code": null, "e": 5797, "s": 5793, "text": "C++" }, { "code": null, "e": 5799, "s": 5797, "text": "C" }, { "code": null, "e": 5804, "s": 5799, "text": "Java" }, { "code": null, "e": 5812, "s": 5804, "text": "Python3" }, { "code": null, "e": 5815, "s": 5812, "text": "C#" }, { "code": null, "e": 5819, "s": 5815, "text": "PHP" }, { "code": null, "e": 5830, "s": 5819, "text": "Javascript" }, { "code": "// C++ program to find sum of all// divisor of number up to 'n'#include<bits/stdc++.h>using namespace std; // Utility function to find sum of// all divisor of number up to 'n'int divisorSum(int n){ int sum = 0; for (int i = 1; i <= n; ++i) sum += (n / i) * i; return sum;} // Driver codeint main(){ int n = 4; cout <<\" \"<< divisorSum(n)<<endl; n = 5; cout <<\" \"<< divisorSum(n)<< endl; return 0;} // This code is contributed by shivanisinghss2110", "e": 6308, "s": 5830, "text": null }, { "code": "// C program to find sum of all// divisor of number up to 'n'#include <stdio.h> // Utility function to find sum of// all divisor of number up to 'n'int divisorSum(int n){ int sum = 0; for (int i = 1; i <= n; ++i) sum += (n / i) * i; return sum;} // Driver codeint main(){ int n = 4; printf(\"%d\\n\", divisorSum(n)); n = 5; printf(\"%d\", divisorSum(n)); return 0;}", "e": 6700, "s": 6308, "text": null }, { "code": "// Java program to find sum of all// divisor of number up to 'n'import java.io.*; class GFG { // Utility function to find sum of // all divisor of number up to 'n' static int divisorSum(int n) { int sum = 0; for (int i = 1; i <= n; ++i) sum += (n / i) * i; return sum; } // Driver code public static void main(String args[]) { int n = 4; System.out.println(divisorSum(n)); n = 5; System.out.println(divisorSum(n)); }} /*This code is contributed by Nikita Tiwari.*/", "e": 7254, "s": 6700, "text": null }, { "code": "# Python3 code to find sum of all# divisor of number up to 'n' # Utility function to find sum of# all divisor of number up to 'n'def divisorSum( n ): sum = 0 for i in range(1, n + 1): sum += int(n / i) * i return int(sum) # Driver coden = 4print( divisorSum(n))n = 5print( divisorSum(n)) # This code is contributed by \"Sharad_Bhardwaj\".", "e": 7611, "s": 7254, "text": null }, { "code": "// C# program to find sum of all// divisor of number up to 'n'using System; class GFG { // Utility function to find sum of // all divisor of number up to 'n' static int divisorSum(int n) { int sum = 0; for (int i = 1; i <= n; ++i) sum += (n / i) * i; return sum; } // Driver code public static void Main() { int n = 4; Console.WriteLine(divisorSum(n)); n = 5; Console.WriteLine(divisorSum(n)); }} /*This code is contributed by vt_m.*/", "e": 8135, "s": 7611, "text": null }, { "code": "<?php// PHP program to find sum of all// divisor of number up to 'n' // Utility function to find sum of// all divisor of number up to 'n'function divisorSum( $n){ $sum = 0; for ( $i = 1; $i <= $n; ++$i) $sum += floor($n / $i) * $i; return $sum;} // Driver code$n = 4;echo divisorSum($n),\"\\n\";$n = 5;echo divisorSum($n),\"\\n\"; // This code is contributed by anuj_67.?>", "e": 8518, "s": 8135, "text": null }, { "code": "// Javascript program to find sum of all// divisor of number up to 'n' // Utility function to find sum of// all divisor of number up to 'n'function divisorSum(n){ let sum = 0; for (let i = 1; i <= n; ++i) sum += Math.floor(n / i) * i; return sum;} // Driver codelet n = 4;document.write(divisorSum(n) + \"<br>\");n = 5;document.write(divisorSum(n) + \"<br>\"); // This code is contributed by _saurabh_jaiswal.", "e": 8940, "s": 8518, "text": null }, { "code": null, "e": 8949, "s": 8940, "text": "Output :" }, { "code": null, "e": 8955, "s": 8949, "text": "15\n21" }, { "code": null, "e": 8999, "s": 8955, "text": "Time complexity: O(n) Auxiliary space: O(1)" }, { "code": null, "e": 9024, "s": 8999, "text": "More efficient solution:" }, { "code": null, "e": 9046, "s": 9024, "text": "We need to calculate " }, { "code": null, "e": 9131, "s": 9048, "text": "To evaluate the above expression in O(sqrt(N)) we make use of The Harmonic Lemma. " }, { "code": null, "e": 9211, "s": 9131, "text": "Consider the harmonic sequence on integer division: {N/1, N/2, N/3, ..... ,N/N}" }, { "code": null, "e": 9323, "s": 9211, "text": "The lemma states that the above sequence is non-increasing, and there are at most 2*sqrt(N) different elements." }, { "code": null, "e": 9690, "s": 9323, "text": "Consider floor(N/i) = k. Thus, k <= N/i < k+1. From this we get largest = floor(N/k). Therefore, we can find a range of values of i for which floor(N/i) is constant. And using The Harmonic Lemma we know that will be at most 2*sqrt(N) terms, thus we can calculate it programmatically in O(sqrt(N)) complexity. Consider the following example for better clarification. " }, { "code": null, "e": 9694, "s": 9690, "text": "C++" }, { "code": null, "e": 9699, "s": 9694, "text": "Java" }, { "code": null, "e": 9707, "s": 9699, "text": "Python3" }, { "code": null, "e": 9710, "s": 9707, "text": "C#" }, { "code": null, "e": 9721, "s": 9710, "text": "Javascript" }, { "code": "// C++ program to calculate sum of divisors// of numbers from 1 to N in O(sqrt(N)) complexity#include <iostream>using namespace std; #define ll long long#define mod 1000000007 /*Function to calculate x^y usingModular exponentiationRefer to https://www.geeksforgeeks.org/modular-exponentiation-power-in-modular-arithmetic/*/ll power(ll x, ll y, ll p){ // re x^y if p not specified // else (x^y)%p ll res = 1; x = x % p; while (y > 0) { if (y & 1) res = (res * x) % p; y = y >> 1; x = (x * x) % p; } return (res + p) % p;} // Function to find modular// inverse of a under modulo m// Assumption: m is primell modinv(ll x){ return power(x, mod - 2, mod);} // Function to calculate sum from 1 to nll sum(ll n){ // sum 1 to n = (n*(n+1))/2 ll retval = ((((n % mod) * ((n + 1) % mod)) % mod) * modinv(2)) % mod; return retval;} ll divisorSum(ll n){ ll l = 1; ll ans = 0; while (l <= n) { ll k = n / l; ll r = n / k; k %= mod; // For i=l to i=r, floor(n/i) will be k ans += ((sum(r) - sum(l - 1) % mod) * k) % mod; // Since values can be very large // we need to take mod at every step ans %= mod; l = r + 1; } ans = ans % mod; // ans can be negative // for example n = 831367 ans would be -534577982 if (ans < 0){ return ans+mod; }else{ return ans; }} /* Driver program to test above function */int main(){ int n = 5; cout << \"The sum of divisors of all \\ numbers from 1 to \" << n << \" is: \" \\ << divisorSum(n) << '\\n'; n = 14; cout << \"The sum of divisors of all \\ numbers from 1 to \" << n << \" is: \" \\ << divisorSum(n) << '\\n';}", "e": 11578, "s": 9721, "text": null }, { "code": "// Java program to calculate// sum of divisors of numbers// from 1 to N in O(sqrt(N))// complexityimport java.util.*;class Main{ static int mod = 1000000007; /*Function to calculate x^y using Modular exponentiationRefer to https://www.geeksforgeeks.org/modular-exponentiation-power-in-modular-arithmetic/*/public static long power(long x, long y, long p){ // re x^y if p not specified // else (x^y)%p long res = 1; x = x % p; while (y > 0) { if ((y & 1) != 0) res = (res * x) % p; y = y >> 1; x = (x * x) % p; } return (res + p) % p;} // Function to find modular // inverse of a under modulo m// Assumption: m is primepublic static long modinv(long x){ return power(x, mod - 2, mod);} // Function to calculate sum// from 1 to npublic static long sum(long n){ // sum 1 to n = (n*(n+1))/2 long retval = ((((n % mod) * ((n + 1) % mod)) % mod) * modinv(2)) % mod; return retval;} public static long divisorSum(long n){ long l = 1; long ans = 0; while (l <= n) { long k = n / l; long r = n / k; k %= mod; // For i=l to i=r, // floor(n/i) will be k ans += ((sum(r) - sum(l - 1) % mod) * k) % mod; // Since values can be very // large we need to take mod // at every step ans %= mod; l = r + 1; } ans = ans % mod; return ans;} // Driver code public static void main(String[] args){ int n = 5; System.out.println(\"The sum of divisors of\" + \" all numbers from 1 to \" + n + \" is: \" + divisorSum(n)); n = 14; System.out.println(\"The sum of divisors of all\" + \" numbers from 1 to \" + n + \" is: \" + divisorSum(n));}} // This code is contributed by divyeshrabadiya07", "e": 13403, "s": 11578, "text": null }, { "code": "# Python program to calculate# sum of divisors of numbers# from 1 to N in O(sqrt(N))# complexitymod = 1000000007; # Function to calculate x^y using Modular exponentiation Refer to# https:#www.geeksforgeeks.org/ modular-exponentiation-power-in-# modular-arithmetic/def power(x, y, p): # re x^y if p not specified # else (x^y)%p res = 1; x = x % p; while (y > 0): if ((y & 1) != 0): res = (res * x) % p; y = y >> 1; x = (x * x) % p; return (res + p) % p; # Function to find modular# inverse of a under modulo m# Assumption: m is primedef modinv(x): return power(x, mod - 2, mod); # Function to calculate sum# from 1 to ndef sum(n): # sum 1 to n = (n*(n+1))/2 retval = ((((n % mod) * ((n + 1) % mod)) % mod) * modinv(2)) % mod; return retval; def divisorSum(n): l = 1; ans = 0; while (l <= n): k = n // l; r = n // k; k %= mod; # For i=l to i=r, # floor(n/i) will be k ans += ((sum(r) - sum(l - 1) % mod) * k) % mod; # Since values can be very # large we need to take mod # at every step ans %= mod; l = r + 1; ans = ans % mod; return ans; # Driver codeif __name__ == '__main__': n = 5; print(\"The sum of divisors of all numbers from 1 to \" , n , \" is: \" ,int( divisorSum(n))); n = 14; print(\"The sum of divisors of all numbers from 1 to \", n ,\" is: \" , int(divisorSum(n))); # This code contributed by aashish1995 Write", "e": 14909, "s": 13403, "text": null }, { "code": "// C# program to calculate// sum of divisors of numbers// from 1 to N in O(sqrt(N))// complexityusing System; class GFG{ static int mod = 1000000007; /*Function to calculate x^y using Modular exponentiationRefer to https://www.geeksforgeeks.org/modular-exponentiation-power-in-modular-arithmetic/*/static long power(long x, long y, long p){ // re x^y if p not specified // else (x^y)%p long res = 1; x = x % p; while (y > 0) { if ((y & 1) != 0) res = (res * x) % p; y = y >> 1; x = (x * x) % p; } return (res + p) % p;} // Function to find modular // inverse of a under modulo m// Assumption: m is primestatic long modinv(long x){ return power(x, mod - 2, mod);} // Function to calculate sum// from 1 to nstatic long sum(long n){ // sum 1 to n = (n*(n+1))/2 long retval = ((((n % mod) * ((n + 1) % mod)) % mod) * modinv(2)) % mod; return retval;} static long divisorSum(long n){ long l = 1; long ans = 0; while (l <= n) { long k = n / l; long r = n / k; k %= mod; // For i=l to i=r, // floor(n/i) will be k ans += ((sum(r) - sum(l - 1) % mod) * k) % mod; // Since values can be very // large we need to take mod // at every step ans %= mod; l = r + 1; } ans = ans % mod; return ans;} // Driver codestatic void Main(){ int n = 5; Console.WriteLine(\"The sum of divisors of\" + \" all numbers from 1 to \" + n + \" is: \" + divisorSum(n)); n = 14; Console.WriteLine(\"The sum of divisors of all\" + \" numbers from 1 to \" + n + \" is: \" + divisorSum(n));}} // This code is contributed by divyesh072019", "e": 16777, "s": 14909, "text": null }, { "code": "<script> // Javascript program to calculate// sum of divisors of numbers// from 1 to N in O(sqrt(N))// complexity var mod = 10007; /*Function to calculate x^y using Modular exponentiationRefer to https://www.geeksforgeeks.org/modular-exponentiation-power-in-modular-arithmetic/*/function power(x, y, p){ // re x^y if p not specified // else (x^y)%p var res = 1; x = x % p; while (y > 0) { if ((y & 1) != 0) res = (res * x) % p; y = y >> 1; x = (x * x) % p; } return (res + p) % p;} // Function to find modular // inverse of a under modulo m// Assumption: m is primefunction modinv(x){ return power(x, mod - 2, mod);} // Function to calculate sum// from 1 to nfunction sum(n){ // sum 1 to n = (n*(n+1))/2 var retval = Math.floor((((n % mod) * ((n + 1) % mod)) % mod) * modinv(2)) % mod; return retval;} function divisorSum(n){ var l = 1; var ans = 0; while (l <= n) { var k = n / l; var r = n / k; k %= mod; // For i=l to i=r, // floor(n/i) will be k ans += Math.floor((sum(r) - sum(l - 1) % mod) * k) % mod; // Since values can be very // large we need to take mod // at every step ans %= mod; l = r + 1; } ans = ans % mod; return ans;} // Driver code var n = 5; document.write(\"The sum of divisors of\" + \" all numbers from 1 to \" + n + \" is: \" + divisorSum(n) +\"<br>\"); n = 14; document.write(\"The sum of divisors of all\" + \" numbers from 1 to \" + n + \" is: \" + divisorSum(n)); // This code is contributed by shivanisinghss2110</script>", "e": 18436, "s": 16777, "text": null }, { "code": null, "e": 18444, "s": 18436, "text": "Output:" }, { "code": null, "e": 18554, "s": 18444, "text": "The sum of divisors of all numbers from 1 to 5 is: 21\nThe sum of divisors of all numbers from 1 to 14 is: 165" }, { "code": null, "e": 18582, "s": 18554, "text": "Time complexity: O(sqrt(N))" }, { "code": null, "e": 18604, "s": 18582, "text": "Auxiliary space: O(1)" }, { "code": null, "e": 18630, "s": 18604, "text": "Another sqrt(n) approach:" }, { "code": null, "e": 18705, "s": 18630, "text": "Anywhere division is used in the below article, it means integer division." }, { "code": null, "e": 18841, "s": 18705, "text": "Let’s start with an example assume that n = 20, now let’s see how each number from 1 to 20 appears as the factor of some other number." }, { "code": null, "e": 18990, "s": 18841, "text": " 1 : 1 * 1, 1 * 2, 1 * 3, 1 * 4..., 1 * (20 / 1)\n 2 : 2 * 1, 2 * 2, 2 * 3, 2 * 4,..., 2 * (20 / 2)\n 3 : 3 * 1, 3 * 2, 3 * 3, 3 * 4...., 3 * (20 / 3)" }, { "code": null, "e": 19811, "s": 18990, "text": "our goal is to add every number each time it appears as the factor of some other number. For example 3 appears as the factor of (3 * 1), (3 * 2), (3 * 3)..., (3 * (20 / 3)). Now let’s start from 1 and add 1 to our sum each time it appears and also we will add all the numbers that appeared with 1, we’ll do the same thing with 2 and when we reach 3 we have already added 3 to our sum when it appeared with 1 and 2 so now we will only add 3 when it appears with numbers greater than 2 i.e. 3, 4, 5, 6 also we will add the numbers that appeared with 3 so we’ll add 4, 5 and 6 as well (notice here we will not add 3 twice because of 3 * 3). Similarly when we reach 4 we have already added 4 when it appeared with 1, 2 and 3 so we’ll add it only when it appears with numbers >= itself and add the numbers that appear with 4." }, { "code": null, "e": 20142, "s": 19811, "text": "Finally we can say that when we are at a number i, we have already processed numbers from1 to i – 1 and hence we have added i every time it appears with numbers 1 to i – 1 so this time we only need to add i every time it appears with numbers >= i also we have to add all the numbers that appear together with i and they are > i." }, { "code": null, "e": 20217, "s": 20142, "text": "Therefore for every number i we want to add the following terms to our sum" }, { "code": null, "e": 21213, "s": 20217, "text": "t1 : (add i each time it appears with numbers >= itself) -> i * (num / i - (i - 1)) \n\n(recall i will appear with numbers 1 to num / i \nand we have already added i each time it appeared with a numbers less than itself)\n\nt2 : (add numbers that appear with i) -> (i + 1) + (i + 2) ... + (num / i) \n(numbers 1 to num / i will appear with i but \nwe have already processed numbers 1 to i - 1 and added them \nwhen they appeared with i so now we only have to add the numbers \nthat appear with i and are greater than i, \nhere we will not add i itself because when i appears with itself \nit should be added only once and we have added it once in t1)\n\nwe need to calculate t2 in O(1) time, here's how to do that\nt2 = (i + 1) + (i + 2) + (i + 3) + ... + (num / i)\nadd and subtract 1 + 2 + 3 ... + i\n=> t2 = 1 + 2 + 3 + ... + i + (i + 1) + (i + 2) + ... + (num / i) - (1 + 2 + 3 + ... + i)\n=> t2 = (1 + 2 + 3 + .. + (num / i)) - (1 + 2 + 3 .. + i)\n=> t2 = ((num / i) * (num / i + 1)) / 2 - (i * (i + 1)) / 2 " }, { "code": null, "e": 21404, "s": 21213, "text": "Finally, let’s look at the numbers that are greater than sqrt(num). These numbers will only appear with numbers that are lesser than sqrt(num). Let’s say x is a number greater than sqrt(num)" }, { "code": null, "e": 21524, "s": 21404, "text": "we have,\nx > sqrt(num)\nmultiply sqrt(num) on both sides\n=> x * sqrt(num) > sqrt(num) * sqrt(num)\n=> x * sqrt(num) > num" }, { "code": null, "e": 22135, "s": 21524, "text": "we want to add x each time it appears, from above proof we see that x multiplied by root of num itself is greater than num hence x will only appear with numbers less than root of num so if we process all the numbers from 1 to sqrt(num) we will add every time x appears. For example take n = 100 now consider 11, 11 * 10 > 100 so 11 appears only with 1 to 9 i.e. as a factor of 11, 22, 33,..., 99 same is true for rest of the numbers that are greater than 10 they will only appear with numbers lesser than 10 and hence we only need to process numbers from 1 to 10 to add the numbers greater than 10 for n = 100." }, { "code": null, "e": 22166, "s": 22135, "text": "Finally, our solution is this " }, { "code": null, "e": 22273, "s": 22166, "text": "for each i in 1 to sqrt(num) //no need to visit numbers greater than the root\n add t1 and t2 to the sum" }, { "code": null, "e": 22295, "s": 22273, "text": "below is the c++ code" }, { "code": null, "e": 22299, "s": 22295, "text": "C++" }, { "code": null, "e": 22304, "s": 22299, "text": "Java" }, { "code": null, "e": 22312, "s": 22304, "text": "Python3" }, { "code": null, "e": 22315, "s": 22312, "text": "C#" }, { "code": null, "e": 22326, "s": 22315, "text": "Javascript" }, { "code": "#include <bits/stdc++.h>using namespace std;long long sum_all_divisors(long long num){ long long sum = 0; for (long long i = 1; i <= sqrt(num); i++) { long long t1 = i * (num / i - i + 1); // adding i every time it appears with numbers greater than or equal to itself long long t2 = (((num / i) * (num / i + 1)) / 2) - ((i * (i + 1)) / 2); // adding numbers that appear with i and are greater than i sum += t1 + t2; } return sum;}int main(){ int n; long long sum = sum_all_divisors(n); cout << sum << '\\n'; return 0;}", "e": 22889, "s": 22326, "text": null }, { "code": "import java.io.*; class GFG { public static int sum_all_divisors(int num){ int sum = 0; for (int i = 1; i <= Math.sqrt(num); i++) { int t1 = i * (num / i - i + 1); // adding i every time it appears with numbers greater than or equal to itself int t2 = (((num / i) * (num / i + 1)) / 2) - ((i * (i + 1)) / 2); // adding numbers that appear with i and are greater than i sum += t1 + t2; } return sum;} // Driver code public static void main (String[] args){ int n = 1; int sum = sum_all_divisors(n); System.out.println(sum);}} // This code is contributed by shivanisinghss2110", "e": 23508, "s": 22889, "text": null }, { "code": "import mathdef sum_all_divisors(num): sum = 0; for i in range(1,math.floor(math.sqrt(num))+1): t1 = i * (num / i - i + 1) # adding i every time it appears with numbers greater than or equal to itself t2 = (((num / i) * (num / i + 1)) / 2) - ((i * (i + 1)) / 2) # adding numbers that appear with i and are greater than i sum += t1 + t2; return sum; n = 1sum = sum_all_divisors(n)print(sum) # This code is contributed by shivanisinghss2110", "e": 23982, "s": 23508, "text": null }, { "code": "using System; class GFG { public static int sum_all_divisors(int num){ int sum = 0; for (int i = 1; i <= Math.Sqrt(num); i++) { int t1 = i * (num / i - i + 1); // adding i every time it appears with numbers greater than or equal to itself int t2 = (((num / i) * (num / i + 1)) / 2) - ((i * (i + 1)) / 2); // adding numbers that appear with i and are greater than i sum += t1 + t2; } return sum;} // Driver code public static void Main (String[] args){ int n = 1; int sum = sum_all_divisors(n); Console.Write(sum);}} // This code is contributed by shivanisinghss2110", "e": 24592, "s": 23982, "text": null }, { "code": "<script>function sum_all_divisors(num){ var sum = 0; for (var i = 1; i <= Math.sqrt(num); i++) { var t1 = i * (num / i - i + 1); // adding i every time it appears with numbers greater than or equal to itself var t2 = (((num / i) * (num / i + 1)) / 2) - ((i * (i + 1)) / 2); // adding numbers that appear with i and are greater than i sum += t1 + t2; } return sum;} var n; var sum = sum_all_divisors(n); document.write( sum ); // This code is contributed by shivanisinghss2110</script>", "e": 25124, "s": 24592, "text": null }, { "code": null, "e": 25152, "s": 25124, "text": "Time complexity: O(sqrt(N))" }, { "code": null, "e": 25174, "s": 25152, "text": "Auxiliary space: O(1)" }, { "code": null, "e": 25180, "s": 25174, "text": "jit_t" }, { "code": null, "e": 25185, "s": 25180, "text": "vt_m" }, { "code": null, "e": 25200, "s": 25185, "text": "shreyanshjain1" }, { "code": null, "e": 25218, "s": 25200, "text": "divyeshrabadiya07" }, { "code": null, "e": 25232, "s": 25218, "text": "divyesh072019" }, { "code": null, "e": 25244, "s": 25232, "text": "aashish1995" }, { "code": null, "e": 25263, "s": 25244, "text": "shivanisinghss2110" }, { "code": null, "e": 25280, "s": 25263, "text": "_saurabh_jaiswal" }, { "code": null, "e": 25290, "s": 25280, "text": "abughalib" }, { "code": null, "e": 25305, "s": 25290, "text": "raikaushik2000" }, { "code": null, "e": 25315, "s": 25305, "text": "ruhelaa48" }, { "code": null, "e": 25334, "s": 25315, "text": "surindertarika1234" }, { "code": null, "e": 25343, "s": 25334, "text": "divisors" }, { "code": null, "e": 25357, "s": 25343, "text": "number-theory" }, { "code": null, "e": 25370, "s": 25357, "text": "Mathematical" }, { "code": null, "e": 25384, "s": 25370, "text": "number-theory" }, { "code": null, "e": 25397, "s": 25384, "text": "Mathematical" }, { "code": null, "e": 25495, "s": 25397, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 25525, "s": 25495, "text": "Program for Fibonacci numbers" }, { "code": null, "e": 25568, "s": 25525, "text": "Set in C++ Standard Template Library (STL)" }, { "code": null, "e": 25628, "s": 25568, "text": "Write a program to print all permutations of a given string" }, { "code": null, "e": 25643, "s": 25628, "text": "C++ Data Types" }, { "code": null, "e": 25667, "s": 25643, "text": "Merge two sorted arrays" }, { "code": null, "e": 25686, "s": 25667, "text": "Coin Change | DP-7" }, { "code": null, "e": 25707, "s": 25686, "text": "Operators in C / C++" }, { "code": null, "e": 25721, "s": 25707, "text": "Prime Numbers" }, { "code": null, "e": 25763, "s": 25721, "text": "Program to find GCD or HCF of two numbers" } ]
Stack push() Method in Java
10 Jun, 2022 Java.util.Stack.push(E element) method is used to push an element into the Stack. The element gets pushed onto the top of the Stack. Syntax: STACK.push(E element) Parameters: The method accepts one parameter element of type Stack and refers to the element to be pushed into the stack. Return Value: The method returns the argument passed. It also accepts the null value unlike ArrayDeque.push() which throws java.lang.NullPointerException on doing the same. Below programs illustrate the Java.util.Stack.push() method: Program 1: Adding String elements into the Stack. Java // Java Code to illustrate push() Method import java.util.*; // Main classpublic class StackDemo { // Main driver method public static void main(String args[]) { // Creating an empty Stack Stack& lt; String& gt; STACK = new Stack& lt; String& gt; (); // Adding elements into the stack // using push() method STACK.push(" Welcome & quot;); STACK.push(" To & quot;); STACK.push(" Geeks & quot;); STACK.push(" For & quot;); STACK.push(" Geeks & quot;); // Displaying the Stack System.out.println(" Initial Stack : " + STACK); // Pushing elements into the stack STACK.push(" Hello & quot;); STACK.push(" World & quot;); // Displaying the final Stack System.out.println(" Final Stack : " + STACK); }} Initial Stack: [Welcome, To, Geeks, For, Geeks] Final Stack: [Welcome, To, Geeks, For, Geeks, Hello, World] Program 2: Adding Integer elements into the Stack. Java // Java code to illustrate push() methodimport java.util.*; public class StackDemo { public static void main(String args[]) { // Creating an empty Stack Stack<Integer> STACK = new Stack<Integer>(); // Use push() to add elements into the Stack STACK.push(10); STACK.push(15); STACK.push(30); STACK.push(20); STACK.push(5); STACK.push(null); // Displaying the Stack System.out.println("Initial Stack: " + STACK); // Pushing elements into the Stack STACK.push(1254); STACK.push(4521); // Displaying the final Stack System.out.println("Final Stack: " + STACK); }} Initial Stack: [10, 15, 30, 20, 5] Final Stack: [10, 15, 30, 20, 5, 1254, 4521] anand00525 Java - util package Java-Collections Java-Functions Java-Stack Java Java Java-Collections Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Arrays in Java Arrays.sort() in Java with examples Reverse a string in Java Split() String method in Java with examples Object Oriented Programming (OOPs) Concept in Java For-each loop in Java How to iterate any Map in Java Interfaces in Java HashMap in Java with Examples ArrayList in Java
[ { "code": null, "e": 53, "s": 25, "text": "\n10 Jun, 2022" }, { "code": null, "e": 186, "s": 53, "text": "Java.util.Stack.push(E element) method is used to push an element into the Stack. The element gets pushed onto the top of the Stack." }, { "code": null, "e": 194, "s": 186, "text": "Syntax:" }, { "code": null, "e": 216, "s": 194, "text": "STACK.push(E element)" }, { "code": null, "e": 338, "s": 216, "text": "Parameters: The method accepts one parameter element of type Stack and refers to the element to be pushed into the stack." }, { "code": null, "e": 512, "s": 338, "text": "Return Value: The method returns the argument passed. It also accepts the null value unlike ArrayDeque.push() which throws java.lang.NullPointerException on doing the same." }, { "code": null, "e": 574, "s": 512, "text": "Below programs illustrate the Java.util.Stack.push() method: " }, { "code": null, "e": 625, "s": 574, "text": "Program 1: Adding String elements into the Stack. " }, { "code": null, "e": 630, "s": 625, "text": "Java" }, { "code": "// Java Code to illustrate push() Method import java.util.*; // Main classpublic class StackDemo { // Main driver method public static void main(String args[]) { // Creating an empty Stack Stack& lt; String& gt; STACK = new Stack& lt; String& gt; (); // Adding elements into the stack // using push() method STACK.push(\" Welcome & quot;); STACK.push(\" To & quot;); STACK.push(\" Geeks & quot;); STACK.push(\" For & quot;); STACK.push(\" Geeks & quot;); // Displaying the Stack System.out.println(\" Initial Stack : \" + STACK); // Pushing elements into the stack STACK.push(\" Hello & quot;); STACK.push(\" World & quot;); // Displaying the final Stack System.out.println(\" Final Stack : \" + STACK); }}", "e": 1587, "s": 630, "text": null }, { "code": null, "e": 1695, "s": 1587, "text": "Initial Stack: [Welcome, To, Geeks, For, Geeks]\nFinal Stack: [Welcome, To, Geeks, For, Geeks, Hello, World]" }, { "code": null, "e": 1747, "s": 1695, "text": "Program 2: Adding Integer elements into the Stack. " }, { "code": null, "e": 1752, "s": 1747, "text": "Java" }, { "code": "// Java code to illustrate push() methodimport java.util.*; public class StackDemo { public static void main(String args[]) { // Creating an empty Stack Stack<Integer> STACK = new Stack<Integer>(); // Use push() to add elements into the Stack STACK.push(10); STACK.push(15); STACK.push(30); STACK.push(20); STACK.push(5); STACK.push(null); // Displaying the Stack System.out.println(\"Initial Stack: \" + STACK); // Pushing elements into the Stack STACK.push(1254); STACK.push(4521); // Displaying the final Stack System.out.println(\"Final Stack: \" + STACK); }}", "e": 2437, "s": 1752, "text": null }, { "code": null, "e": 2517, "s": 2437, "text": "Initial Stack: [10, 15, 30, 20, 5]\nFinal Stack: [10, 15, 30, 20, 5, 1254, 4521]" }, { "code": null, "e": 2528, "s": 2517, "text": "anand00525" }, { "code": null, "e": 2548, "s": 2528, "text": "Java - util package" }, { "code": null, "e": 2565, "s": 2548, "text": "Java-Collections" }, { "code": null, "e": 2580, "s": 2565, "text": "Java-Functions" }, { "code": null, "e": 2591, "s": 2580, "text": "Java-Stack" }, { "code": null, "e": 2596, "s": 2591, "text": "Java" }, { "code": null, "e": 2601, "s": 2596, "text": "Java" }, { "code": null, "e": 2618, "s": 2601, "text": "Java-Collections" }, { "code": null, "e": 2716, "s": 2618, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 2731, "s": 2716, "text": "Arrays in Java" }, { "code": null, "e": 2767, "s": 2731, "text": "Arrays.sort() in Java with examples" }, { "code": null, "e": 2792, "s": 2767, "text": "Reverse a string in Java" }, { "code": null, "e": 2836, "s": 2792, "text": "Split() String method in Java with examples" }, { "code": null, "e": 2887, "s": 2836, "text": "Object Oriented Programming (OOPs) Concept in Java" }, { "code": null, "e": 2909, "s": 2887, "text": "For-each loop in Java" }, { "code": null, "e": 2940, "s": 2909, "text": "How to iterate any Map in Java" }, { "code": null, "e": 2959, "s": 2940, "text": "Interfaces in Java" }, { "code": null, "e": 2989, "s": 2959, "text": "HashMap in Java with Examples" } ]
Range queries for alternatively addition and subtraction on given Array
07 Apr, 2022 Given an array arr[] of N integers and Q queries where every row consists of two numbers L and R which denotes the range [L, R], the task is to find the value of alternate addition and subtraction of the array element between range [L, R]. Examples: Input: arr[] = {10, 13, 15, 2, 45, 31, 22, 3, 27}, Q[][] = {{2, 5}, {6, 8}, {1, 7}, {4, 8}, {0, 5}} Output: 27 46 -33 60 24 Explanation: Result of query {2, 5} is 27 ( 15 – 2 + 45 – 31) Result of query {6, 8} is 46 ( 22 – 3 + 27) Result of query {1, 7} is -33 ( 13 – 15 + 2 – 45 + 31 – 22 + 3) Result of query {4, 8} is 60 ( 45 – 31 + 22 – 3 + 27) Result of query {0, 5} is 24 ( 10 – 13 + 15 – 2 + 45 – 31) Input: arr[] = {1, 1, 1, 1, 1, 1, 1, 1, 1}, Q[] = {{2, 5}, {6, 8}, {1, 7}, {4, 8}, {0, 5}} Output: 0 1 1 1 0 Naive Approach: The naive idea is to iterate from index L to R for each query and find the value of alternatively adding and subtracting the elements of the array and print the value after the operations are performed. Below is the implementation of the above approach: C++ Java Python3 C# Javascript // C++ program for the above approach#include <bits/stdc++.h>using namespace std; // Structure to represent a range querystruct Query { int L, R;}; // Function to find the result of// alternatively adding and subtracting// elements in the range [L, R]int findResultUtil(int arr[], int L, int R){ int result = 0; // A boolean variable flag to // alternatively add and subtract bool flag = false; // Iterate from [L, R] for (int i = L; i <= R; i++) { // if flag is false, then // add & toggle the flag if (flag == false) { result = result + arr[i]; flag = true; } // if flag is true subtract // and toggle the flag else { result = result - arr[i]; flag = false; } } // Return the final result return result;} // Function to find the value// for each queryvoid findResult(int arr[], int n, Query q[], int m){ // Iterate for each query for (int i = 0; i < m; i++) { cout << findResultUtil(arr, q[i].L, q[i].R) << " "; }} // Driver Codeint main(){ // Given array int arr[] = { 10, 13, 15, 2, 45, 31, 22, 3, 27 }; int n = sizeof(arr) / sizeof(arr[0]); // Given Queries Query q[] = { { 2, 5 }, { 6, 8 }, { 1, 7 }, { 4, 8 }, { 0, 5 } }; int m = sizeof(q) / sizeof(q[0]); // Function Call findResult(arr, n, q, m); return 0;} // Java program for the above approachimport java.util.*; class GFG{ // Structure to represent a range querystatic class Query{ int L, R; public Query(int l, int r) { super(); L = l; R = r; }}; // Function to find the result of// alternatively adding and subtracting// elements in the range [L, R]static int findResultUtil(int arr[], int L, int R){ int result = 0; // A boolean variable flag to // alternatively add and subtract boolean flag = false; // Iterate from [L, R] for(int i = L; i <= R; i++) { // If flag is false, then // add & toggle the flag if (flag == false) { result = result + arr[i]; flag = true; } // If flag is true subtract // and toggle the flag else { result = result - arr[i]; flag = false; } } // Return the final result return result;} // Function to find the value// for each querystatic void findResult(int arr[], int n, Query q[], int m){ // Iterate for each query for(int i = 0; i < m; i++) { System.out.print(findResultUtil(arr, q[i].L, q[i].R) + " "); }} // Driver Codepublic static void main(String[] args){ // Given array int arr[] = { 10, 13, 15, 2, 45, 31, 22, 3, 27 }; int n = arr.length; // Given Queries Query q[] = { new Query(2, 5), new Query(6, 8), new Query(1, 7), new Query(4, 8), new Query(0, 5) }; int m = q.length; // Function call findResult(arr, n, q, m);}} // This code is contributed by Princi Singh # Python3 program for the above approach # Function to find the result of# alternatively adding and subtracting# elements in the range [L, R]def findResultUtil(arr, L, R): result = 0 # A boolean variable flag to # alternatively add and subtract flag = False # Iterate from [L, R] for i in range(L, R + 1): # If flag is False, then # add & toggle the flag if (flag == False): result = result + arr[i] flag = True # If flag is True subtract # and toggle the flag else: result = result - arr[i] flag = False # Return the final result return result # Function to find the value# for each querydef findResult(arr, n, q, m): # Iterate for each query for i in range(m): print(findResultUtil(arr, q[i][0], q[i][1]), end = " ") # Driver Codeif __name__ == '__main__': # Given array arr = [ 10, 13, 15, 2, 45, 31, 22, 3, 27 ] n = len(arr) # Given Queries q = [ [ 2, 5 ], [ 6, 8 ], [ 1, 7 ], [ 4, 8 ], [ 0, 5 ] ] m = len(q) # Function Call findResult(arr, n, q, m) # This code is contributed by mohit kumar 29 // C# program for the above approachusing System;class GFG{ // Structure to represent a range queryclass Query{ public int L, R; public Query(int l, int r) { L = l; R = r; }}; // Function to find the result of// alternatively adding and subtracting// elements in the range [L, R]static int findResultUtil(int []arr, int L, int R){ int result = 0; // A bool variable flag to // alternatively add and subtract bool flag = false; // Iterate from [L, R] for(int i = L; i <= R; i++) { // If flag is false, then // add & toggle the flag if (flag == false) { result = result + arr[i]; flag = true; } // If flag is true subtract // and toggle the flag else { result = result - arr[i]; flag = false; } } // Return the readonly result return result;} // Function to find the value// for each querystatic void findResult(int []arr, int n, Query []q, int m){ // Iterate for each query for(int i = 0; i < m; i++) { Console.Write(findResultUtil(arr, q[i].L, q[i].R) + " "); }} // Driver Codepublic static void Main(String[] args){ // Given array int []arr = { 10, 13, 15, 2, 45, 31, 22, 3, 27 }; int n = arr.Length; // Given Queries Query []q = { new Query(2, 5), new Query(6, 8), new Query(1, 7), new Query(4, 8), new Query(0, 5) }; int m = q.Length; // Function call findResult(arr, n, q, m);}} // This code is contributed by gauravrajput1 <script> // Javascript program for the above approach // Function to find the result of// alternatively adding and subtracting// elements in the range [L, R]function findResultUtil(arr, L, R){ var result = 0; // A boolean variable flag to // alternatively add and subtract var flag = false; // Iterate from [L, R] for (var i = L; i <= R; i++) { // if flag is false, then // add & toggle the flag if (flag == false) { result = result + arr[i]; flag = true; } // if flag is true subtract // and toggle the flag else { result = result - arr[i]; flag = false; } } // Return the final result return result;} // Function to find the value// for each queryfunction findResult(arr, n, q, m){ // Iterate for each query for (var i = 0; i < m; i++) { document.write( findResultUtil(arr, q[i][0], q[i][1]) + " "); }} // Driver Code// Given arrayvar arr = [10, 13, 15, 2, 45, 31, 22, 3, 27 ];var n = arr.length;// Given Queriesvar q = [ [ 2, 5 ], [ 6, 8 ], [ 1, 7 ], [ 4, 8 ], [ 0, 5 ] ];var m = q.length;// Function CallfindResult(arr, n, q, m); </script> 27 46 -33 60 24 Time Complexity: O(N*Q) Auxiliary Space: O(1) Efficient Approach: The efficient approach is to use Prefix Sum Array to solve the above problem. Below are the steps: Initialize the first element of prefix array(say pre[]) to first element of the arr[].Traverse through an index from 1 to N-1 and alternative add and subtract the elements of arr[i] from pre[i-1] and store it in pre[i] to make a prefix array.Now, Iterate through each query from 1 to Q, and find the result on the basis of the below cases: Case 1: If L is zero then result is pre[R].Case 2: If L is non-zero, find the result using the equation: Initialize the first element of prefix array(say pre[]) to first element of the arr[]. Traverse through an index from 1 to N-1 and alternative add and subtract the elements of arr[i] from pre[i-1] and store it in pre[i] to make a prefix array. Now, Iterate through each query from 1 to Q, and find the result on the basis of the below cases: Case 1: If L is zero then result is pre[R].Case 2: If L is non-zero, find the result using the equation: Case 1: If L is zero then result is pre[R]. Case 2: If L is non-zero, find the result using the equation: result = Query(L, R) = pre[R] – pre[L - 1] If L is odd multiply the above result by -1. Below is the implementation of the above approach: C++ Java Python3 C# Javascript // C++ program for the above approach#include <bits/stdc++.h>using namespace std; // Structure to represent a querystruct Query { int L, R;}; // This function fills the Prefix Arrayvoid fillPrefixArray(int arr[], int n, int prefixArray[]){ // Initialise the prefix array prefixArray[0] = arr[0]; // Iterate all the element of arr[] // and update the prefix array for (int i = 1; i < n; i++) { // If n is even then, add the // previous value of prefix array // with the current value of arr if (i % 2 == 0) { prefixArray[i] = prefixArray[i - 1] + arr[i]; } // if n is odd, then subtract // the previous value of prefix // Array from current value else { prefixArray[i] = prefixArray[i - 1] - arr[i]; } }} // Function to find the result of// alternatively adding and subtracting// elements in the range [L< R]int findResultUtil(int prefixArray[], int L, int R){ int result; // Case 1 : when L is zero if (L == 0) { result = prefixArray[R]; } // Case 2 : When L is non zero else { result = prefixArray[R] - prefixArray[L - 1]; } // If L is odd means range starts from // odd position multiply result by -1 if (L & 1) { result = result * (-1); } // Return the final result return result;} // Function to find the sum of all// alternative add and subtract// between ranges [L, R]void findResult(int arr[], int n, Query q[], int m){ // Declare prefix array int prefixArray[n]; // Function Call to fill prefix arr[] fillPrefixArray(arr, n, prefixArray); // Iterate for each query for (int i = 0; i < m; i++) { cout << findResultUtil(prefixArray, q[i].L, q[i].R) << " "; }} // Driver Codeint main(){ // Given array int arr[] = { 10, 13, 15, 2, 45, 31, 22, 3, 27 }; int n = sizeof(arr) / sizeof(arr[0]); // Given Queries Query q[] = { { 2, 5 }, { 6, 8 }, { 1, 7 }, { 4, 8 }, { 0, 5 } }; int m = sizeof(q) / sizeof(q[0]); // Function Call findResult(arr, n, q, m); return 0;} // Java program for the above approachimport java.util.*;class GFG{ // Structure to represent a querystatic class Query{ int L, R; public Query(int l, int r) { super(); L = l; R = r; }}; // This function fills the Prefix Arraystatic void fillPrefixArray(int arr[], int n, int prefixArray[]){ // Initialise the prefix array prefixArray[0] = arr[0]; // Iterate all the element of arr[] // and update the prefix array for (int i = 1; i < n; i++) { // If n is even then, add the // previous value of prefix array // with the current value of arr if (i % 2 == 0) { prefixArray[i] = prefixArray[i - 1] + arr[i]; } // if n is odd, then subtract // the previous value of prefix // Array from current value else { prefixArray[i] = prefixArray[i - 1] - arr[i]; } }} // Function to find the result of// alternatively adding and subtracting// elements in the range [L< R]static int findResultUtil(int prefixArray[], int L, int R){ int result; // Case 1 : when L is zero if (L == 0) { result = prefixArray[R]; } // Case 2 : When L is non zero else { result = prefixArray[R] - prefixArray[L - 1]; } // If L is odd means range starts from // odd position multiply result by -1 if (L % 2 == 1) { result = result * (-1); } // Return the final result return result;} // Function to find the sum of all// alternative add and subtract// between ranges [L, R]static void findResult(int arr[], int n, Query q[], int m){ // Declare prefix array int []prefixArray = new int[n]; // Function Call to fill prefix arr[] fillPrefixArray(arr, n, prefixArray); // Iterate for each query for (int i = 0; i < m; i++) { System.out.print(findResultUtil( prefixArray, q[i].L, q[i].R) + " "); }} // Driver Codepublic static void main(String[] args){ // Given array int arr[] = { 10, 13, 15, 2, 45, 31, 22, 3, 27 }; int n = arr.length; // Given Queries Query q[] = {new Query( 2, 5 ), new Query( 6, 8 ), new Query( 1, 7 ), new Query( 4, 8 ), new Query( 0, 5 )}; int m = q.length; // Function Call findResult(arr, n, q, m);}} // This code is contributed by PrinciRaj1992 # Python program for the above approach # Structure to represent a queryclass Query: def __init__(self,l,r): self.L = l self.R = r # This function fills the Prefix Arraydef fillPrefixArray(arr, n, prefixArray): # Initialise the prefix array prefixArray[0] = arr[0] # Iterate all the element of arr[] # and update the prefix array for i in range(1,n): # If n is even then, add the # previous value of prefix array # with the current value of arr if (i % 2 == 0): prefixArray[i] = prefixArray[i - 1] + arr[i] # if n is odd, then subtract # the previous value of prefix # Array from current value else: prefixArray[i] = prefixArray[i - 1] - arr[i] # Function to find the result of# alternatively adding and subtracting# elements in the range [L< R]def findResultUtil(prefixArray, L, R): # Case 1 : when L is zero if (L == 0): result = prefixArray[R] # Case 2 : When L is non zero else: result = prefixArray[R] - prefixArray[L - 1] # If L is odd means range starts from # odd position multiply result by -1 if (L % 2 == 1): result = result * (-1) # Return the final result return result # Function to find the sum of all# alternative add and subtract# between ranges [L, R]def findResult(arr, n, q, m): # Declare prefix array prefixArray = [0 for i in range(n)] # Function Call to fill prefix arr[] fillPrefixArray(arr, n, prefixArray) # Iterate for each query for i in range(m): print(findResultUtil(prefixArray, q[i].L,q[i].R),end = " ") # Driver Code # Given arrayarr = [ 10, 13, 15, 2, 45, 31, 22, 3, 27 ]n = len(arr) # Given Queriesq = [ Query(2, 5), Query(6, 8), Query(1, 7), Query(4, 8), Query(0, 5)]m = len(q) # Function CallfindResult(arr, n, q, m) # This code is contributed by shinjanpatra // C# program for the above approachusing System;class GFG{ // Structure to represent a queryclass Query{ public int L, R; public Query(int l, int r) { L = l; R = r; }}; // This function fills the Prefix Arraystatic void fillPrefixArray(int []arr, int n, int []prefixArray){ // Initialise the prefix array prefixArray[0] = arr[0]; // Iterate all the element of []arr // and update the prefix array for (int i = 1; i < n; i++) { // If n is even then, add the // previous value of prefix array // with the current value of arr if (i % 2 == 0) { prefixArray[i] = prefixArray[i - 1] + arr[i]; } // if n is odd, then subtract // the previous value of prefix // Array from current value else { prefixArray[i] = prefixArray[i - 1] - arr[i]; } }} // Function to find the result of// alternatively adding and subtracting// elements in the range [L< R]static int findResultUtil(int []prefixArray, int L, int R){ int result; // Case 1 : when L is zero if (L == 0) { result = prefixArray[R]; } // Case 2 : When L is non zero else { result = prefixArray[R] - prefixArray[L - 1]; } // If L is odd means range starts from // odd position multiply result by -1 if (L % 2 == 1) { result = result * (-1); } // Return the readonly result return result;} // Function to find the sum of all// alternative add and subtract// between ranges [L, R]static void findResult(int []arr, int n, Query []q, int m){ // Declare prefix array int []prefixArray = new int[n]; // Function Call to fill prefix []arr fillPrefixArray(arr, n, prefixArray); // Iterate for each query for (int i = 0; i < m; i++) { Console.Write(findResultUtil( prefixArray, q[i].L, q[i].R) + " "); }} // Driver Codepublic static void Main(String[] args){ // Given array int []arr = { 10, 13, 15, 2, 45, 31, 22, 3, 27 }; int n = arr.Length; // Given Queries Query []q = {new Query( 2, 5 ), new Query( 6, 8 ), new Query( 1, 7 ), new Query( 4, 8 ), new Query( 0, 5 )}; int m = q.Length; // Function Call findResult(arr, n, q, m);}} // This code is contributed by Rohit_ranjan <script> // Javascript program for the above approach // Structure to represent a queryclass Query{ constructor(l, r) { this.L = l; this.R = r; }} // This function fills the Prefix Arrayfunction fillPrefixArray(arr, n, prefixArray){ // Initialise the prefix array prefixArray[0] = arr[0]; // Iterate all the element of arr[] // and update the prefix array for(let i = 1; i < n; i++) { // If n is even then, add the // previous value of prefix array // with the current value of arr if (i % 2 == 0) { prefixArray[i] = prefixArray[i - 1] + arr[i]; } // if n is odd, then subtract // the previous value of prefix // Array from current value else { prefixArray[i] = prefixArray[i - 1] - arr[i]; } }} // Function to find the result of// alternatively adding and subtracting// elements in the range [L< R]function findResultUtil(prefixArray, L, R){ let result; // Case 1 : when L is zero if (L == 0) { result = prefixArray[R]; } // Case 2 : When L is non zero else { result = prefixArray[R] - prefixArray[L - 1]; } // If L is odd means range starts from // odd position multiply result by -1 if (L % 2 == 1) { result = result * (-1); } // Return the final result return result;} // Function to find the sum of all// alternative add and subtract// between ranges [L, R]function findResult(arr, n, q, m){ // Declare prefix array let prefixArray = new Array(n); // Function Call to fill prefix arr[] fillPrefixArray(arr, n, prefixArray); // Iterate for each query for(let i = 0; i < m; i++) { document.write(findResultUtil( prefixArray, q[i].L, q[i].R) + " "); }} // Driver Code // Given arraylet arr = [ 10, 13, 15, 2, 45, 31, 22, 3, 27 ];let n = arr.length; // Given Querieslet q = [ new Query(2, 5), new Query(6, 8), new Query(1, 7), new Query(4, 8), new Query(0, 5)];let m = q.length; // Function CallfindResult(arr, n, q, m); // This code is contributed by unknown2108 </script> Output: 27 46 -33 60 24 Time Complexity:O(N + Q) Auxiliary Space: O(N) mohit kumar 29 princi singh GauravRajput1 princiraj1992 Rohit_ranjan famously unknown2108 shinjanpatra array-range-queries Algorithms Arrays Dynamic Programming Arrays Dynamic Programming Algorithms Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 54, "s": 26, "text": "\n07 Apr, 2022" }, { "code": null, "e": 294, "s": 54, "text": "Given an array arr[] of N integers and Q queries where every row consists of two numbers L and R which denotes the range [L, R], the task is to find the value of alternate addition and subtraction of the array element between range [L, R]." }, { "code": null, "e": 305, "s": 294, "text": "Examples: " }, { "code": null, "e": 712, "s": 305, "text": "Input: arr[] = {10, 13, 15, 2, 45, 31, 22, 3, 27}, Q[][] = {{2, 5}, {6, 8}, {1, 7}, {4, 8}, {0, 5}} Output: 27 46 -33 60 24 Explanation: Result of query {2, 5} is 27 ( 15 – 2 + 45 – 31) Result of query {6, 8} is 46 ( 22 – 3 + 27) Result of query {1, 7} is -33 ( 13 – 15 + 2 – 45 + 31 – 22 + 3) Result of query {4, 8} is 60 ( 45 – 31 + 22 – 3 + 27) Result of query {0, 5} is 24 ( 10 – 13 + 15 – 2 + 45 – 31)" }, { "code": null, "e": 822, "s": 712, "text": "Input: arr[] = {1, 1, 1, 1, 1, 1, 1, 1, 1}, Q[] = {{2, 5}, {6, 8}, {1, 7}, {4, 8}, {0, 5}} Output: 0 1 1 1 0 " }, { "code": null, "e": 1041, "s": 822, "text": "Naive Approach: The naive idea is to iterate from index L to R for each query and find the value of alternatively adding and subtracting the elements of the array and print the value after the operations are performed." }, { "code": null, "e": 1094, "s": 1041, "text": "Below is the implementation of the above approach: " }, { "code": null, "e": 1098, "s": 1094, "text": "C++" }, { "code": null, "e": 1103, "s": 1098, "text": "Java" }, { "code": null, "e": 1111, "s": 1103, "text": "Python3" }, { "code": null, "e": 1114, "s": 1111, "text": "C#" }, { "code": null, "e": 1125, "s": 1114, "text": "Javascript" }, { "code": "// C++ program for the above approach#include <bits/stdc++.h>using namespace std; // Structure to represent a range querystruct Query { int L, R;}; // Function to find the result of// alternatively adding and subtracting// elements in the range [L, R]int findResultUtil(int arr[], int L, int R){ int result = 0; // A boolean variable flag to // alternatively add and subtract bool flag = false; // Iterate from [L, R] for (int i = L; i <= R; i++) { // if flag is false, then // add & toggle the flag if (flag == false) { result = result + arr[i]; flag = true; } // if flag is true subtract // and toggle the flag else { result = result - arr[i]; flag = false; } } // Return the final result return result;} // Function to find the value// for each queryvoid findResult(int arr[], int n, Query q[], int m){ // Iterate for each query for (int i = 0; i < m; i++) { cout << findResultUtil(arr, q[i].L, q[i].R) << \" \"; }} // Driver Codeint main(){ // Given array int arr[] = { 10, 13, 15, 2, 45, 31, 22, 3, 27 }; int n = sizeof(arr) / sizeof(arr[0]); // Given Queries Query q[] = { { 2, 5 }, { 6, 8 }, { 1, 7 }, { 4, 8 }, { 0, 5 } }; int m = sizeof(q) / sizeof(q[0]); // Function Call findResult(arr, n, q, m); return 0;}", "e": 2682, "s": 1125, "text": null }, { "code": "// Java program for the above approachimport java.util.*; class GFG{ // Structure to represent a range querystatic class Query{ int L, R; public Query(int l, int r) { super(); L = l; R = r; }}; // Function to find the result of// alternatively adding and subtracting// elements in the range [L, R]static int findResultUtil(int arr[], int L, int R){ int result = 0; // A boolean variable flag to // alternatively add and subtract boolean flag = false; // Iterate from [L, R] for(int i = L; i <= R; i++) { // If flag is false, then // add & toggle the flag if (flag == false) { result = result + arr[i]; flag = true; } // If flag is true subtract // and toggle the flag else { result = result - arr[i]; flag = false; } } // Return the final result return result;} // Function to find the value// for each querystatic void findResult(int arr[], int n, Query q[], int m){ // Iterate for each query for(int i = 0; i < m; i++) { System.out.print(findResultUtil(arr, q[i].L, q[i].R) + \" \"); }} // Driver Codepublic static void main(String[] args){ // Given array int arr[] = { 10, 13, 15, 2, 45, 31, 22, 3, 27 }; int n = arr.length; // Given Queries Query q[] = { new Query(2, 5), new Query(6, 8), new Query(1, 7), new Query(4, 8), new Query(0, 5) }; int m = q.length; // Function call findResult(arr, n, q, m);}} // This code is contributed by Princi Singh", "e": 4383, "s": 2682, "text": null }, { "code": "# Python3 program for the above approach # Function to find the result of# alternatively adding and subtracting# elements in the range [L, R]def findResultUtil(arr, L, R): result = 0 # A boolean variable flag to # alternatively add and subtract flag = False # Iterate from [L, R] for i in range(L, R + 1): # If flag is False, then # add & toggle the flag if (flag == False): result = result + arr[i] flag = True # If flag is True subtract # and toggle the flag else: result = result - arr[i] flag = False # Return the final result return result # Function to find the value# for each querydef findResult(arr, n, q, m): # Iterate for each query for i in range(m): print(findResultUtil(arr, q[i][0], q[i][1]), end = \" \") # Driver Codeif __name__ == '__main__': # Given array arr = [ 10, 13, 15, 2, 45, 31, 22, 3, 27 ] n = len(arr) # Given Queries q = [ [ 2, 5 ], [ 6, 8 ], [ 1, 7 ], [ 4, 8 ], [ 0, 5 ] ] m = len(q) # Function Call findResult(arr, n, q, m) # This code is contributed by mohit kumar 29", "e": 5666, "s": 4383, "text": null }, { "code": "// C# program for the above approachusing System;class GFG{ // Structure to represent a range queryclass Query{ public int L, R; public Query(int l, int r) { L = l; R = r; }}; // Function to find the result of// alternatively adding and subtracting// elements in the range [L, R]static int findResultUtil(int []arr, int L, int R){ int result = 0; // A bool variable flag to // alternatively add and subtract bool flag = false; // Iterate from [L, R] for(int i = L; i <= R; i++) { // If flag is false, then // add & toggle the flag if (flag == false) { result = result + arr[i]; flag = true; } // If flag is true subtract // and toggle the flag else { result = result - arr[i]; flag = false; } } // Return the readonly result return result;} // Function to find the value// for each querystatic void findResult(int []arr, int n, Query []q, int m){ // Iterate for each query for(int i = 0; i < m; i++) { Console.Write(findResultUtil(arr, q[i].L, q[i].R) + \" \"); }} // Driver Codepublic static void Main(String[] args){ // Given array int []arr = { 10, 13, 15, 2, 45, 31, 22, 3, 27 }; int n = arr.Length; // Given Queries Query []q = { new Query(2, 5), new Query(6, 8), new Query(1, 7), new Query(4, 8), new Query(0, 5) }; int m = q.Length; // Function call findResult(arr, n, q, m);}} // This code is contributed by gauravrajput1", "e": 7337, "s": 5666, "text": null }, { "code": "<script> // Javascript program for the above approach // Function to find the result of// alternatively adding and subtracting// elements in the range [L, R]function findResultUtil(arr, L, R){ var result = 0; // A boolean variable flag to // alternatively add and subtract var flag = false; // Iterate from [L, R] for (var i = L; i <= R; i++) { // if flag is false, then // add & toggle the flag if (flag == false) { result = result + arr[i]; flag = true; } // if flag is true subtract // and toggle the flag else { result = result - arr[i]; flag = false; } } // Return the final result return result;} // Function to find the value// for each queryfunction findResult(arr, n, q, m){ // Iterate for each query for (var i = 0; i < m; i++) { document.write( findResultUtil(arr, q[i][0], q[i][1]) + \" \"); }} // Driver Code// Given arrayvar arr = [10, 13, 15, 2, 45, 31, 22, 3, 27 ];var n = arr.length;// Given Queriesvar q = [ [ 2, 5 ], [ 6, 8 ], [ 1, 7 ], [ 4, 8 ], [ 0, 5 ] ];var m = q.length;// Function CallfindResult(arr, n, q, m); </script>", "e": 8642, "s": 7337, "text": null }, { "code": null, "e": 8658, "s": 8642, "text": "27 46 -33 60 24" }, { "code": null, "e": 8706, "s": 8660, "text": "Time Complexity: O(N*Q) Auxiliary Space: O(1)" }, { "code": null, "e": 8826, "s": 8706, "text": "Efficient Approach: The efficient approach is to use Prefix Sum Array to solve the above problem. Below are the steps: " }, { "code": null, "e": 9271, "s": 8826, "text": "Initialize the first element of prefix array(say pre[]) to first element of the arr[].Traverse through an index from 1 to N-1 and alternative add and subtract the elements of arr[i] from pre[i-1] and store it in pre[i] to make a prefix array.Now, Iterate through each query from 1 to Q, and find the result on the basis of the below cases: Case 1: If L is zero then result is pre[R].Case 2: If L is non-zero, find the result using the equation:" }, { "code": null, "e": 9358, "s": 9271, "text": "Initialize the first element of prefix array(say pre[]) to first element of the arr[]." }, { "code": null, "e": 9515, "s": 9358, "text": "Traverse through an index from 1 to N-1 and alternative add and subtract the elements of arr[i] from pre[i-1] and store it in pre[i] to make a prefix array." }, { "code": null, "e": 9718, "s": 9515, "text": "Now, Iterate through each query from 1 to Q, and find the result on the basis of the below cases: Case 1: If L is zero then result is pre[R].Case 2: If L is non-zero, find the result using the equation:" }, { "code": null, "e": 9762, "s": 9718, "text": "Case 1: If L is zero then result is pre[R]." }, { "code": null, "e": 9824, "s": 9762, "text": "Case 2: If L is non-zero, find the result using the equation:" }, { "code": null, "e": 9867, "s": 9824, "text": "result = Query(L, R) = pre[R] – pre[L - 1]" }, { "code": null, "e": 9912, "s": 9867, "text": "If L is odd multiply the above result by -1." }, { "code": null, "e": 9963, "s": 9912, "text": "Below is the implementation of the above approach:" }, { "code": null, "e": 9967, "s": 9963, "text": "C++" }, { "code": null, "e": 9972, "s": 9967, "text": "Java" }, { "code": null, "e": 9980, "s": 9972, "text": "Python3" }, { "code": null, "e": 9983, "s": 9980, "text": "C#" }, { "code": null, "e": 9994, "s": 9983, "text": "Javascript" }, { "code": "// C++ program for the above approach#include <bits/stdc++.h>using namespace std; // Structure to represent a querystruct Query { int L, R;}; // This function fills the Prefix Arrayvoid fillPrefixArray(int arr[], int n, int prefixArray[]){ // Initialise the prefix array prefixArray[0] = arr[0]; // Iterate all the element of arr[] // and update the prefix array for (int i = 1; i < n; i++) { // If n is even then, add the // previous value of prefix array // with the current value of arr if (i % 2 == 0) { prefixArray[i] = prefixArray[i - 1] + arr[i]; } // if n is odd, then subtract // the previous value of prefix // Array from current value else { prefixArray[i] = prefixArray[i - 1] - arr[i]; } }} // Function to find the result of// alternatively adding and subtracting// elements in the range [L< R]int findResultUtil(int prefixArray[], int L, int R){ int result; // Case 1 : when L is zero if (L == 0) { result = prefixArray[R]; } // Case 2 : When L is non zero else { result = prefixArray[R] - prefixArray[L - 1]; } // If L is odd means range starts from // odd position multiply result by -1 if (L & 1) { result = result * (-1); } // Return the final result return result;} // Function to find the sum of all// alternative add and subtract// between ranges [L, R]void findResult(int arr[], int n, Query q[], int m){ // Declare prefix array int prefixArray[n]; // Function Call to fill prefix arr[] fillPrefixArray(arr, n, prefixArray); // Iterate for each query for (int i = 0; i < m; i++) { cout << findResultUtil(prefixArray, q[i].L, q[i].R) << \" \"; }} // Driver Codeint main(){ // Given array int arr[] = { 10, 13, 15, 2, 45, 31, 22, 3, 27 }; int n = sizeof(arr) / sizeof(arr[0]); // Given Queries Query q[] = { { 2, 5 }, { 6, 8 }, { 1, 7 }, { 4, 8 }, { 0, 5 } }; int m = sizeof(q) / sizeof(q[0]); // Function Call findResult(arr, n, q, m); return 0;}", "e": 12339, "s": 9994, "text": null }, { "code": "// Java program for the above approachimport java.util.*;class GFG{ // Structure to represent a querystatic class Query{ int L, R; public Query(int l, int r) { super(); L = l; R = r; }}; // This function fills the Prefix Arraystatic void fillPrefixArray(int arr[], int n, int prefixArray[]){ // Initialise the prefix array prefixArray[0] = arr[0]; // Iterate all the element of arr[] // and update the prefix array for (int i = 1; i < n; i++) { // If n is even then, add the // previous value of prefix array // with the current value of arr if (i % 2 == 0) { prefixArray[i] = prefixArray[i - 1] + arr[i]; } // if n is odd, then subtract // the previous value of prefix // Array from current value else { prefixArray[i] = prefixArray[i - 1] - arr[i]; } }} // Function to find the result of// alternatively adding and subtracting// elements in the range [L< R]static int findResultUtil(int prefixArray[], int L, int R){ int result; // Case 1 : when L is zero if (L == 0) { result = prefixArray[R]; } // Case 2 : When L is non zero else { result = prefixArray[R] - prefixArray[L - 1]; } // If L is odd means range starts from // odd position multiply result by -1 if (L % 2 == 1) { result = result * (-1); } // Return the final result return result;} // Function to find the sum of all// alternative add and subtract// between ranges [L, R]static void findResult(int arr[], int n, Query q[], int m){ // Declare prefix array int []prefixArray = new int[n]; // Function Call to fill prefix arr[] fillPrefixArray(arr, n, prefixArray); // Iterate for each query for (int i = 0; i < m; i++) { System.out.print(findResultUtil( prefixArray, q[i].L, q[i].R) + \" \"); }} // Driver Codepublic static void main(String[] args){ // Given array int arr[] = { 10, 13, 15, 2, 45, 31, 22, 3, 27 }; int n = arr.length; // Given Queries Query q[] = {new Query( 2, 5 ), new Query( 6, 8 ), new Query( 1, 7 ), new Query( 4, 8 ), new Query( 0, 5 )}; int m = q.length; // Function Call findResult(arr, n, q, m);}} // This code is contributed by PrinciRaj1992", "e": 14961, "s": 12339, "text": null }, { "code": "# Python program for the above approach # Structure to represent a queryclass Query: def __init__(self,l,r): self.L = l self.R = r # This function fills the Prefix Arraydef fillPrefixArray(arr, n, prefixArray): # Initialise the prefix array prefixArray[0] = arr[0] # Iterate all the element of arr[] # and update the prefix array for i in range(1,n): # If n is even then, add the # previous value of prefix array # with the current value of arr if (i % 2 == 0): prefixArray[i] = prefixArray[i - 1] + arr[i] # if n is odd, then subtract # the previous value of prefix # Array from current value else: prefixArray[i] = prefixArray[i - 1] - arr[i] # Function to find the result of# alternatively adding and subtracting# elements in the range [L< R]def findResultUtil(prefixArray, L, R): # Case 1 : when L is zero if (L == 0): result = prefixArray[R] # Case 2 : When L is non zero else: result = prefixArray[R] - prefixArray[L - 1] # If L is odd means range starts from # odd position multiply result by -1 if (L % 2 == 1): result = result * (-1) # Return the final result return result # Function to find the sum of all# alternative add and subtract# between ranges [L, R]def findResult(arr, n, q, m): # Declare prefix array prefixArray = [0 for i in range(n)] # Function Call to fill prefix arr[] fillPrefixArray(arr, n, prefixArray) # Iterate for each query for i in range(m): print(findResultUtil(prefixArray, q[i].L,q[i].R),end = \" \") # Driver Code # Given arrayarr = [ 10, 13, 15, 2, 45, 31, 22, 3, 27 ]n = len(arr) # Given Queriesq = [ Query(2, 5), Query(6, 8), Query(1, 7), Query(4, 8), Query(0, 5)]m = len(q) # Function CallfindResult(arr, n, q, m) # This code is contributed by shinjanpatra", "e": 16872, "s": 14961, "text": null }, { "code": "// C# program for the above approachusing System;class GFG{ // Structure to represent a queryclass Query{ public int L, R; public Query(int l, int r) { L = l; R = r; }}; // This function fills the Prefix Arraystatic void fillPrefixArray(int []arr, int n, int []prefixArray){ // Initialise the prefix array prefixArray[0] = arr[0]; // Iterate all the element of []arr // and update the prefix array for (int i = 1; i < n; i++) { // If n is even then, add the // previous value of prefix array // with the current value of arr if (i % 2 == 0) { prefixArray[i] = prefixArray[i - 1] + arr[i]; } // if n is odd, then subtract // the previous value of prefix // Array from current value else { prefixArray[i] = prefixArray[i - 1] - arr[i]; } }} // Function to find the result of// alternatively adding and subtracting// elements in the range [L< R]static int findResultUtil(int []prefixArray, int L, int R){ int result; // Case 1 : when L is zero if (L == 0) { result = prefixArray[R]; } // Case 2 : When L is non zero else { result = prefixArray[R] - prefixArray[L - 1]; } // If L is odd means range starts from // odd position multiply result by -1 if (L % 2 == 1) { result = result * (-1); } // Return the readonly result return result;} // Function to find the sum of all// alternative add and subtract// between ranges [L, R]static void findResult(int []arr, int n, Query []q, int m){ // Declare prefix array int []prefixArray = new int[n]; // Function Call to fill prefix []arr fillPrefixArray(arr, n, prefixArray); // Iterate for each query for (int i = 0; i < m; i++) { Console.Write(findResultUtil( prefixArray, q[i].L, q[i].R) + \" \"); }} // Driver Codepublic static void Main(String[] args){ // Given array int []arr = { 10, 13, 15, 2, 45, 31, 22, 3, 27 }; int n = arr.Length; // Given Queries Query []q = {new Query( 2, 5 ), new Query( 6, 8 ), new Query( 1, 7 ), new Query( 4, 8 ), new Query( 0, 5 )}; int m = q.Length; // Function Call findResult(arr, n, q, m);}} // This code is contributed by Rohit_ranjan", "e": 19461, "s": 16872, "text": null }, { "code": "<script> // Javascript program for the above approach // Structure to represent a queryclass Query{ constructor(l, r) { this.L = l; this.R = r; }} // This function fills the Prefix Arrayfunction fillPrefixArray(arr, n, prefixArray){ // Initialise the prefix array prefixArray[0] = arr[0]; // Iterate all the element of arr[] // and update the prefix array for(let i = 1; i < n; i++) { // If n is even then, add the // previous value of prefix array // with the current value of arr if (i % 2 == 0) { prefixArray[i] = prefixArray[i - 1] + arr[i]; } // if n is odd, then subtract // the previous value of prefix // Array from current value else { prefixArray[i] = prefixArray[i - 1] - arr[i]; } }} // Function to find the result of// alternatively adding and subtracting// elements in the range [L< R]function findResultUtil(prefixArray, L, R){ let result; // Case 1 : when L is zero if (L == 0) { result = prefixArray[R]; } // Case 2 : When L is non zero else { result = prefixArray[R] - prefixArray[L - 1]; } // If L is odd means range starts from // odd position multiply result by -1 if (L % 2 == 1) { result = result * (-1); } // Return the final result return result;} // Function to find the sum of all// alternative add and subtract// between ranges [L, R]function findResult(arr, n, q, m){ // Declare prefix array let prefixArray = new Array(n); // Function Call to fill prefix arr[] fillPrefixArray(arr, n, prefixArray); // Iterate for each query for(let i = 0; i < m; i++) { document.write(findResultUtil( prefixArray, q[i].L, q[i].R) + \" \"); }} // Driver Code // Given arraylet arr = [ 10, 13, 15, 2, 45, 31, 22, 3, 27 ];let n = arr.length; // Given Querieslet q = [ new Query(2, 5), new Query(6, 8), new Query(1, 7), new Query(4, 8), new Query(0, 5)];let m = q.length; // Function CallfindResult(arr, n, q, m); // This code is contributed by unknown2108 </script>", "e": 21804, "s": 19461, "text": null }, { "code": null, "e": 21814, "s": 21804, "text": "Output: " }, { "code": null, "e": 21830, "s": 21814, "text": "27 46 -33 60 24" }, { "code": null, "e": 21878, "s": 21830, "text": "Time Complexity:O(N + Q) Auxiliary Space: O(N) " }, { "code": null, "e": 21893, "s": 21878, "text": "mohit kumar 29" }, { "code": null, "e": 21906, "s": 21893, "text": "princi singh" }, { "code": null, "e": 21920, "s": 21906, "text": "GauravRajput1" }, { "code": null, "e": 21934, "s": 21920, "text": "princiraj1992" }, { "code": null, "e": 21947, "s": 21934, "text": "Rohit_ranjan" }, { "code": null, "e": 21956, "s": 21947, "text": "famously" }, { "code": null, "e": 21968, "s": 21956, "text": "unknown2108" }, { "code": null, "e": 21981, "s": 21968, "text": "shinjanpatra" }, { "code": null, "e": 22001, "s": 21981, "text": "array-range-queries" }, { "code": null, "e": 22012, "s": 22001, "text": "Algorithms" }, { "code": null, "e": 22019, "s": 22012, "text": "Arrays" }, { "code": null, "e": 22039, "s": 22019, "text": "Dynamic Programming" }, { "code": null, "e": 22046, "s": 22039, "text": "Arrays" }, { "code": null, "e": 22066, "s": 22046, "text": "Dynamic Programming" }, { "code": null, "e": 22077, "s": 22066, "text": "Algorithms" } ]
jQuery UI Dialog position Option
22 Mar, 2021 jQuery UI consists of GUI widgets, visual effects, and themes implemented using HTML, CSS, and jQuery. jQuery UI is great for building UI interfaces for the webpages. The jQuery UI Dialog position Option is used to set the position of dialog box. Syntax: $( ".selector" ).dialog({ position: { my: "left top", at: "left bottom", of: button } }); CDN Link: First, add jQuery UI scripts needed for your project. <link rel=”stylesheet” href=”https://code.jquery.com/ui/1.10.4/themes/ui-lightness/jquery-ui.css”><script src=”https://code.jquery.com/jquery-1.10.2.js”></script><script src=”https://code.jquery.com/ui/1.10.4/jquery-ui.js”></script> Example: HTML <!doctype html><html lang="en"> <head> <meta charset="utf-8"> <link href= "https://code.jquery.com/ui/1.10.4/themes/ui-lightness/jquery-ui.css" rel="stylesheet"> <script src="https://code.jquery.com/jquery-1.10.2.js"></script> <script src="https://code.jquery.com/ui/1.10.4/jquery-ui.js"></script> <script> $(function () { $("#gfg").dialog({ autoOpen: false, position: { at: "center" } }); $("#geeks").click(function () { $("#gfg").dialog("open"); }); }); </script></head> <body style="text-align: center;"> <h1 style="color:green;">GeeksforGeeks</h1> <h3>jQuery UI Dialog position Option</h3> <button id="geeks">Open Dialog</button> <div id="gfg" title="GeeksforGeeks"> Welcome to GeeksforGeeks </div></body> </html> Output: Reference: https://api.jqueryui.com/dialog/#option-position HTML-Tags jQuery-Methods jQuery-UI JQuery Web Technologies Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. How to get the value in an input text box using jQuery ? How to prevent Body from scrolling when a modal is opened using jQuery ? jQuery | ajax() Method jQuery | removeAttr() with Examples jQuery | parent() & parents() with Examples Top 10 Projects For Beginners To Practice HTML and CSS Skills Installation of Node.js on Linux Difference between var, let and const keywords in JavaScript How to insert spaces/tabs in text using HTML/CSS? How to fetch data from an API in ReactJS ?
[ { "code": null, "e": 28, "s": 0, "text": "\n22 Mar, 2021" }, { "code": null, "e": 275, "s": 28, "text": "jQuery UI consists of GUI widgets, visual effects, and themes implemented using HTML, CSS, and jQuery. jQuery UI is great for building UI interfaces for the webpages. The jQuery UI Dialog position Option is used to set the position of dialog box." }, { "code": null, "e": 283, "s": 275, "text": "Syntax:" }, { "code": null, "e": 393, "s": 283, "text": "$( \".selector\" ).dialog({\n position: { \n my: \"left top\", \n at: \"left bottom\", \n of: button \n }\n});" }, { "code": null, "e": 457, "s": 393, "text": "CDN Link: First, add jQuery UI scripts needed for your project." }, { "code": null, "e": 690, "s": 457, "text": "<link rel=”stylesheet” href=”https://code.jquery.com/ui/1.10.4/themes/ui-lightness/jquery-ui.css”><script src=”https://code.jquery.com/jquery-1.10.2.js”></script><script src=”https://code.jquery.com/ui/1.10.4/jquery-ui.js”></script>" }, { "code": null, "e": 699, "s": 690, "text": "Example:" }, { "code": null, "e": 704, "s": 699, "text": "HTML" }, { "code": "<!doctype html><html lang=\"en\"> <head> <meta charset=\"utf-8\"> <link href= \"https://code.jquery.com/ui/1.10.4/themes/ui-lightness/jquery-ui.css\" rel=\"stylesheet\"> <script src=\"https://code.jquery.com/jquery-1.10.2.js\"></script> <script src=\"https://code.jquery.com/ui/1.10.4/jquery-ui.js\"></script> <script> $(function () { $(\"#gfg\").dialog({ autoOpen: false, position: { at: \"center\" } }); $(\"#geeks\").click(function () { $(\"#gfg\").dialog(\"open\"); }); }); </script></head> <body style=\"text-align: center;\"> <h1 style=\"color:green;\">GeeksforGeeks</h1> <h3>jQuery UI Dialog position Option</h3> <button id=\"geeks\">Open Dialog</button> <div id=\"gfg\" title=\"GeeksforGeeks\"> Welcome to GeeksforGeeks </div></body> </html>", "e": 1618, "s": 704, "text": null }, { "code": null, "e": 1626, "s": 1618, "text": "Output:" }, { "code": null, "e": 1686, "s": 1626, "text": "Reference: https://api.jqueryui.com/dialog/#option-position" }, { "code": null, "e": 1696, "s": 1686, "text": "HTML-Tags" }, { "code": null, "e": 1711, "s": 1696, "text": "jQuery-Methods" }, { "code": null, "e": 1721, "s": 1711, "text": "jQuery-UI" }, { "code": null, "e": 1728, "s": 1721, "text": "JQuery" }, { "code": null, "e": 1745, "s": 1728, "text": "Web Technologies" }, { "code": null, "e": 1843, "s": 1745, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 1900, "s": 1843, "text": "How to get the value in an input text box using jQuery ?" }, { "code": null, "e": 1973, "s": 1900, "text": "How to prevent Body from scrolling when a modal is opened using jQuery ?" }, { "code": null, "e": 1996, "s": 1973, "text": "jQuery | ajax() Method" }, { "code": null, "e": 2032, "s": 1996, "text": "jQuery | removeAttr() with Examples" }, { "code": null, "e": 2076, "s": 2032, "text": "jQuery | parent() & parents() with Examples" }, { "code": null, "e": 2138, "s": 2076, "text": "Top 10 Projects For Beginners To Practice HTML and CSS Skills" }, { "code": null, "e": 2171, "s": 2138, "text": "Installation of Node.js on Linux" }, { "code": null, "e": 2232, "s": 2171, "text": "Difference between var, let and const keywords in JavaScript" }, { "code": null, "e": 2282, "s": 2232, "text": "How to insert spaces/tabs in text using HTML/CSS?" } ]
Exception Propagation in Java
07 Feb, 2018 Prerequisite : Exceptions in Java, Checked vs Unchecked Exceptions Exception propagation : An exception is first thrown from the top of the stack and if it is not caught, it drops down the call stack to the previous method.After a method throws an exception, the runtime system attempts to find something to handle it. The set of possible “somethings” to handle the exception is the ordered list of methods that had been called to get to the method where the error occurred. The list of methods is known as the call stack and the method of searching is Exception Propagation. Exception Propagation in Unchecked Exceptions when an exception happens, Propagation is a process in which the exception is being dropped from to the top to the bottom of the stack. If not caught once, the exception again drops down to the previous method and so on until it gets caught or until it reach the very bottom of the call stack. This is called exception propagation and this happens in case of Unchecked Exceptions. In the example below, exception occurs in m() method where it is not handled, so it is propagated to previous n() method where it is not handled, again it is propagated to p() method where exception is handled.Exception can be handled in any method in call stack either in main() method, p() method, n() method or m() method. Note : By default, Unchecked Exceptions are forwarded in calling chain (propagated). // Java program to illustrate// unchecked exception propagation// without using throws keywordclass Simple { void m() { int data = 50 / 0; // unchecked exception occurred // exception propagated to n() } void n() { m(); // exception propagated to p() } void p() { try { n(); // exception handled } catch (Exception e) { System.out.println("Exception handled"); } } public static void main(String args[]) { Simple obj = new Simple(); obj.p(); System.out.println("Normal flow..."); }} Output: Exception handled Normal flow... Exception Propagation in Checked Exceptions Unlike Unchecked Exceptions, the propagation of exception does not happen in case of Checked Exception and its mandatory to use throw keyword here. Only unchecked exceptions are propagated. Checked exceptions throw compilation error. In example below, If we omit the throws keyword from the m() and n() functions, the compiler will generate compile time error. Because unlike in the case of unchecked exceptions, the checked exceptions cannot propagate without using throws keyword. Note : By default, Checked Exceptions are not forwarded in calling chain (propagated). // Java program to illustrate exception propagation// in checked exceptions and it can be propagated// by throws keyword ONLYimport java.io.IOException;class Simple { // exception propagated to n() void m() throws IOException { // checked exception occurred throw new IOException("device error"); } // exception propagated to p() void n() throws IOException { m(); } void p() { try { // exception handled n(); } catch (Exception e) { System.out.println("exception handled"); } } public static void main(String args[]) { Simple obj = new Simple(); obj.p(); System.out.println("normal flow..."); }} Output: exception handled normal flow... Java-Exception Handling Java-Exceptions Java Java Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Stream In Java Introduction to Java Constructors in Java Exceptions in Java Generics in Java Functional Interfaces in Java Java Programming Examples Strings in Java Differences between JDK, JRE and JVM Abstraction in Java
[ { "code": null, "e": 54, "s": 26, "text": "\n07 Feb, 2018" }, { "code": null, "e": 121, "s": 54, "text": "Prerequisite : Exceptions in Java, Checked vs Unchecked Exceptions" }, { "code": null, "e": 630, "s": 121, "text": "Exception propagation : An exception is first thrown from the top of the stack and if it is not caught, it drops down the call stack to the previous method.After a method throws an exception, the runtime system attempts to find something to handle it. The set of possible “somethings” to handle the exception is the ordered list of methods that had been called to get to the method where the error occurred. The list of methods is known as the call stack and the method of searching is Exception Propagation." }, { "code": null, "e": 676, "s": 630, "text": "Exception Propagation in Unchecked Exceptions" }, { "code": null, "e": 1057, "s": 676, "text": "when an exception happens, Propagation is a process in which the exception is being dropped from to the top to the bottom of the stack. If not caught once, the exception again drops down to the previous method and so on until it gets caught or until it reach the very bottom of the call stack. This is called exception propagation and this happens in case of Unchecked Exceptions." }, { "code": null, "e": 1383, "s": 1057, "text": "In the example below, exception occurs in m() method where it is not handled, so it is propagated to previous n() method where it is not handled, again it is propagated to p() method where exception is handled.Exception can be handled in any method in call stack either in main() method, p() method, n() method or m() method." }, { "code": null, "e": 1468, "s": 1383, "text": "Note : By default, Unchecked Exceptions are forwarded in calling chain (propagated)." }, { "code": "// Java program to illustrate// unchecked exception propagation// without using throws keywordclass Simple { void m() { int data = 50 / 0; // unchecked exception occurred // exception propagated to n() } void n() { m(); // exception propagated to p() } void p() { try { n(); // exception handled } catch (Exception e) { System.out.println(\"Exception handled\"); } } public static void main(String args[]) { Simple obj = new Simple(); obj.p(); System.out.println(\"Normal flow...\"); }}", "e": 2092, "s": 1468, "text": null }, { "code": null, "e": 2100, "s": 2092, "text": "Output:" }, { "code": null, "e": 2135, "s": 2100, "text": "Exception handled \nNormal flow...\n" }, { "code": null, "e": 2179, "s": 2135, "text": "Exception Propagation in Checked Exceptions" }, { "code": null, "e": 2413, "s": 2179, "text": "Unlike Unchecked Exceptions, the propagation of exception does not happen in case of Checked Exception and its mandatory to use throw keyword here. Only unchecked exceptions are propagated. Checked exceptions throw compilation error." }, { "code": null, "e": 2662, "s": 2413, "text": "In example below, If we omit the throws keyword from the m() and n() functions, the compiler will generate compile time error. Because unlike in the case of unchecked exceptions, the checked exceptions cannot propagate without using throws keyword." }, { "code": null, "e": 2749, "s": 2662, "text": "Note : By default, Checked Exceptions are not forwarded in calling chain (propagated)." }, { "code": "// Java program to illustrate exception propagation// in checked exceptions and it can be propagated// by throws keyword ONLYimport java.io.IOException;class Simple { // exception propagated to n() void m() throws IOException { // checked exception occurred throw new IOException(\"device error\"); } // exception propagated to p() void n() throws IOException { m(); } void p() { try { // exception handled n(); } catch (Exception e) { System.out.println(\"exception handled\"); } } public static void main(String args[]) { Simple obj = new Simple(); obj.p(); System.out.println(\"normal flow...\"); }}", "e": 3500, "s": 2749, "text": null }, { "code": null, "e": 3508, "s": 3500, "text": "Output:" }, { "code": null, "e": 3543, "s": 3508, "text": "exception handled \nnormal flow...\n" }, { "code": null, "e": 3567, "s": 3543, "text": "Java-Exception Handling" }, { "code": null, "e": 3583, "s": 3567, "text": "Java-Exceptions" }, { "code": null, "e": 3588, "s": 3583, "text": "Java" }, { "code": null, "e": 3593, "s": 3588, "text": "Java" }, { "code": null, "e": 3691, "s": 3593, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 3706, "s": 3691, "text": "Stream In Java" }, { "code": null, "e": 3727, "s": 3706, "text": "Introduction to Java" }, { "code": null, "e": 3748, "s": 3727, "text": "Constructors in Java" }, { "code": null, "e": 3767, "s": 3748, "text": "Exceptions in Java" }, { "code": null, "e": 3784, "s": 3767, "text": "Generics in Java" }, { "code": null, "e": 3814, "s": 3784, "text": "Functional Interfaces in Java" }, { "code": null, "e": 3840, "s": 3814, "text": "Java Programming Examples" }, { "code": null, "e": 3856, "s": 3840, "text": "Strings in Java" }, { "code": null, "e": 3893, "s": 3856, "text": "Differences between JDK, JRE and JVM" } ]
Node.js Basics
13 Oct, 2021 Node.js is a cross-platform JavaScript runtime environment. It allows the creation of scalable Web servers without threading and networking tools using JavaScript and a collection of “modules” that handle various core functionalities. It can make console-based and web-based node.js applications. Datatypes: Node.js contains various types of data types similar to JavaScript. Boolean Undefined Null String Number Loose Typing: Node.js supports loose typing, it means you don’t need to specify what type of information will be stored in a variable in advance. We use var keyword in Node.js to declare any type of variable. Examples are given below: Example: // Variable store number data typevar a = 35;console.log(typeof a); // Variable store string data typea = "GeeksforGeeks";console.log(typeof a); // Variable store Boolean data typea = true;console.log(typeof a); // Variable store undefined (no value) data typea = undefined;console.log(typeof a); Output: number string boolean undefined Objects & Functions: Node.js objects are same as JavaScript objects i.e. the objects are similar to variable and it contains many values which are written as name : value pairs. Name and value are separated by colon and every pair is separated by comma. Example: var company = { Name: "GeeksforGeeks", Address: "Noida", Contact: "+919876543210", Email: "abc@geeksforgeeks.org"}; // Display the object informationconsole.log("Information of variable company:", company); // Display the type of variableconsole.log("Type of variable company:", typeof company); Output: Information of variable company: { Name: 'GeeksforGeeks', Address: 'Noida', Contact: '+919876543210', Email: 'abc@geeksforgeeks.org' } Type of variable company: object Functions: Node.js functions are defined using function keyword then the name of the function and parameters which are passed in the function. In Node.js, we don’t have to specify datatypes for the parameters and check the number of arguments received. Node.js functions follow every rule which is there while writing JavaScript functions. Example: function multiply(num1, num2) { // It returns the multiplication // of num1 and num2 return num1 * num2;} // Declare variablevar x = 2;var y = 3; // Display the answer returned by// multiply functionconsole.log("Multiplication of", x, "and", y, "is", multiply(x, y)); Output: Multiplication of 2 and 3 is 6 If you observe in the above example, we have created a function called “multiply” with parameters same like JavaScript. String and String Functions: In Node.js we can make a variable as string by assigning a value either by using single (”) or double (“”) quotes and it contains many functions to manipulate to strings.Following is the example of defining string variables and functions in node.js. Example: var x = "Welcome to GeeksforGeeks "; var y = 'Node.js Tutorials'; var z = ['Geeks', 'for', 'Geeks']; console.log(x); console.log(y); console.log("Concat Using (+) :", (x + y)); console.log("Concat Using Function :", (x.concat(y))); console.log("Split string: ", x.split(' ')); console.log("Join string: ", z.join(', ')); console.log("Char At Index 5: ", x.charAt(5) ); Output: Welcome to GeeksforGeeks Node.js Tutorials Concat Using (+) : Welcome to GeeksforGeeks Node.js Tutorials Concat Using Function : Welcome to GeeksforGeeks Node.js Tutorials Split string: [ 'Welcome', 'to', 'GeeksforGeeks', '' ] Join string: Geeks, for, Geeks Char At Index 5: m Buffer: In node.js, we have a data type called “Buffer” to store a binary data and it is useful when we are reading a data from files or receiving a packets over network. Node.js console-based application: Make a file called console.js with the following code. console.log('Hello this is the console-based application'); console.log('This all will be printed in console'); // The above two lines will be printed in the console. To run this file, open node.js command prompt and go to the folder where console.js file exist and write the following command. It will display content on console. The console.log() method of console class prints the message passed in the method in the console. Node.js web-based application: Node.js web application contains different types of modules which is imported using require() directive and we have to create a server and write code for the read request and return response.Make a file web.js with the following code. // Require http modulevar http = require("http"); // Create serverhttp.createServer(function (req, res) { // Send the HTTP header // HTTP Status: 200 : OK // Content Type: text/plain res.writeHead(200, {'Content-Type': 'text/plain'}); // Send the response body as "This is the example // of node.js web based application" res.end('This is the example of node.js web-based application \n'); // Console will display the message }).listen(5000, ()=>console.log('Server running at http://127.0.0.1:5000/')); To run this file follow the steps as given below: Search the node.js command prompt in the search bar and open the node.js command prompt. Go to the folder using cd command in command prompt and write the following command node web.js Now the server has started and go to the browser and open this url localhost:5000 You will see the response which you have sent back from web.js in the browser. If any changes are made in the web.js file then again run the command node web.js and refresh the tab in the browser. Node.js-Basics Picked Node.js Web Technologies 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 ? Node.js fs.readFileSync() Method Node.js fs.writeFile() Method How to update NPM ? Difference between promise and async await in Node.js Top 10 Projects For Beginners To Practice HTML and CSS Skills Difference between var, let and const keywords in JavaScript How to insert spaces/tabs in text using HTML/CSS? How to fetch data from an API in ReactJS ? Differences between Functional Components and Class Components in React
[ { "code": null, "e": 54, "s": 26, "text": "\n13 Oct, 2021" }, { "code": null, "e": 351, "s": 54, "text": "Node.js is a cross-platform JavaScript runtime environment. It allows the creation of scalable Web servers without threading and networking tools using JavaScript and a collection of “modules” that handle various core functionalities. It can make console-based and web-based node.js applications." }, { "code": null, "e": 430, "s": 351, "text": "Datatypes: Node.js contains various types of data types similar to JavaScript." }, { "code": null, "e": 438, "s": 430, "text": "Boolean" }, { "code": null, "e": 448, "s": 438, "text": "Undefined" }, { "code": null, "e": 453, "s": 448, "text": "Null" }, { "code": null, "e": 460, "s": 453, "text": "String" }, { "code": null, "e": 467, "s": 460, "text": "Number" }, { "code": null, "e": 702, "s": 467, "text": "Loose Typing: Node.js supports loose typing, it means you don’t need to specify what type of information will be stored in a variable in advance. We use var keyword in Node.js to declare any type of variable. Examples are given below:" }, { "code": null, "e": 711, "s": 702, "text": "Example:" }, { "code": "// Variable store number data typevar a = 35;console.log(typeof a); // Variable store string data typea = \"GeeksforGeeks\";console.log(typeof a); // Variable store Boolean data typea = true;console.log(typeof a); // Variable store undefined (no value) data typea = undefined;console.log(typeof a);", "e": 1014, "s": 711, "text": null }, { "code": null, "e": 1022, "s": 1014, "text": "Output:" }, { "code": null, "e": 1054, "s": 1022, "text": "number\nstring\nboolean\nundefined" }, { "code": null, "e": 1308, "s": 1054, "text": "Objects & Functions: Node.js objects are same as JavaScript objects i.e. the objects are similar to variable and it contains many values which are written as name : value pairs. Name and value are separated by colon and every pair is separated by comma." }, { "code": null, "e": 1317, "s": 1308, "text": "Example:" }, { "code": "var company = { Name: \"GeeksforGeeks\", Address: \"Noida\", Contact: \"+919876543210\", Email: \"abc@geeksforgeeks.org\"}; // Display the object informationconsole.log(\"Information of variable company:\", company); // Display the type of variableconsole.log(\"Type of variable company:\", typeof company);", "e": 1634, "s": 1317, "text": null }, { "code": null, "e": 1642, "s": 1634, "text": "Output:" }, { "code": null, "e": 1818, "s": 1642, "text": "Information of variable company: {\n Name: 'GeeksforGeeks',\n Address: 'Noida',\n Contact: '+919876543210',\n Email: 'abc@geeksforgeeks.org'\n}\nType of variable company: object" }, { "code": null, "e": 2158, "s": 1818, "text": "Functions: Node.js functions are defined using function keyword then the name of the function and parameters which are passed in the function. In Node.js, we don’t have to specify datatypes for the parameters and check the number of arguments received. Node.js functions follow every rule which is there while writing JavaScript functions." }, { "code": null, "e": 2167, "s": 2158, "text": "Example:" }, { "code": "function multiply(num1, num2) { // It returns the multiplication // of num1 and num2 return num1 * num2;} // Declare variablevar x = 2;var y = 3; // Display the answer returned by// multiply functionconsole.log(\"Multiplication of\", x, \"and\", y, \"is\", multiply(x, y));", "e": 2457, "s": 2167, "text": null }, { "code": null, "e": 2465, "s": 2457, "text": "Output:" }, { "code": null, "e": 2496, "s": 2465, "text": "Multiplication of 2 and 3 is 6" }, { "code": null, "e": 2616, "s": 2496, "text": "If you observe in the above example, we have created a function called “multiply” with parameters same like JavaScript." }, { "code": null, "e": 2895, "s": 2616, "text": "String and String Functions: In Node.js we can make a variable as string by assigning a value either by using single (”) or double (“”) quotes and it contains many functions to manipulate to strings.Following is the example of defining string variables and functions in node.js." }, { "code": null, "e": 2904, "s": 2895, "text": "Example:" }, { "code": "var x = \"Welcome to GeeksforGeeks \"; var y = 'Node.js Tutorials'; var z = ['Geeks', 'for', 'Geeks']; console.log(x); console.log(y); console.log(\"Concat Using (+) :\", (x + y)); console.log(\"Concat Using Function :\", (x.concat(y))); console.log(\"Split string: \", x.split(' ')); console.log(\"Join string: \", z.join(', ')); console.log(\"Char At Index 5: \", x.charAt(5) );", "e": 3291, "s": 2904, "text": null }, { "code": null, "e": 3299, "s": 3291, "text": "Output:" }, { "code": null, "e": 3579, "s": 3299, "text": "Welcome to GeeksforGeeks\nNode.js Tutorials\nConcat Using (+) : Welcome to GeeksforGeeks Node.js Tutorials\nConcat Using Function : Welcome to GeeksforGeeks Node.js Tutorials\nSplit string: [ 'Welcome', 'to', 'GeeksforGeeks', '' ]\nJoin string: Geeks, for, Geeks\nChar At Index 5: m" }, { "code": null, "e": 3750, "s": 3579, "text": "Buffer: In node.js, we have a data type called “Buffer” to store a binary data and it is useful when we are reading a data from files or receiving a packets over network." }, { "code": null, "e": 3840, "s": 3750, "text": "Node.js console-based application: Make a file called console.js with the following code." }, { "code": "console.log('Hello this is the console-based application'); console.log('This all will be printed in console'); // The above two lines will be printed in the console.", "e": 4009, "s": 3840, "text": null }, { "code": null, "e": 4173, "s": 4009, "text": "To run this file, open node.js command prompt and go to the folder where console.js file exist and write the following command. It will display content on console." }, { "code": null, "e": 4271, "s": 4173, "text": "The console.log() method of console class prints the message passed in the method in the console." }, { "code": null, "e": 4537, "s": 4271, "text": "Node.js web-based application: Node.js web application contains different types of modules which is imported using require() directive and we have to create a server and write code for the read request and return response.Make a file web.js with the following code." }, { "code": "// Require http modulevar http = require(\"http\"); // Create serverhttp.createServer(function (req, res) { // Send the HTTP header // HTTP Status: 200 : OK // Content Type: text/plain res.writeHead(200, {'Content-Type': 'text/plain'}); // Send the response body as \"This is the example // of node.js web based application\" res.end('This is the example of node.js web-based application \\n'); // Console will display the message }).listen(5000, ()=>console.log('Server running at http://127.0.0.1:5000/'));", "e": 5093, "s": 4537, "text": null }, { "code": null, "e": 5143, "s": 5093, "text": "To run this file follow the steps as given below:" }, { "code": null, "e": 5232, "s": 5143, "text": "Search the node.js command prompt in the search bar and open the node.js command prompt." }, { "code": null, "e": 5328, "s": 5232, "text": "Go to the folder using cd command in command prompt and write the following command node web.js" }, { "code": null, "e": 5410, "s": 5328, "text": "Now the server has started and go to the browser and open this url localhost:5000" }, { "code": null, "e": 5607, "s": 5410, "text": "You will see the response which you have sent back from web.js in the browser. If any changes are made in the web.js file then again run the command node web.js and refresh the tab in the browser." }, { "code": null, "e": 5622, "s": 5607, "text": "Node.js-Basics" }, { "code": null, "e": 5629, "s": 5622, "text": "Picked" }, { "code": null, "e": 5637, "s": 5629, "text": "Node.js" }, { "code": null, "e": 5654, "s": 5637, "text": "Web Technologies" }, { "code": null, "e": 5752, "s": 5654, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 5800, "s": 5752, "text": "How to update Node.js and NPM to next version ?" }, { "code": null, "e": 5833, "s": 5800, "text": "Node.js fs.readFileSync() Method" }, { "code": null, "e": 5863, "s": 5833, "text": "Node.js fs.writeFile() Method" }, { "code": null, "e": 5883, "s": 5863, "text": "How to update NPM ?" }, { "code": null, "e": 5937, "s": 5883, "text": "Difference between promise and async await in Node.js" }, { "code": null, "e": 5999, "s": 5937, "text": "Top 10 Projects For Beginners To Practice HTML and CSS Skills" }, { "code": null, "e": 6060, "s": 5999, "text": "Difference between var, let and const keywords in JavaScript" }, { "code": null, "e": 6110, "s": 6060, "text": "How to insert spaces/tabs in text using HTML/CSS?" }, { "code": null, "e": 6153, "s": 6110, "text": "How to fetch data from an API in ReactJS ?" } ]
Sort the Array by reversing the numbers in it
29 Nov, 2021 Given an array arr[] of N non-negative integers, the task is to sort these integers according to their reverse. Examples: Input: arr[] = {12, 10, 102, 31, 15} Output: 10 31 12 15 102 Reversing the numbers: 12 -> 21 10 -> 01 102 -> 201 31 -> 13 15 -> 51 Sorting the reversed numbers: 01 13 21 51 201 Original sorted array: 10 13 12 15 102 Input: arr[] = {12, 10} Output: 10 12 Approach: The idea is to store each element with its reverse in a vector pair and then sort all the elements of the vector according to the reverse stored. Finally, print the elements in order. Below is the implementation of the above approach: C++ Java Python3 C# Javascript // C++ implementation of the approach #include <bits/stdc++.h>using namespace std; // Function to return the// reverse of nint reversDigits(int num){ int rev_num = 0; while (num > 0) { rev_num = rev_num * 10 + num % 10; num = num / 10; } return rev_num;} // Function to sort the array according to// the reverse of elementsvoid sortArr(int arr[], int n){ // Vector to store the reverse // with respective elements vector<pair<int, int> > vp; // Inserting reverse with elements // in the vector pair for (int i = 0; i < n; i++) { vp.push_back( make_pair(reversDigits(arr[i]), arr[i])); } // Sort the vector, this will sort the pair // according to the reverse of elements sort(vp.begin(), vp.end()); // Print the sorted vector content for (int i = 0; i < vp.size(); i++) cout << vp[i].second << " ";} // Driver codeint main(){ int arr[] = { 12, 10, 102, 31, 15 }; int n = sizeof(arr) / sizeof(arr[0]); sortArr(arr, n); return 0;} // Java implementation of the approachimport java.util.*;import java.lang.*;import java.io.*; class GFG{ // Function to return the// reverse of nstatic int reversDigits(int num){ int rev_num = 0; while (num > 0) { rev_num = rev_num * 10 + num % 10; num = num / 10; } return rev_num;} // Function to sort the array according// to the reverse of elementsstatic void sortArr(int arr[], int n){ // Vector to store the reverse // with respective elements ArrayList<int[]> vp = new ArrayList<>(); // Inserting reverse with elements // in the vector pair for(int i = 0; i < n; i++) { vp.add(new int[]{reversDigits(arr[i]), arr[i]}); } // Sort the vector, this will sort the pair // according to the reverse of elements Collections.sort(vp, (a, b) -> a[0] - b[0]); // Print the sorted vector content for(int i = 0; i < vp.size(); i++) System.out.print(vp.get(i)[1] + " ");} // Driver codepublic static void main(String[] args){ int arr[] = { 12, 10, 102, 31, 15 }; int n = arr.length; sortArr(arr, n);}} // This code is contributed by offbeat # Python3 implementation of the approach # Function to return the# reverse of ndef reversDigits(num) : rev_num = 0; while (num > 0) : rev_num = rev_num * 10 + num % 10; num = num // 10; return rev_num; # Function to sort the array according to# the reverse of elementsdef sortArr(arr, n) : # Vector to store the reverse # with respective elements vp = []; # Inserting reverse with elements # in the vector pair for i in range(n) : vp.append((reversDigits(arr[i]),arr[i])); # Sort the vector, this will sort the pair # according to the reverse of elements vp.sort() # Print the sorted vector content for i in range(len(vp)) : print(vp[i][1],end= " "); # Driver codeif __name__ == "__main__" : arr = [ 12, 10, 102, 31, 15 ]; n = len(arr); sortArr(arr, n); # This code is contributed by AnkitRai01 // C# implementation of the approachusing System;using System.Collections.Generic;class GFG{ // Function to return the // reverse of n static int reversDigits(int num) { int rev_num = 0; while (num > 0) { rev_num = rev_num * 10 + num % 10; num = num / 10; } return rev_num; } // Function to sort the array according to // the reverse of elements static void sortArr(int[] arr, int n) { // Vector to store the reverse // with respective elements List<Tuple<int, int>> vp = new List<Tuple<int, int>>(); // Inserting reverse with elements // in the vector pair for (int i = 0; i < n; i++) { vp.Add(new Tuple<int, int>(reversDigits(arr[i]),arr[i])); } // Sort the vector, this will sort the pair // according to the reverse of elements vp.Sort(); // Print the sorted vector content for (int i = 0; i < vp.Count; i++) Console.Write(vp[i].Item2 + " "); } // Driver code static void Main() { int[] arr = { 12, 10, 102, 31, 15 }; int n = arr.Length; sortArr(arr, n); }} // This code is contributed by divyesh072019 <script>// Javascript implementation of the// above approach // Function to return the// reverse of nfunction reversDigits(num){ var rev_num = 0; while (num > 0) { rev_num = rev_num * 10 + num % 10; num = Math.floor(num / 10); } return rev_num;} // Function to sort the array according to// the reverse of elementsfunction sortArr(arr, n){ // Vector to store the reverse // with respective elements var vp = new Array(n); for (var i = 0; i < n; i++) { vp[i] = []; } // Inserting reverse with elements // in the vector pair for (var i = 0; i < n; i++) { var pair = []; pair.push(reversDigits(arr[i])); pair.push(arr[i]); vp[i] = pair; } // Sort the vector, this will sort the pair // according to the reverse of elements vp = vp.sort(function(a,b) { return a[0] - b[0]; }); // Print the sorted vector content for (var i = 0; i < n; i++){ document.write(vp[i][1] + " "); }}// Driver codevar arr = [ 12, 10, 102, 31, 15 ];var n = arr.length; sortArr(arr, n); // This code is contributed by Shivanisingh</script> 10 31 12 15 102 Time Complexity: where N is the size of the array Auxiliary Space: O(N) ankthon offbeat divyesh072019 shivanisinghss2110 anikakapoor subham348 Numbers Arrays Mathematical Sorting Arrays Mathematical Sorting Numbers Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 28, "s": 0, "text": "\n29 Nov, 2021" }, { "code": null, "e": 140, "s": 28, "text": "Given an array arr[] of N non-negative integers, the task is to sort these integers according to their reverse." }, { "code": null, "e": 150, "s": 140, "text": "Examples:" }, { "code": null, "e": 366, "s": 150, "text": "Input: arr[] = {12, 10, 102, 31, 15} Output: 10 31 12 15 102 Reversing the numbers: 12 -> 21 10 -> 01 102 -> 201 31 -> 13 15 -> 51 Sorting the reversed numbers: 01 13 21 51 201 Original sorted array: 10 13 12 15 102" }, { "code": null, "e": 405, "s": 366, "text": "Input: arr[] = {12, 10} Output: 10 12 " }, { "code": null, "e": 599, "s": 405, "text": "Approach: The idea is to store each element with its reverse in a vector pair and then sort all the elements of the vector according to the reverse stored. Finally, print the elements in order." }, { "code": null, "e": 650, "s": 599, "text": "Below is the implementation of the above approach:" }, { "code": null, "e": 654, "s": 650, "text": "C++" }, { "code": null, "e": 659, "s": 654, "text": "Java" }, { "code": null, "e": 667, "s": 659, "text": "Python3" }, { "code": null, "e": 670, "s": 667, "text": "C#" }, { "code": null, "e": 681, "s": 670, "text": "Javascript" }, { "code": "// C++ implementation of the approach #include <bits/stdc++.h>using namespace std; // Function to return the// reverse of nint reversDigits(int num){ int rev_num = 0; while (num > 0) { rev_num = rev_num * 10 + num % 10; num = num / 10; } return rev_num;} // Function to sort the array according to// the reverse of elementsvoid sortArr(int arr[], int n){ // Vector to store the reverse // with respective elements vector<pair<int, int> > vp; // Inserting reverse with elements // in the vector pair for (int i = 0; i < n; i++) { vp.push_back( make_pair(reversDigits(arr[i]), arr[i])); } // Sort the vector, this will sort the pair // according to the reverse of elements sort(vp.begin(), vp.end()); // Print the sorted vector content for (int i = 0; i < vp.size(); i++) cout << vp[i].second << \" \";} // Driver codeint main(){ int arr[] = { 12, 10, 102, 31, 15 }; int n = sizeof(arr) / sizeof(arr[0]); sortArr(arr, n); return 0;}", "e": 1735, "s": 681, "text": null }, { "code": "// Java implementation of the approachimport java.util.*;import java.lang.*;import java.io.*; class GFG{ // Function to return the// reverse of nstatic int reversDigits(int num){ int rev_num = 0; while (num > 0) { rev_num = rev_num * 10 + num % 10; num = num / 10; } return rev_num;} // Function to sort the array according// to the reverse of elementsstatic void sortArr(int arr[], int n){ // Vector to store the reverse // with respective elements ArrayList<int[]> vp = new ArrayList<>(); // Inserting reverse with elements // in the vector pair for(int i = 0; i < n; i++) { vp.add(new int[]{reversDigits(arr[i]), arr[i]}); } // Sort the vector, this will sort the pair // according to the reverse of elements Collections.sort(vp, (a, b) -> a[0] - b[0]); // Print the sorted vector content for(int i = 0; i < vp.size(); i++) System.out.print(vp.get(i)[1] + \" \");} // Driver codepublic static void main(String[] args){ int arr[] = { 12, 10, 102, 31, 15 }; int n = arr.length; sortArr(arr, n);}} // This code is contributed by offbeat", "e": 2924, "s": 1735, "text": null }, { "code": "# Python3 implementation of the approach # Function to return the# reverse of ndef reversDigits(num) : rev_num = 0; while (num > 0) : rev_num = rev_num * 10 + num % 10; num = num // 10; return rev_num; # Function to sort the array according to# the reverse of elementsdef sortArr(arr, n) : # Vector to store the reverse # with respective elements vp = []; # Inserting reverse with elements # in the vector pair for i in range(n) : vp.append((reversDigits(arr[i]),arr[i])); # Sort the vector, this will sort the pair # according to the reverse of elements vp.sort() # Print the sorted vector content for i in range(len(vp)) : print(vp[i][1],end= \" \"); # Driver codeif __name__ == \"__main__\" : arr = [ 12, 10, 102, 31, 15 ]; n = len(arr); sortArr(arr, n); # This code is contributed by AnkitRai01", "e": 3806, "s": 2924, "text": null }, { "code": "// C# implementation of the approachusing System;using System.Collections.Generic;class GFG{ // Function to return the // reverse of n static int reversDigits(int num) { int rev_num = 0; while (num > 0) { rev_num = rev_num * 10 + num % 10; num = num / 10; } return rev_num; } // Function to sort the array according to // the reverse of elements static void sortArr(int[] arr, int n) { // Vector to store the reverse // with respective elements List<Tuple<int, int>> vp = new List<Tuple<int, int>>(); // Inserting reverse with elements // in the vector pair for (int i = 0; i < n; i++) { vp.Add(new Tuple<int, int>(reversDigits(arr[i]),arr[i])); } // Sort the vector, this will sort the pair // according to the reverse of elements vp.Sort(); // Print the sorted vector content for (int i = 0; i < vp.Count; i++) Console.Write(vp[i].Item2 + \" \"); } // Driver code static void Main() { int[] arr = { 12, 10, 102, 31, 15 }; int n = arr.Length; sortArr(arr, n); }} // This code is contributed by divyesh072019", "e": 5065, "s": 3806, "text": null }, { "code": "<script>// Javascript implementation of the// above approach // Function to return the// reverse of nfunction reversDigits(num){ var rev_num = 0; while (num > 0) { rev_num = rev_num * 10 + num % 10; num = Math.floor(num / 10); } return rev_num;} // Function to sort the array according to// the reverse of elementsfunction sortArr(arr, n){ // Vector to store the reverse // with respective elements var vp = new Array(n); for (var i = 0; i < n; i++) { vp[i] = []; } // Inserting reverse with elements // in the vector pair for (var i = 0; i < n; i++) { var pair = []; pair.push(reversDigits(arr[i])); pair.push(arr[i]); vp[i] = pair; } // Sort the vector, this will sort the pair // according to the reverse of elements vp = vp.sort(function(a,b) { return a[0] - b[0]; }); // Print the sorted vector content for (var i = 0; i < n; i++){ document.write(vp[i][1] + \" \"); }}// Driver codevar arr = [ 12, 10, 102, 31, 15 ];var n = arr.length; sortArr(arr, n); // This code is contributed by Shivanisingh</script>", "e": 6202, "s": 5065, "text": null }, { "code": null, "e": 6218, "s": 6202, "text": "10 31 12 15 102" }, { "code": null, "e": 6238, "s": 6220, "text": "Time Complexity: " }, { "code": null, "e": 6271, "s": 6238, "text": "where N is the size of the array" }, { "code": null, "e": 6294, "s": 6271, "text": "Auxiliary Space: O(N) " }, { "code": null, "e": 6304, "s": 6296, "text": "ankthon" }, { "code": null, "e": 6312, "s": 6304, "text": "offbeat" }, { "code": null, "e": 6326, "s": 6312, "text": "divyesh072019" }, { "code": null, "e": 6345, "s": 6326, "text": "shivanisinghss2110" }, { "code": null, "e": 6357, "s": 6345, "text": "anikakapoor" }, { "code": null, "e": 6367, "s": 6357, "text": "subham348" }, { "code": null, "e": 6375, "s": 6367, "text": "Numbers" }, { "code": null, "e": 6382, "s": 6375, "text": "Arrays" }, { "code": null, "e": 6395, "s": 6382, "text": "Mathematical" }, { "code": null, "e": 6403, "s": 6395, "text": "Sorting" }, { "code": null, "e": 6410, "s": 6403, "text": "Arrays" }, { "code": null, "e": 6423, "s": 6410, "text": "Mathematical" }, { "code": null, "e": 6431, "s": 6423, "text": "Sorting" }, { "code": null, "e": 6439, "s": 6431, "text": "Numbers" } ]
How to Calculate Weighted Average in Excel?
15 May, 2021 Have you ever think why we need an average or weightage average? In our daily, we can’t calculate everything, let’s suppose I am asking how’s the weather for a week, you are not going to tell me every day’s temperature, but an estimation here comes to the concept of an Average. Mathematically you can evaluate the average= Sum of Values/Number of Values, and the values carry equal weightage. Now let’s take another example you are in university, and you got your result of the semester exam. Since the semester consists of minor and major where minor carries 25% weightage and major carries 75% of weightage, now how will you calculate your average? So here comes a concept of weightage average where we consider the weight of every value. In order to calculate the weighted average, we will use two functions in Excel, the first one is the sum function, and the other SUMPRODUCT function, let’s discuss it one by one. It is an inbuilt function in Excel, helps to sum the numerical data in a range of cells. The function enables us to calculate multiple data very easily. = SUM (number1, [number2],... ) For example, you are purchasing class 12 science textbooks for donating to the NGO, so now you have to calculate the total number of books, so here you simply use the sum function. It is an inbuilt function in Excel, it will return the sum of products of the value given in the argument or an array. This function usually uses when you need to multiply many cells together. = SUMPRODUCT ( array1, [array2],[array3],...) For example, you are purchasing class 12 textbooks for donating to the NGO, so now you have to calculate the total price. So here’s this function comes handy, you will first enter array 1 and the put comma and again array 2 and then press enter, you will get your result, which is 5780. Now we are clear with the concept of both SUM function and SUMPRODUCT function now let’s calculate the weightage average. So in Excel to calculate weightage average is SUMPRODUCT/ SUM. Weightage Average = SUMPRODUCT ( array1, [array2],[array3],...)/SUM (number1, [number2],...) Let’s understand with an example, you have to calculate your college marks, but every subject has a different average. So we can use the weightage average to calculate our average marks. So Now put the values in the formula which is: weightage average = SUMPRODUCT(B1:B6, C2: C6)/SUM(C2:C6) And then hit enter, you will get your result 82.25. Example of weightage average Picked Excel Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. How to Delete Blank Columns in Excel? How to Normalize Data in Excel? How to Get Length of Array in Excel VBA? How to Find the Last Used Row and Column in Excel VBA? How to Use Solver in Excel? How to make a 3 Axis Graph using Excel? Introduction to Excel Spreadsheet Macros in Excel How to Create a Macro in Excel? How to Show Percentages in Stacked Column Chart in Excel?
[ { "code": null, "e": 28, "s": 0, "text": "\n15 May, 2021" }, { "code": null, "e": 423, "s": 28, "text": "Have you ever think why we need an average or weightage average? In our daily, we can’t calculate everything, let’s suppose I am asking how’s the weather for a week, you are not going to tell me every day’s temperature, but an estimation here comes to the concept of an Average. Mathematically you can evaluate the average= Sum of Values/Number of Values, and the values carry equal weightage." }, { "code": null, "e": 771, "s": 423, "text": "Now let’s take another example you are in university, and you got your result of the semester exam. Since the semester consists of minor and major where minor carries 25% weightage and major carries 75% of weightage, now how will you calculate your average? So here comes a concept of weightage average where we consider the weight of every value." }, { "code": null, "e": 950, "s": 771, "text": "In order to calculate the weighted average, we will use two functions in Excel, the first one is the sum function, and the other SUMPRODUCT function, let’s discuss it one by one." }, { "code": null, "e": 1103, "s": 950, "text": "It is an inbuilt function in Excel, helps to sum the numerical data in a range of cells. The function enables us to calculate multiple data very easily." }, { "code": null, "e": 1135, "s": 1103, "text": "= SUM (number1, [number2],... )" }, { "code": null, "e": 1317, "s": 1135, "text": "For example, you are purchasing class 12 science textbooks for donating to the NGO, so now you have to calculate the total number of books, so here you simply use the sum function." }, { "code": null, "e": 1510, "s": 1317, "text": "It is an inbuilt function in Excel, it will return the sum of products of the value given in the argument or an array. This function usually uses when you need to multiply many cells together." }, { "code": null, "e": 1556, "s": 1510, "text": "= SUMPRODUCT ( array1, [array2],[array3],...)" }, { "code": null, "e": 1844, "s": 1556, "text": "For example, you are purchasing class 12 textbooks for donating to the NGO, so now you have to calculate the total price. So here’s this function comes handy, you will first enter array 1 and the put comma and again array 2 and then press enter, you will get your result, which is 5780." }, { "code": null, "e": 2029, "s": 1844, "text": "Now we are clear with the concept of both SUM function and SUMPRODUCT function now let’s calculate the weightage average. So in Excel to calculate weightage average is SUMPRODUCT/ SUM." }, { "code": null, "e": 2123, "s": 2029, "text": "Weightage Average = SUMPRODUCT ( array1, [array2],[array3],...)/SUM (number1, [number2],...) " }, { "code": null, "e": 2359, "s": 2123, "text": " Let’s understand with an example, you have to calculate your college marks, but every subject has a different average. So we can use the weightage average to calculate our average marks. So Now put the values in the formula which is:" }, { "code": null, "e": 2417, "s": 2359, "text": " weightage average = SUMPRODUCT(B1:B6, C2: C6)/SUM(C2:C6)" }, { "code": null, "e": 2470, "s": 2417, "text": " And then hit enter, you will get your result 82.25." }, { "code": null, "e": 2499, "s": 2470, "text": "Example of weightage average" }, { "code": null, "e": 2506, "s": 2499, "text": "Picked" }, { "code": null, "e": 2512, "s": 2506, "text": "Excel" }, { "code": null, "e": 2610, "s": 2512, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 2648, "s": 2610, "text": "How to Delete Blank Columns in Excel?" }, { "code": null, "e": 2680, "s": 2648, "text": "How to Normalize Data in Excel?" }, { "code": null, "e": 2721, "s": 2680, "text": "How to Get Length of Array in Excel VBA?" }, { "code": null, "e": 2776, "s": 2721, "text": "How to Find the Last Used Row and Column in Excel VBA?" }, { "code": null, "e": 2804, "s": 2776, "text": "How to Use Solver in Excel?" }, { "code": null, "e": 2844, "s": 2804, "text": "How to make a 3 Axis Graph using Excel?" }, { "code": null, "e": 2878, "s": 2844, "text": "Introduction to Excel Spreadsheet" }, { "code": null, "e": 2894, "s": 2878, "text": "Macros in Excel" }, { "code": null, "e": 2926, "s": 2894, "text": "How to Create a Macro in Excel?" } ]
How to show webcam in TkInter Window?
Python libraries are independent and thus they all can be used for different purposes while building a particular featured application. In this example, we will build an application using OpenCV and Tkinter library. OpenCV is a Python library that is used to work with Computer Vision and other artificial artifacts. Using the OpenCV module, we have to show the webcam in a tkinter window. To create the application, you are required to install open-cv in your local machine and make sure that Python Pillow package is pre-installed. You can install these packages by typing the following commands, pip install open-cv pip install Pillow Once the installation has been done, we can start creating the structure and GUI of the application. The basic functionality of our application would be to open the web camera (if possible) using OpenCV. So, to display each and every captured frame, we can use Python Pillow (PIL) package which converts the frame into an Image. The Image now can be used in a Label widget that iteratively displays every captured frame in the window. # Import required Libraries from tkinter import * from PIL import Image, ImageTk import cv2 # Create an instance of TKinter Window or frame win = Tk() # Set the size of the window win.geometry("700x350") # Create a Label to capture the Video frames label =Label(win) label.grid(row=0, column=0) cap= cv2.VideoCapture(0) # Define function to show frame def show_frames(): # Get the latest frame and convert into Image cv2image= cv2.cvtColor(cap.read()[1],cv2.COLOR_BGR2RGB) img = Image.fromarray(cv2image) # Convert image to PhotoImage imgtk = ImageTk.PhotoImage(image = img) label.imgtk = imgtk label.configure(image=imgtk) # Repeat after an interval to capture continiously label.after(20, show_frames) show_frames() win.mainloop() Whenever we run the above code, it will turn on the webcam and the output will display in the tkinter window.
[ { "code": null, "e": 1577, "s": 1187, "text": "Python libraries are independent and thus they all can be used for different purposes\nwhile building a particular featured application. In this example, we will build an application\nusing OpenCV and Tkinter library. OpenCV is a Python library that is used to work with\nComputer Vision and other artificial artifacts. Using the OpenCV module, we have to show\nthe webcam in a tkinter window." }, { "code": null, "e": 1786, "s": 1577, "text": "To create the application, you are required to install open-cv in your local machine and make sure that Python Pillow package is pre-installed. You can install these packages by typing the following commands," }, { "code": null, "e": 1825, "s": 1786, "text": "pip install open-cv\npip install Pillow" }, { "code": null, "e": 2260, "s": 1825, "text": "Once the installation has been done, we can start creating the structure and GUI of the application. The basic functionality of our application would be to open the web camera (if possible) using OpenCV. So, to display each and every captured frame, we can use Python Pillow (PIL) package which converts the frame into an Image. The Image now can be used in a Label widget that iteratively displays every captured frame in the window." }, { "code": null, "e": 3025, "s": 2260, "text": "# Import required Libraries\nfrom tkinter import *\nfrom PIL import Image, ImageTk\nimport cv2\n\n# Create an instance of TKinter Window or frame\nwin = Tk()\n\n# Set the size of the window\nwin.geometry(\"700x350\")\n\n# Create a Label to capture the Video frames\nlabel =Label(win)\nlabel.grid(row=0, column=0)\ncap= cv2.VideoCapture(0)\n\n# Define function to show frame\ndef show_frames():\n # Get the latest frame and convert into Image\n cv2image= cv2.cvtColor(cap.read()[1],cv2.COLOR_BGR2RGB)\n img = Image.fromarray(cv2image)\n # Convert image to PhotoImage\n imgtk = ImageTk.PhotoImage(image = img)\n label.imgtk = imgtk\n label.configure(image=imgtk)\n # Repeat after an interval to capture continiously\n label.after(20, show_frames)\n\nshow_frames()\nwin.mainloop()" }, { "code": null, "e": 3135, "s": 3025, "text": "Whenever we run the above code, it will turn on the webcam and the output will display in the tkinter window." } ]
Linearity of Expectation
28 Jun, 2021 Prerequisite: Random VariableThis post is about mathematical concepts like expectation, linearity of expectation. It covers one of the required topics to understand Randomized Algorithms. Let us consider the following simple problem. Problem: Given a fair dice with 6 faces, the dice is thrown n times, find the expected value of the sum of all results.For example, if n = 2, there are total 36 possible outcomes. (1, 1), (1, 2), .... (1, 6) (2, 1), (2, 2), .... (2, 6) ................ ................ (6, 1), (6, 2), ..... (6, 6) Expected value of a discrete random variable is R defined as following. Suppose R can take value r1 with probability p1, value r2 with probability p2, and so on, up to value rk with probability pk. Then the expectation of this random variable R is defined as: E[R] = r1*p1 + r2*p2 + ... rk*pk Let us calculate expected value for the above example. Expected Value of sum = 2*1/36 + 3*1/36 + .... + 7*1/36 + of two dice throws 3*1/36 + 4*1/36 + .... + 8*1/36 + ........................ ......................... 7*1/36 + 8*1/36 + .... + 12*1/36 = 7 The above way to solve the problem becomes difficult when there are more dice throws.If we know about the linearity of expectation, then we can quickly solve the above problem for any number of throws. Linearity of Expectation: Let R1 and R2 be two discrete random variables on some probability space, then E[R1 + R2] = E[R1] + E[R2] Using the above formula, we can quickly solve the dice problem. Expected Value of sum of 2 dice throws = 2*(Expected value of one dice throw) = 2*(1/6 + 2/6 + .... 6/6) = 2*7/2 = 7 Expected value of sum for n dice throws is = n * 7/2 = 3.5 * n Some interesting facts about Linearly of Expectation: Linearity of expectation holds for both dependent and independent events. On the other hand the rule E[R1R2] = E[R1]*E[R2] is true only for independent events.Linearity of expectation holds for any number of random variables on some probability space. Let R1, R2, R3, ... Rk be k random variables, thenE[R1 + R2 + R3 + ... + Rk] = E[R1] + E[R2] + E[R3] + ... + E[Rk] Linearity of expectation holds for both dependent and independent events. On the other hand the rule E[R1R2] = E[R1]*E[R2] is true only for independent events. Linearity of expectation holds for any number of random variables on some probability space. Let R1, R2, R3, ... Rk be k random variables, thenE[R1 + R2 + R3 + ... + Rk] = E[R1] + E[R2] + E[R3] + ... + E[Rk] Another example that can be easily solved with the linearity of expectation:Hat-Check Problem: Let there be a group of n men where every man has one hat. The hats are redistributed and every man gets a random hat back. What is the expected number of men that get their original hat back? Solution: Let Ri be a random variable, the value of random variable is 1 if i’th man gets the same hat back, otherwise 0. So the expected number of men to get the right hat back is = E[R1] + E[R2] + .. + E[Rn] = P(R1 = 1) + P(R2 = 1) + .... + P(Rn = 1) [Here P(Ri = 1) indicates probability that Ri is 1] = 1/n + 1/n + ... + 1/n = 1 So on average 1 person gets the right hat back. Exercise: Given a fair coin, what is the expected number of heads when coin is tossed n times.Balls and Bins: Suppose we have m balls, labelled i = 1, ... , m and n bins, labeled j = 1, .. ,n. Each ball is thrown into one of the bin independently and uniformly at random. a) What is the expected number of balls in every bin b) What is the expected number of empty bins.Coupon Collector: Suppose there are n types of coupons in a lottery and each lot contains one coupon (with probability 1 = n each). How many lots have to be bought (in expectation) until we have at least one coupon of each type. Given a fair coin, what is the expected number of heads when coin is tossed n times. Balls and Bins: Suppose we have m balls, labelled i = 1, ... , m and n bins, labeled j = 1, .. ,n. Each ball is thrown into one of the bin independently and uniformly at random. a) What is the expected number of balls in every bin b) What is the expected number of empty bins. Coupon Collector: Suppose there are n types of coupons in a lottery and each lot contains one coupon (with probability 1 = n each). How many lots have to be bought (in expectation) until we have at least one coupon of each type. See following for solution of Coupon Collector.Expected Number of Trials until Success The linearity of expectation is useful in algorithms. For example, expected time complexity of random algorithms like randomized quick sort is evaluated using linearity of expectation (See this for reference). References:http://www.cse.iitd.ac.in/~mohanty/col106/Resources/linearity_expectation.pdf http://ocw.mit.edu/courses/electrical-engineering-and-computer-science/6-042j-mathematics-for-computer-science-fall-2010/video-lectures/lecture-22-expectation-i/ This article is contributed by Shubham Gupta. Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above praveshgupta1993 Mathematical Randomized Mathematical Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. 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 K'th Smallest/Largest Element in Unsorted Array | Set 2 (Expected Linear Time) Shuffle a given array using Fisher–Yates shuffle Algorithm Shuffle or Randomize a list in Java Generating Random String Using PHP Estimating the value of Pi using Monte Carlo
[ { "code": null, "e": 52, "s": 24, "text": "\n28 Jun, 2021" }, { "code": null, "e": 240, "s": 52, "text": "Prerequisite: Random VariableThis post is about mathematical concepts like expectation, linearity of expectation. It covers one of the required topics to understand Randomized Algorithms." }, { "code": null, "e": 286, "s": 240, "text": "Let us consider the following simple problem." }, { "code": null, "e": 466, "s": 286, "text": "Problem: Given a fair dice with 6 faces, the dice is thrown n times, find the expected value of the sum of all results.For example, if n = 2, there are total 36 possible outcomes." }, { "code": null, "e": 586, "s": 466, "text": "(1, 1), (1, 2), .... (1, 6)\n(2, 1), (2, 2), .... (2, 6)\n................\n................\n(6, 1), (6, 2), ..... (6, 6)\n" }, { "code": null, "e": 846, "s": 586, "text": "Expected value of a discrete random variable is R defined as following. Suppose R can take value r1 with probability p1, value r2 with probability p2, and so on, up to value rk with probability pk. Then the expectation of this random variable R is defined as:" }, { "code": null, "e": 879, "s": 846, "text": "E[R] = r1*p1 + r2*p2 + ... rk*pk" }, { "code": null, "e": 934, "s": 879, "text": "Let us calculate expected value for the above example." }, { "code": null, "e": 1259, "s": 934, "text": "Expected Value of sum = 2*1/36 + 3*1/36 + .... + 7*1/36 + \nof two dice throws 3*1/36 + 4*1/36 + .... + 8*1/36 + \n ........................\n .........................\n 7*1/36 + 8*1/36 + .... + 12*1/36 \n \n = 7\n" }, { "code": null, "e": 1461, "s": 1259, "text": "The above way to solve the problem becomes difficult when there are more dice throws.If we know about the linearity of expectation, then we can quickly solve the above problem for any number of throws." }, { "code": null, "e": 1566, "s": 1461, "text": "Linearity of Expectation: Let R1 and R2 be two discrete random variables on some probability space, then" }, { "code": null, "e": 1599, "s": 1566, "text": " E[R1 + R2] = E[R1] + E[R2] " }, { "code": null, "e": 1663, "s": 1599, "text": "Using the above formula, we can quickly solve the dice problem." }, { "code": null, "e": 1963, "s": 1663, "text": "Expected Value of sum of 2 dice throws = 2*(Expected value of one dice throw)\n = 2*(1/6 + 2/6 + .... 6/6)\n = 2*7/2\n = 7 \n\nExpected value of sum for n dice throws is = n * 7/2 = 3.5 * n " }, { "code": null, "e": 2017, "s": 1963, "text": "Some interesting facts about Linearly of Expectation:" }, { "code": null, "e": 2384, "s": 2017, "text": "Linearity of expectation holds for both dependent and independent events. On the other hand the rule E[R1R2] = E[R1]*E[R2] is true only for independent events.Linearity of expectation holds for any number of random variables on some probability space. Let R1, R2, R3, ... Rk be k random variables, thenE[R1 + R2 + R3 + ... + Rk] = E[R1] + E[R2] + E[R3] + ... + E[Rk]" }, { "code": null, "e": 2544, "s": 2384, "text": "Linearity of expectation holds for both dependent and independent events. On the other hand the rule E[R1R2] = E[R1]*E[R2] is true only for independent events." }, { "code": null, "e": 2752, "s": 2544, "text": "Linearity of expectation holds for any number of random variables on some probability space. Let R1, R2, R3, ... Rk be k random variables, thenE[R1 + R2 + R3 + ... + Rk] = E[R1] + E[R2] + E[R3] + ... + E[Rk]" }, { "code": null, "e": 3040, "s": 2752, "text": "Another example that can be easily solved with the linearity of expectation:Hat-Check Problem: Let there be a group of n men where every man has one hat. The hats are redistributed and every man gets a random hat back. What is the expected number of men that get their original hat back?" }, { "code": null, "e": 3162, "s": 3040, "text": "Solution: Let Ri be a random variable, the value of random variable is 1 if i’th man gets the same hat back, otherwise 0." }, { "code": null, "e": 3390, "s": 3162, "text": "So the expected number of men to get the right hat back is\n = E[R1] + E[R2] + .. + E[Rn] \n = P(R1 = 1) + P(R2 = 1) + .... + P(Rn = 1) \n [Here P(Ri = 1) indicates probability that Ri is 1]\n = 1/n + 1/n + ... + 1/n \n = 1\n" }, { "code": null, "e": 3438, "s": 3390, "text": "So on average 1 person gets the right hat back." }, { "code": null, "e": 3448, "s": 3438, "text": "Exercise:" }, { "code": null, "e": 4045, "s": 3448, "text": "Given a fair coin, what is the expected number of heads when coin is tossed n times.Balls and Bins: Suppose we have m balls, labelled i = 1, ... , m and n bins, labeled j = 1, .. ,n. Each ball is thrown into one of the bin independently and uniformly at random. a) What is the expected number of balls in every bin b) What is the expected number of empty bins.Coupon Collector: Suppose there are n types of coupons in a lottery and each lot contains one coupon (with probability 1 = n each). How many lots have to be bought (in expectation) until we have at least one coupon of each type." }, { "code": null, "e": 4130, "s": 4045, "text": "Given a fair coin, what is the expected number of heads when coin is tossed n times." }, { "code": null, "e": 4415, "s": 4130, "text": "Balls and Bins: Suppose we have m balls, labelled i = 1, ... , m and n bins, labeled j = 1, .. ,n. Each ball is thrown into one of the bin independently and uniformly at random. a) What is the expected number of balls in every bin b) What is the expected number of empty bins." }, { "code": null, "e": 4644, "s": 4415, "text": "Coupon Collector: Suppose there are n types of coupons in a lottery and each lot contains one coupon (with probability 1 = n each). How many lots have to be bought (in expectation) until we have at least one coupon of each type." }, { "code": null, "e": 4731, "s": 4644, "text": "See following for solution of Coupon Collector.Expected Number of Trials until Success" }, { "code": null, "e": 4941, "s": 4731, "text": "The linearity of expectation is useful in algorithms. For example, expected time complexity of random algorithms like randomized quick sort is evaluated using linearity of expectation (See this for reference)." }, { "code": null, "e": 5030, "s": 4941, "text": "References:http://www.cse.iitd.ac.in/~mohanty/col106/Resources/linearity_expectation.pdf" }, { "code": null, "e": 5192, "s": 5030, "text": "http://ocw.mit.edu/courses/electrical-engineering-and-computer-science/6-042j-mathematics-for-computer-science-fall-2010/video-lectures/lecture-22-expectation-i/" }, { "code": null, "e": 5362, "s": 5192, "text": "This article is contributed by Shubham Gupta. Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above" }, { "code": null, "e": 5379, "s": 5362, "text": "praveshgupta1993" }, { "code": null, "e": 5392, "s": 5379, "text": "Mathematical" }, { "code": null, "e": 5403, "s": 5392, "text": "Randomized" }, { "code": null, "e": 5416, "s": 5403, "text": "Mathematical" }, { "code": null, "e": 5514, "s": 5416, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 5544, "s": 5514, "text": "Program for Fibonacci numbers" }, { "code": null, "e": 5587, "s": 5544, "text": "Set in C++ Standard Template Library (STL)" }, { "code": null, "e": 5647, "s": 5587, "text": "Write a program to print all permutations of a given string" }, { "code": null, "e": 5662, "s": 5647, "text": "C++ Data Types" }, { "code": null, "e": 5686, "s": 5662, "text": "Merge two sorted arrays" }, { "code": null, "e": 5765, "s": 5686, "text": "K'th Smallest/Largest Element in Unsorted Array | Set 2 (Expected Linear Time)" }, { "code": null, "e": 5824, "s": 5765, "text": "Shuffle a given array using Fisher–Yates shuffle Algorithm" }, { "code": null, "e": 5860, "s": 5824, "text": "Shuffle or Randomize a list in Java" }, { "code": null, "e": 5895, "s": 5860, "text": "Generating Random String Using PHP" } ]
Sieve of Atkin
10 Mar, 2022 Given a limit, print all prime numbers smaller than or equal to the given limit. Examples: Input: limit = 10Output: 2, 3, 5, 7 Input: limit = 20Output: 2, 3, 5, 7, 11, 13, 17, 19 Other Approaches: The prime numbers till a limit can be generated using other algorithms, such as: Sieve of Eratosthenes: O(N*log(log(N))) Sieve of Sundaram: O(N*log N) Sieve of Atkin Approach: The sieve of Atkin is a modern algorithm for finding all prime numbers up to a specified integer. Sieve of Atkin vs Sieve of Eratosthenes: Compared with the ancient Sieve of Eratosthenes, which marks off multiples of primes, it does some preliminary work and then marks off multiples of squares of primes, that’s why it has a better theoretical asymptotic complexity with Complexity of (N / (log log N)) How Sieve of Atkin algorithm works: The Sieve of Atkin algorithm works similar to Sieve of Eratosthenes to filter out the composite numbers from a list of numbers, but this algorithm works in terms of modulo-60 remainders. So we first assume all the numbers within limit to be composite, and then apply filter or sieve on them. If while any filter, the number appears to be prime, we mark it as prime and move on to the next number. The filter or sieve in this algorithms works mainly 4 cases or layers: Case 1: If limit is greater than 2 or 3:The algorithm treats 2, and 3 as special cases and just adds them to the set of primes to start with. The algorithm treats 2, and 3 as special cases and just adds them to the set of primes to start with. Case 2: if 4x2+y2=n is odd and modulo-12 remainder is 1 or 5Since all numbers with modulo-60 remainders 1, 13, 17, 29, 37, 41, 49, or 53 have a modulo-12 remainder of 1 or 5. Therefore, for this filter as well, we have to check if the number is 1 or 5 when taken modulo with 12.Also, These numbers are prime if and only if the number of solutions to 4x2+y2=n is odd and the number is square-free. A square-free integer is one that is not divisible by any perfect square other than 1. Since all numbers with modulo-60 remainders 1, 13, 17, 29, 37, 41, 49, or 53 have a modulo-12 remainder of 1 or 5. Therefore, for this filter as well, we have to check if the number is 1 or 5 when taken modulo with 12. Also, These numbers are prime if and only if the number of solutions to 4x2+y2=n is odd and the number is square-free. A square-free integer is one that is not divisible by any perfect square other than 1. Case 3: if 3x2+y2=n is odd and modulo-6 remainder is 1All numbers with modulo-60 remainder 7, 19, 31, or 43 have a modulo-6 remainder of 1. These numbers are prime if and only if the number of solutions to 3x2 + y2 = n is odd and the number is square-free. All numbers with modulo-60 remainder 7, 19, 31, or 43 have a modulo-6 remainder of 1. These numbers are prime if and only if the number of solutions to 3x2 + y2 = n is odd and the number is square-free. Case 4: if 3x2-y2=n is odd and modulo-12 remainder is 11All numbers with modulo-60 remainder 11, 23, 47, or 59 have a modulo-12 remainder of 11. These numbers are prime if and only if the number of solutions to 3x2 – y2 = n is odd and the number is square-free. All numbers with modulo-60 remainder 11, 23, 47, or 59 have a modulo-12 remainder of 11. These numbers are prime if and only if the number of solutions to 3x2 – y2 = n is odd and the number is square-free. Case 5: Filtering out all the residual primes which have not yet been foundDue to the filtering of the Sieve of Atkin algorithm, there might be some prime numbers who have been discarded or not found in the above cases.So to find out those, select all non-primes within limit, and mark all their squares as non-primes. Due to the filtering of the Sieve of Atkin algorithm, there might be some prime numbers who have been discarded or not found in the above cases. So to find out those, select all non-primes within limit, and mark all their squares as non-primes. At the end of all of the filters above, the positions in the Sieve with a true value will be the list of primes within limit. Illustration of Sieve of Atkin algorithm: Consider limit as 20 and lets see how Sieve of Atkin algorithm generates primes up to 20: Step 0: The status for all the numbers at the start is false. The special numbers are 2, 3, and 5, which are known to be prime. Step 1: Generate values for the conditions. Step 2: Flipping the status according to condition.The above values of n in the table generated in the x, y loop will be tested for modulo conditions. Column 1: if (colum1 value) % 12 == 1 or 5, then flip the sieve status for that number. Column 2: if (colum2 value) % 12 == 7, then flip the sieve status for that number. Column 3: if (colum3 value) % 12 == 11, then flip the sieve status for that number. Note: Notice that we are taking mod with 12 in place of 60. This is because if we take mod 60 then we have to consider as many r as 1, 13, 17, 29, 37, 41, 49, or 53 and for all these r, mod 12 is 1 or 5. (done only to reduce the expression size) Step 3: Checking for Square free Condition: If any number in our list is the square of any number, then remove it. Step 4: Creating an array of prime numbers for which status is true. i.e. 2 3 5 7 11 13 17 19 Step 5: Print the output on the screen. Sieve of Atkin algorithm step-by-step: Create a results list, filled with 2, 3, and 5.Create a sieve list with an entry for each positive integer; all entries in this list should initially be marked non-prime.For each entry number n in the sieve list, with modulo-sixty remainder r: If r is 1, 13, 17, 29, 37, 41, 49, or 53, flip the entry for each possible solution to 4x2 + y2 = n.If r is 7, 19, 31, or 43, flip the entry for each possible solution to 3x2 + y2 = n.If r is 11, 23, 47, or 59, flip the entry for each possible solution to 3x2 – y2 = n when x > y.If r is something else, ignore it completely...Start with the lowest number in the sieve list.Take the next number in the sieve list, still marked prime.Include the number in the results list.Square the number and mark all multiples of that square as non-prime. Note that the multiples that can be factored by 2, 3, or 5 need not be marked, as these will be ignored in the final enumeration of primes.Repeat steps four through seven. Create a results list, filled with 2, 3, and 5. Create a sieve list with an entry for each positive integer; all entries in this list should initially be marked non-prime. For each entry number n in the sieve list, with modulo-sixty remainder r: If r is 1, 13, 17, 29, 37, 41, 49, or 53, flip the entry for each possible solution to 4x2 + y2 = n.If r is 7, 19, 31, or 43, flip the entry for each possible solution to 3x2 + y2 = n.If r is 11, 23, 47, or 59, flip the entry for each possible solution to 3x2 – y2 = n when x > y.If r is something else, ignore it completely... If r is 1, 13, 17, 29, 37, 41, 49, or 53, flip the entry for each possible solution to 4x2 + y2 = n.If r is 7, 19, 31, or 43, flip the entry for each possible solution to 3x2 + y2 = n.If r is 11, 23, 47, or 59, flip the entry for each possible solution to 3x2 – y2 = n when x > y.If r is something else, ignore it completely... If r is 1, 13, 17, 29, 37, 41, 49, or 53, flip the entry for each possible solution to 4x2 + y2 = n. If r is 7, 19, 31, or 43, flip the entry for each possible solution to 3x2 + y2 = n. If r is 11, 23, 47, or 59, flip the entry for each possible solution to 3x2 – y2 = n when x > y. If r is something else, ignore it completely... Start with the lowest number in the sieve list. Take the next number in the sieve list, still marked prime. Include the number in the results list. Square the number and mark all multiples of that square as non-prime. Note that the multiples that can be factored by 2, 3, or 5 need not be marked, as these will be ignored in the final enumeration of primes. Repeat steps four through seven. Below is the implementation of the above algorithm. C++ Java Python 3 C# PHP Javascript // C++ program for implementation// of Sieve of Atkin#include <bits/stdc++.h>using namespace std; // Function to generate primes// till limit using Sieve of Atkinvoid SieveOfAtkin(int limit){ // Initialise the sieve array // with initial false values bool sieve[limit]; for (int i = 0; i <= limit; i++) sieve[i] = false; // 2 and 3 are known to be prime if (limit > 2) sieve[2] = true; if (limit > 3) sieve[3] = true; /* Mark sieve[n] is true if one of the following is true: a) n = (4*x*x)+(y*y) has odd number of solutions, i.e., there exist odd number of distinct pairs (x, y) that satisfy the equation and n % 12 = 1 or n % 12 = 5. b) n = (3*x*x)+(y*y) has odd number of solutions and n % 12 = 7 c) n = (3*x*x)-(y*y) has odd number of solutions, x > y and n % 12 = 11 */ for (int x = 1; x * x <= limit; x++) { for (int y = 1; y * y <= limit; y++) { // Condition 1 int n = (4 * x * x) + (y * y); if (n <= limit && (n % 12 == 1 || n % 12 == 5)) sieve[n] ^= true; // Condition 2 n = (3 * x * x) + (y * y); if (n <= limit && n % 12 == 7) sieve[n] ^= true; // Condition 3 n = (3 * x * x) - (y * y); if (x > y && n <= limit && n % 12 == 11) sieve[n] ^= true; } } // Mark all multiples // of squares as non-prime for (int r = 5; r * r <= limit; r++) { if (sieve[r]) { for (int i = r * r; i <= limit; i += r * r) sieve[i] = false; } } // Print primes using sieve[] for (int a = 1; a <= limit; a++) if (sieve[a]) cout << a << " "; cout << "\n";} // Driver programint main(void){ int limit = 20; SieveOfAtkin(limit); return 0;} // Java program for implementation// of Sieve of Atkinclass GFG { static void SieveOfAtkin(int limit) { // 2 and 3 are known to be prime if (limit > 2) System.out.print(2 + " "); if (limit > 3) System.out.print(3 + " "); // Initialise the sieve array with // false values boolean sieve[] = new boolean[limit+1]; for (int i = 0; i <= limit; i++) sieve[i] = false; /* Mark sieve[n] is true if one of the following is true: a) n = (4*x*x)+(y*y) has odd number of solutions, i.e., there exist odd number of distinct pairs (x, y) that satisfy the equation and n % 12 = 1 or n % 12 = 5. b) n = (3*x*x)+(y*y) has odd number of solutions and n % 12 = 7 c) n = (3*x*x)-(y*y) has odd number of solutions, x > y and n % 12 = 11 */ for (int x = 1; x * x <= limit; x++) { for (int y = 1; y * y <= limit; y++) { // Main part of Sieve of Atkin int n = (4 * x * x) + (y * y); if (n <= limit && (n % 12 == 1 || n % 12 == 5)) sieve[n] ^= true; n = (3 * x * x) + (y * y); if (n <= limit && n % 12 == 7) sieve[n] ^= true; n = (3 * x * x) - (y * y); if (x > y && n <= limit && n % 12 == 11) sieve[n] ^= true; } } // Mark all multiples of squares as // non-prime for (int r = 5; r * r <= limit; r++) { if (sieve[r]) { for (int i = r * r; i <= limit; i += r * r) sieve[i] = false; } } // Print primes using sieve[] for (int a = 5; a <= limit; a++) if (sieve[a]) System.out.print(a + " "); System.out.println(); } // Driver code public static void main(String[] args) { int limit = 20; SieveOfAtkin(limit); }} // This code is contributed by Anant Agarwal. # Python 3 program for# implementation of# Sieve of Atkin def SieveOfAtkin(limit): # 2 and 3 are known # to be prime if limit > 2: print(2, end=" ") if limit > 3: print(3, end=" ") # Initialise the sieve # array with False values sieve = [False] * (limit + 1) for i in range(0, limit + 1): sieve[i] = False '''Mark sieve[n] is True if one of the following is True: a) n = (4*x*x)+(y*y) has odd number of solutions, i.e., there exist odd number of distinct pairs (x, y) that satisfy the equation and n % 12 = 1 or n % 12 = 5. b) n = (3*x*x)+(y*y) has odd number of solutions and n % 12 = 7 c) n = (3*x*x)-(y*y) has odd number of solutions, x > y and n % 12 = 11 ''' x = 1 while x * x <= limit: y = 1 while y * y <= limit: # Main part of # Sieve of Atkin n = (4 * x * x) + (y * y) if (n <= limit and (n % 12 == 1 or n % 12 == 5)): sieve[n] ^= True n = (3 * x * x) + (y * y) if n <= limit and n % 12 == 7: sieve[n] ^= True n = (3 * x * x) - (y * y) if (x > y and n <= limit and n % 12 == 11): sieve[n] ^= True y += 1 x += 1 # Mark all multiples of # squares as non-prime r = 5 while r * r <= limit: if sieve[r]: for i in range(r * r, limit+1, r * r): sieve[i] = False r += 1 # Print primes # using sieve[] for a in range(5, limit+1): if sieve[a]: print(a, end=" ") # Driver Codelimit = 20SieveOfAtkin(limit) # This code is contributed# by Smitha // C# program for implementation of Sieve// of Atkinusing System; class GFG { static void SieveOfAtkin(int limit) { // 2 and 3 are known to be prime if (limit > 2) Console.Write(2 + " "); if (limit > 3) Console.Write(3 + " "); // Initialise the sieve array with // false values bool[] sieve = new bool[limit + 1]; for (int i = 0; i <= limit; i++) sieve[i] = false; /* Mark sieve[n] is true if one of the following is true: a) n = (4*x*x)+(y*y) has odd number of solutions, i.e., there exist odd number of distinct pairs (x, y) that satisfy the equation and n % 12 = 1 or n % 12 = 5. b) n = (3*x*x)+(y*y) has odd number of solutions and n % 12 = 7 c) n = (3*x*x)-(y*y) has odd number of solutions, x > y and n % 12 = 11 */ for (int x = 1; x * x <= limit; x++) { for (int y = 1; y * y <= limit; y++) { // Main part of Sieve of Atkin int n = (4 * x * x) + (y * y); if (n <= limit && (n % 12 == 1 || n % 12 == 5)) sieve[n] ^= true; n = (3 * x * x) + (y * y); if (n <= limit && n % 12 == 7) sieve[n] ^= true; n = (3 * x * x) - (y * y); if (x > y && n <= limit && n % 12 == 11) sieve[n] ^= true; } } // Mark all multiples of squares as // non-prime for (int r = 5; r * r < limit; r++) { if (sieve[r]) { for (int i = r * r; i < limit; i += r * r) sieve[i] = false; } } // Print primes using sieve[] for (int a = 5; a <= limit; a++) if (sieve[a]) Console.Write(a + " "); Console.WriteLine(); } // Driver code public static void Main() { int limit = 20; SieveOfAtkin(limit); }} // This code is contributed by nitin mittal <?php// PHP program for implementation// of Sieve of Atkin function SieveOfAtkin($limit){ // 2 and 3 are known // to be prime if ($limit > 2) echo 2 , " "; if ($limit > 3) echo 3 , " "; // Initialise the sieve array // with false values $sieve[$limit+1] = 0; for ($i = 0; $i <= $limit; $i++) $sieve[$i] = false; /* Mark sieve[n] is true if one of the following is true: a) n = (4*x*x)+(y*y) has odd number of solutions, i.e., there exist odd number of distinct pairs (x, y) that satisfy the equation and n % 12 = 1 or n % 12 = 5. b) n = (3*x*x)+(y*y) has odd number of solutions and n % 12 = 7 c) n = (3*x*x)-(y*y) has odd number of solutions, x > y and n % 12 = 11 */ for ($x = 1; $x * $x <= $limit; $x++) { for ($y = 1; $y * $y <= $limit; $y++) { // Main part of Sieve of Atkin $n = (4 * $x * $x) + ($y * $y); if ($n <= $limit && ($n % 12 == 1 || $n % 12 == 5)) $sieve[$n] ^= true; $n = (3 * $x * $x) + ($y * $y); if ($n <= $limit && $n % 12 == 7) $sieve[$n] = true; $n = (3 * $x * $x) - ($y * $y); if ($x > $y && $n <= $limit && $n % 12 == 11) $sieve[$n] ^= true; } } // Mark all multiples of // squares as non-prime for ($r = 5; $r * $r <= $limit; $r++) { if ($sieve[$r]) { for ($i = $r * $r; $i <= $limit; $i += $r * $r) $sieve[$i] = false; } } // Print primes // using sieve[] for ($a = 5; $a <= $limit; $a++) if ($sieve[$a]) echo $a , " "; echo "\n";} // Driver Code $limit = 20; SieveOfAtkin($limit); // This code is contributed by nitin mittal.?> <script>// Javascript program for implementation// of Sieve of Atkin function SieveOfAtkin(limit){ // 2 and 3 are known // to be prime if (limit > 2) document.write(2 + " "); if (limit > 3) document.write(3 + " "); // Initialise the sieve array // with false values let sieve = new Array() sieve[limit+1] = 0; for (let i = 0; i <= limit; i++) sieve[i] = false; /* Mark sieve[n] is true if one of the following is true: a) n = (4*x*x)+(y*y) has odd number of solutions, i.e., there exist odd number of distinct pairs (x, y) that satisfy the equation and n % 12 = 1 or n % 12 = 5. b) n = (3*x*x)+(y*y) has odd number of solutions and n % 12 = 7 c) n = (3*x*x)-(y*y) has odd number of solutions, x > y and n % 12 = 11 */ for (let x = 1; x * x <= limit; x++) { for (let y = 1; y * y <= limit; y++) { // Main part of Sieve of Atkin let n = (4 * x * x) + (y * y); if (n <= limit && (n % 12 == 1 || n % 12 == 5)) sieve[n] ^= true; n = (3 * x * x) + (y * y); if (n <= limit && n % 12 == 7) sieve[n] = true; n = (3 * x * x) - (y * y); if (x > y && n <= limit && n % 12 == 11) sieve[n] ^= true; } } // Mark all multiples of // squares as non-prime for (let r = 5; r * r <= limit; r++) { if (sieve[r]) { for (i = r * r; i <= limit; i += r * r) sieve[i] = false; } } // Print primes // using sieve[] for (let a = 5; a <= limit; a++) if (sieve[a]) document.write(a , " "); document.write("<br>");} // Driver Code let limit = 20; SieveOfAtkin(limit); // This code is contributed by nitin gfgking </script> 2 3 5 7 11 13 17 19 This article is contributed by Anuj Rathore. Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above. nitin mittal Smitha Dinesh Semwal gfgking saurabh1990aror adtimokhin RishabhPrabhu Prime Number sieve Mathematical Mathematical Prime Number sieve Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 52, "s": 24, "text": "\n10 Mar, 2022" }, { "code": null, "e": 133, "s": 52, "text": "Given a limit, print all prime numbers smaller than or equal to the given limit." }, { "code": null, "e": 144, "s": 133, "text": "Examples: " }, { "code": null, "e": 181, "s": 144, "text": "Input: limit = 10Output: 2, 3, 5, 7" }, { "code": null, "e": 235, "s": 181, "text": "Input: limit = 20Output: 2, 3, 5, 7, 11, 13, 17, 19 " }, { "code": null, "e": 335, "s": 235, "text": "Other Approaches: The prime numbers till a limit can be generated using other algorithms, such as: " }, { "code": null, "e": 375, "s": 335, "text": "Sieve of Eratosthenes: O(N*log(log(N)))" }, { "code": null, "e": 405, "s": 375, "text": "Sieve of Sundaram: O(N*log N)" }, { "code": null, "e": 529, "s": 405, "text": "Sieve of Atkin Approach: The sieve of Atkin is a modern algorithm for finding all prime numbers up to a specified integer. " }, { "code": null, "e": 571, "s": 529, "text": "Sieve of Atkin vs Sieve of Eratosthenes: " }, { "code": null, "e": 836, "s": 571, "text": "Compared with the ancient Sieve of Eratosthenes, which marks off multiples of primes, it does some preliminary work and then marks off multiples of squares of primes, that’s why it has a better theoretical asymptotic complexity with Complexity of (N / (log log N))" }, { "code": null, "e": 873, "s": 836, "text": "How Sieve of Atkin algorithm works: " }, { "code": null, "e": 1061, "s": 873, "text": "The Sieve of Atkin algorithm works similar to Sieve of Eratosthenes to filter out the composite numbers from a list of numbers, but this algorithm works in terms of modulo-60 remainders. " }, { "code": null, "e": 1271, "s": 1061, "text": "So we first assume all the numbers within limit to be composite, and then apply filter or sieve on them. If while any filter, the number appears to be prime, we mark it as prime and move on to the next number." }, { "code": null, "e": 1342, "s": 1271, "text": "The filter or sieve in this algorithms works mainly 4 cases or layers:" }, { "code": null, "e": 1484, "s": 1342, "text": "Case 1: If limit is greater than 2 or 3:The algorithm treats 2, and 3 as special cases and just adds them to the set of primes to start with." }, { "code": null, "e": 1586, "s": 1484, "text": "The algorithm treats 2, and 3 as special cases and just adds them to the set of primes to start with." }, { "code": null, "e": 2070, "s": 1586, "text": "Case 2: if 4x2+y2=n is odd and modulo-12 remainder is 1 or 5Since all numbers with modulo-60 remainders 1, 13, 17, 29, 37, 41, 49, or 53 have a modulo-12 remainder of 1 or 5. Therefore, for this filter as well, we have to check if the number is 1 or 5 when taken modulo with 12.Also, These numbers are prime if and only if the number of solutions to 4x2+y2=n is odd and the number is square-free. A square-free integer is one that is not divisible by any perfect square other than 1." }, { "code": null, "e": 2289, "s": 2070, "text": "Since all numbers with modulo-60 remainders 1, 13, 17, 29, 37, 41, 49, or 53 have a modulo-12 remainder of 1 or 5. Therefore, for this filter as well, we have to check if the number is 1 or 5 when taken modulo with 12." }, { "code": null, "e": 2409, "s": 2289, "text": "Also, These numbers are prime if and only if the number of solutions to 4x2+y2=n is odd and the number is square-free. " }, { "code": null, "e": 2496, "s": 2409, "text": "A square-free integer is one that is not divisible by any perfect square other than 1." }, { "code": null, "e": 2753, "s": 2496, "text": "Case 3: if 3x2+y2=n is odd and modulo-6 remainder is 1All numbers with modulo-60 remainder 7, 19, 31, or 43 have a modulo-6 remainder of 1. These numbers are prime if and only if the number of solutions to 3x2 + y2 = n is odd and the number is square-free." }, { "code": null, "e": 2840, "s": 2753, "text": "All numbers with modulo-60 remainder 7, 19, 31, or 43 have a modulo-6 remainder of 1. " }, { "code": null, "e": 2957, "s": 2840, "text": "These numbers are prime if and only if the number of solutions to 3x2 + y2 = n is odd and the number is square-free." }, { "code": null, "e": 3219, "s": 2957, "text": "Case 4: if 3x2-y2=n is odd and modulo-12 remainder is 11All numbers with modulo-60 remainder 11, 23, 47, or 59 have a modulo-12 remainder of 11. These numbers are prime if and only if the number of solutions to 3x2 – y2 = n is odd and the number is square-free." }, { "code": null, "e": 3309, "s": 3219, "text": "All numbers with modulo-60 remainder 11, 23, 47, or 59 have a modulo-12 remainder of 11. " }, { "code": null, "e": 3426, "s": 3309, "text": "These numbers are prime if and only if the number of solutions to 3x2 – y2 = n is odd and the number is square-free." }, { "code": null, "e": 3745, "s": 3426, "text": "Case 5: Filtering out all the residual primes which have not yet been foundDue to the filtering of the Sieve of Atkin algorithm, there might be some prime numbers who have been discarded or not found in the above cases.So to find out those, select all non-primes within limit, and mark all their squares as non-primes." }, { "code": null, "e": 3890, "s": 3745, "text": "Due to the filtering of the Sieve of Atkin algorithm, there might be some prime numbers who have been discarded or not found in the above cases." }, { "code": null, "e": 3990, "s": 3890, "text": "So to find out those, select all non-primes within limit, and mark all their squares as non-primes." }, { "code": null, "e": 4116, "s": 3990, "text": "At the end of all of the filters above, the positions in the Sieve with a true value will be the list of primes within limit." }, { "code": null, "e": 4158, "s": 4116, "text": "Illustration of Sieve of Atkin algorithm:" }, { "code": null, "e": 4248, "s": 4158, "text": "Consider limit as 20 and lets see how Sieve of Atkin algorithm generates primes up to 20:" }, { "code": null, "e": 4376, "s": 4248, "text": "Step 0: The status for all the numbers at the start is false. The special numbers are 2, 3, and 5, which are known to be prime." }, { "code": null, "e": 4422, "s": 4376, "text": "Step 1: Generate values for the conditions. " }, { "code": null, "e": 4573, "s": 4422, "text": "Step 2: Flipping the status according to condition.The above values of n in the table generated in the x, y loop will be tested for modulo conditions." }, { "code": null, "e": 4661, "s": 4573, "text": "Column 1: if (colum1 value) % 12 == 1 or 5, then flip the sieve status for that number." }, { "code": null, "e": 4744, "s": 4661, "text": "Column 2: if (colum2 value) % 12 == 7, then flip the sieve status for that number." }, { "code": null, "e": 4828, "s": 4744, "text": "Column 3: if (colum3 value) % 12 == 11, then flip the sieve status for that number." }, { "code": null, "e": 5074, "s": 4828, "text": "Note: Notice that we are taking mod with 12 in place of 60. This is because if we take mod 60 then we have to consider as many r as 1, 13, 17, 29, 37, 41, 49, or 53 and for all these r, mod 12 is 1 or 5. (done only to reduce the expression size)" }, { "code": null, "e": 5189, "s": 5074, "text": "Step 3: Checking for Square free Condition: If any number in our list is the square of any number, then remove it." }, { "code": null, "e": 5283, "s": 5189, "text": "Step 4: Creating an array of prime numbers for which status is true. i.e. 2 3 5 7 11 13 17 19" }, { "code": null, "e": 5323, "s": 5283, "text": "Step 5: Print the output on the screen." }, { "code": null, "e": 5362, "s": 5323, "text": "Sieve of Atkin algorithm step-by-step:" }, { "code": null, "e": 6320, "s": 5362, "text": "Create a results list, filled with 2, 3, and 5.Create a sieve list with an entry for each positive integer; all entries in this list should initially be marked non-prime.For each entry number n in the sieve list, with modulo-sixty remainder r: If r is 1, 13, 17, 29, 37, 41, 49, or 53, flip the entry for each possible solution to 4x2 + y2 = n.If r is 7, 19, 31, or 43, flip the entry for each possible solution to 3x2 + y2 = n.If r is 11, 23, 47, or 59, flip the entry for each possible solution to 3x2 – y2 = n when x > y.If r is something else, ignore it completely...Start with the lowest number in the sieve list.Take the next number in the sieve list, still marked prime.Include the number in the results list.Square the number and mark all multiples of that square as non-prime. Note that the multiples that can be factored by 2, 3, or 5 need not be marked, as these will be ignored in the final enumeration of primes.Repeat steps four through seven." }, { "code": null, "e": 6368, "s": 6320, "text": "Create a results list, filled with 2, 3, and 5." }, { "code": null, "e": 6492, "s": 6368, "text": "Create a sieve list with an entry for each positive integer; all entries in this list should initially be marked non-prime." }, { "code": null, "e": 6894, "s": 6492, "text": "For each entry number n in the sieve list, with modulo-sixty remainder r: If r is 1, 13, 17, 29, 37, 41, 49, or 53, flip the entry for each possible solution to 4x2 + y2 = n.If r is 7, 19, 31, or 43, flip the entry for each possible solution to 3x2 + y2 = n.If r is 11, 23, 47, or 59, flip the entry for each possible solution to 3x2 – y2 = n when x > y.If r is something else, ignore it completely..." }, { "code": null, "e": 7222, "s": 6894, "text": "If r is 1, 13, 17, 29, 37, 41, 49, or 53, flip the entry for each possible solution to 4x2 + y2 = n.If r is 7, 19, 31, or 43, flip the entry for each possible solution to 3x2 + y2 = n.If r is 11, 23, 47, or 59, flip the entry for each possible solution to 3x2 – y2 = n when x > y.If r is something else, ignore it completely..." }, { "code": null, "e": 7323, "s": 7222, "text": "If r is 1, 13, 17, 29, 37, 41, 49, or 53, flip the entry for each possible solution to 4x2 + y2 = n." }, { "code": null, "e": 7408, "s": 7323, "text": "If r is 7, 19, 31, or 43, flip the entry for each possible solution to 3x2 + y2 = n." }, { "code": null, "e": 7505, "s": 7408, "text": "If r is 11, 23, 47, or 59, flip the entry for each possible solution to 3x2 – y2 = n when x > y." }, { "code": null, "e": 7553, "s": 7505, "text": "If r is something else, ignore it completely..." }, { "code": null, "e": 7601, "s": 7553, "text": "Start with the lowest number in the sieve list." }, { "code": null, "e": 7661, "s": 7601, "text": "Take the next number in the sieve list, still marked prime." }, { "code": null, "e": 7701, "s": 7661, "text": "Include the number in the results list." }, { "code": null, "e": 7911, "s": 7701, "text": "Square the number and mark all multiples of that square as non-prime. Note that the multiples that can be factored by 2, 3, or 5 need not be marked, as these will be ignored in the final enumeration of primes." }, { "code": null, "e": 7944, "s": 7911, "text": "Repeat steps four through seven." }, { "code": null, "e": 7997, "s": 7944, "text": "Below is the implementation of the above algorithm. " }, { "code": null, "e": 8001, "s": 7997, "text": "C++" }, { "code": null, "e": 8006, "s": 8001, "text": "Java" }, { "code": null, "e": 8015, "s": 8006, "text": "Python 3" }, { "code": null, "e": 8018, "s": 8015, "text": "C#" }, { "code": null, "e": 8022, "s": 8018, "text": "PHP" }, { "code": null, "e": 8033, "s": 8022, "text": "Javascript" }, { "code": "// C++ program for implementation// of Sieve of Atkin#include <bits/stdc++.h>using namespace std; // Function to generate primes// till limit using Sieve of Atkinvoid SieveOfAtkin(int limit){ // Initialise the sieve array // with initial false values bool sieve[limit]; for (int i = 0; i <= limit; i++) sieve[i] = false; // 2 and 3 are known to be prime if (limit > 2) sieve[2] = true; if (limit > 3) sieve[3] = true; /* Mark sieve[n] is true if one of the following is true: a) n = (4*x*x)+(y*y) has odd number of solutions, i.e., there exist odd number of distinct pairs (x, y) that satisfy the equation and n % 12 = 1 or n % 12 = 5. b) n = (3*x*x)+(y*y) has odd number of solutions and n % 12 = 7 c) n = (3*x*x)-(y*y) has odd number of solutions, x > y and n % 12 = 11 */ for (int x = 1; x * x <= limit; x++) { for (int y = 1; y * y <= limit; y++) { // Condition 1 int n = (4 * x * x) + (y * y); if (n <= limit && (n % 12 == 1 || n % 12 == 5)) sieve[n] ^= true; // Condition 2 n = (3 * x * x) + (y * y); if (n <= limit && n % 12 == 7) sieve[n] ^= true; // Condition 3 n = (3 * x * x) - (y * y); if (x > y && n <= limit && n % 12 == 11) sieve[n] ^= true; } } // Mark all multiples // of squares as non-prime for (int r = 5; r * r <= limit; r++) { if (sieve[r]) { for (int i = r * r; i <= limit; i += r * r) sieve[i] = false; } } // Print primes using sieve[] for (int a = 1; a <= limit; a++) if (sieve[a]) cout << a << \" \"; cout << \"\\n\";} // Driver programint main(void){ int limit = 20; SieveOfAtkin(limit); return 0;}", "e": 9943, "s": 8033, "text": null }, { "code": "// Java program for implementation// of Sieve of Atkinclass GFG { static void SieveOfAtkin(int limit) { // 2 and 3 are known to be prime if (limit > 2) System.out.print(2 + \" \"); if (limit > 3) System.out.print(3 + \" \"); // Initialise the sieve array with // false values boolean sieve[] = new boolean[limit+1]; for (int i = 0; i <= limit; i++) sieve[i] = false; /* Mark sieve[n] is true if one of the following is true: a) n = (4*x*x)+(y*y) has odd number of solutions, i.e., there exist odd number of distinct pairs (x, y) that satisfy the equation and n % 12 = 1 or n % 12 = 5. b) n = (3*x*x)+(y*y) has odd number of solutions and n % 12 = 7 c) n = (3*x*x)-(y*y) has odd number of solutions, x > y and n % 12 = 11 */ for (int x = 1; x * x <= limit; x++) { for (int y = 1; y * y <= limit; y++) { // Main part of Sieve of Atkin int n = (4 * x * x) + (y * y); if (n <= limit && (n % 12 == 1 || n % 12 == 5)) sieve[n] ^= true; n = (3 * x * x) + (y * y); if (n <= limit && n % 12 == 7) sieve[n] ^= true; n = (3 * x * x) - (y * y); if (x > y && n <= limit && n % 12 == 11) sieve[n] ^= true; } } // Mark all multiples of squares as // non-prime for (int r = 5; r * r <= limit; r++) { if (sieve[r]) { for (int i = r * r; i <= limit; i += r * r) sieve[i] = false; } } // Print primes using sieve[] for (int a = 5; a <= limit; a++) if (sieve[a]) System.out.print(a + \" \"); System.out.println(); } // Driver code public static void main(String[] args) { int limit = 20; SieveOfAtkin(limit); }} // This code is contributed by Anant Agarwal.", "e": 12089, "s": 9943, "text": null }, { "code": "# Python 3 program for# implementation of# Sieve of Atkin def SieveOfAtkin(limit): # 2 and 3 are known # to be prime if limit > 2: print(2, end=\" \") if limit > 3: print(3, end=\" \") # Initialise the sieve # array with False values sieve = [False] * (limit + 1) for i in range(0, limit + 1): sieve[i] = False '''Mark sieve[n] is True if one of the following is True: a) n = (4*x*x)+(y*y) has odd number of solutions, i.e., there exist odd number of distinct pairs (x, y) that satisfy the equation and n % 12 = 1 or n % 12 = 5. b) n = (3*x*x)+(y*y) has odd number of solutions and n % 12 = 7 c) n = (3*x*x)-(y*y) has odd number of solutions, x > y and n % 12 = 11 ''' x = 1 while x * x <= limit: y = 1 while y * y <= limit: # Main part of # Sieve of Atkin n = (4 * x * x) + (y * y) if (n <= limit and (n % 12 == 1 or n % 12 == 5)): sieve[n] ^= True n = (3 * x * x) + (y * y) if n <= limit and n % 12 == 7: sieve[n] ^= True n = (3 * x * x) - (y * y) if (x > y and n <= limit and n % 12 == 11): sieve[n] ^= True y += 1 x += 1 # Mark all multiples of # squares as non-prime r = 5 while r * r <= limit: if sieve[r]: for i in range(r * r, limit+1, r * r): sieve[i] = False r += 1 # Print primes # using sieve[] for a in range(5, limit+1): if sieve[a]: print(a, end=\" \") # Driver Codelimit = 20SieveOfAtkin(limit) # This code is contributed# by Smitha", "e": 13843, "s": 12089, "text": null }, { "code": "// C# program for implementation of Sieve// of Atkinusing System; class GFG { static void SieveOfAtkin(int limit) { // 2 and 3 are known to be prime if (limit > 2) Console.Write(2 + \" \"); if (limit > 3) Console.Write(3 + \" \"); // Initialise the sieve array with // false values bool[] sieve = new bool[limit + 1]; for (int i = 0; i <= limit; i++) sieve[i] = false; /* Mark sieve[n] is true if one of the following is true: a) n = (4*x*x)+(y*y) has odd number of solutions, i.e., there exist odd number of distinct pairs (x, y) that satisfy the equation and n % 12 = 1 or n % 12 = 5. b) n = (3*x*x)+(y*y) has odd number of solutions and n % 12 = 7 c) n = (3*x*x)-(y*y) has odd number of solutions, x > y and n % 12 = 11 */ for (int x = 1; x * x <= limit; x++) { for (int y = 1; y * y <= limit; y++) { // Main part of Sieve of Atkin int n = (4 * x * x) + (y * y); if (n <= limit && (n % 12 == 1 || n % 12 == 5)) sieve[n] ^= true; n = (3 * x * x) + (y * y); if (n <= limit && n % 12 == 7) sieve[n] ^= true; n = (3 * x * x) - (y * y); if (x > y && n <= limit && n % 12 == 11) sieve[n] ^= true; } } // Mark all multiples of squares as // non-prime for (int r = 5; r * r < limit; r++) { if (sieve[r]) { for (int i = r * r; i < limit; i += r * r) sieve[i] = false; } } // Print primes using sieve[] for (int a = 5; a <= limit; a++) if (sieve[a]) Console.Write(a + \" \"); Console.WriteLine(); } // Driver code public static void Main() { int limit = 20; SieveOfAtkin(limit); }} // This code is contributed by nitin mittal", "e": 15970, "s": 13843, "text": null }, { "code": "<?php// PHP program for implementation// of Sieve of Atkin function SieveOfAtkin($limit){ // 2 and 3 are known // to be prime if ($limit > 2) echo 2 , \" \"; if ($limit > 3) echo 3 , \" \"; // Initialise the sieve array // with false values $sieve[$limit+1] = 0; for ($i = 0; $i <= $limit; $i++) $sieve[$i] = false; /* Mark sieve[n] is true if one of the following is true: a) n = (4*x*x)+(y*y) has odd number of solutions, i.e., there exist odd number of distinct pairs (x, y) that satisfy the equation and n % 12 = 1 or n % 12 = 5. b) n = (3*x*x)+(y*y) has odd number of solutions and n % 12 = 7 c) n = (3*x*x)-(y*y) has odd number of solutions, x > y and n % 12 = 11 */ for ($x = 1; $x * $x <= $limit; $x++) { for ($y = 1; $y * $y <= $limit; $y++) { // Main part of Sieve of Atkin $n = (4 * $x * $x) + ($y * $y); if ($n <= $limit && ($n % 12 == 1 || $n % 12 == 5)) $sieve[$n] ^= true; $n = (3 * $x * $x) + ($y * $y); if ($n <= $limit && $n % 12 == 7) $sieve[$n] = true; $n = (3 * $x * $x) - ($y * $y); if ($x > $y && $n <= $limit && $n % 12 == 11) $sieve[$n] ^= true; } } // Mark all multiples of // squares as non-prime for ($r = 5; $r * $r <= $limit; $r++) { if ($sieve[$r]) { for ($i = $r * $r; $i <= $limit; $i += $r * $r) $sieve[$i] = false; } } // Print primes // using sieve[] for ($a = 5; $a <= $limit; $a++) if ($sieve[$a]) echo $a , \" \"; echo \"\\n\";} // Driver Code $limit = 20; SieveOfAtkin($limit); // This code is contributed by nitin mittal.?>", "e": 17851, "s": 15970, "text": null }, { "code": "<script>// Javascript program for implementation// of Sieve of Atkin function SieveOfAtkin(limit){ // 2 and 3 are known // to be prime if (limit > 2) document.write(2 + \" \"); if (limit > 3) document.write(3 + \" \"); // Initialise the sieve array // with false values let sieve = new Array() sieve[limit+1] = 0; for (let i = 0; i <= limit; i++) sieve[i] = false; /* Mark sieve[n] is true if one of the following is true: a) n = (4*x*x)+(y*y) has odd number of solutions, i.e., there exist odd number of distinct pairs (x, y) that satisfy the equation and n % 12 = 1 or n % 12 = 5. b) n = (3*x*x)+(y*y) has odd number of solutions and n % 12 = 7 c) n = (3*x*x)-(y*y) has odd number of solutions, x > y and n % 12 = 11 */ for (let x = 1; x * x <= limit; x++) { for (let y = 1; y * y <= limit; y++) { // Main part of Sieve of Atkin let n = (4 * x * x) + (y * y); if (n <= limit && (n % 12 == 1 || n % 12 == 5)) sieve[n] ^= true; n = (3 * x * x) + (y * y); if (n <= limit && n % 12 == 7) sieve[n] = true; n = (3 * x * x) - (y * y); if (x > y && n <= limit && n % 12 == 11) sieve[n] ^= true; } } // Mark all multiples of // squares as non-prime for (let r = 5; r * r <= limit; r++) { if (sieve[r]) { for (i = r * r; i <= limit; i += r * r) sieve[i] = false; } } // Print primes // using sieve[] for (let a = 5; a <= limit; a++) if (sieve[a]) document.write(a , \" \"); document.write(\"<br>\");} // Driver Code let limit = 20; SieveOfAtkin(limit); // This code is contributed by nitin gfgking </script>", "e": 19805, "s": 17851, "text": null }, { "code": null, "e": 19826, "s": 19805, "text": "2 3 5 7 11 13 17 19 " }, { "code": null, "e": 19998, "s": 19826, "text": " This article is contributed by Anuj Rathore. Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above. " }, { "code": null, "e": 20011, "s": 19998, "text": "nitin mittal" }, { "code": null, "e": 20032, "s": 20011, "text": "Smitha Dinesh Semwal" }, { "code": null, "e": 20040, "s": 20032, "text": "gfgking" }, { "code": null, "e": 20056, "s": 20040, "text": "saurabh1990aror" }, { "code": null, "e": 20067, "s": 20056, "text": "adtimokhin" }, { "code": null, "e": 20081, "s": 20067, "text": "RishabhPrabhu" }, { "code": null, "e": 20094, "s": 20081, "text": "Prime Number" }, { "code": null, "e": 20100, "s": 20094, "text": "sieve" }, { "code": null, "e": 20113, "s": 20100, "text": "Mathematical" }, { "code": null, "e": 20126, "s": 20113, "text": "Mathematical" }, { "code": null, "e": 20139, "s": 20126, "text": "Prime Number" }, { "code": null, "e": 20145, "s": 20139, "text": "sieve" } ]
Inheritance and Friendship in C++
17 Dec, 2021 Inheritance in C++: This is an OOPS concept. It allows creating classes that are derived from other classes so that they automatically include some of the functionality of its base class and some functionality of its own. (See this article for reference) Friendship in C++: Usually, private and protected members of a class cannot be accessed from outside the same class in which they are declared. However, a friend class has the access to the protected and private members of the first one. Classes that are ‘friends’ can access not just the public members, but the private and protected members too. (See this article for reference) Difference between Inheritance and Friendship in C++: In C++, friendship is not inherited. If a base class has a friend function, then the function doesn’t become a friend of the derived class(es). For example, the following program prints an error because the show() which is a friend of base class A tries to access private data of derived class B. C++ // CPP Program to demonstrate the relation between// Inheritance and Friendship#include <iostream>using namespace std; // Parent Classclass A {protected: int x; public: A() { x = 0; } friend void show();}; // Child Classclass B : public A {private: int y; public: B() { y = 0; }}; void show(){ B b; cout << "The default value of A::x = " << b.x; // Can't access private member declared in class 'B' cout << "The default value of B::y = " << b.y;} int main(){ show(); getchar(); return 0;} Output prog.cpp: In function ‘void show()’: prog.cpp:19:9: error: ‘int B::y’ is private int y; ^ prog.cpp:31:49: error: within this context cout << "The default value of B::y = " << b.y; ^ Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above. vikas_m07 GauthamRubyseven anshikajain26 C++ CPP Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Set in C++ Standard Template Library (STL) vector erase() and clear() in C++ unordered_map in C++ STL Substring in C++ C++ Classes and Objects Sorting a vector in C++ Priority Queue in C++ Standard Template Library (STL) 2D Vector In C++ With User Defined Size C++ Data Types Templates in C++ with Examples
[ { "code": null, "e": 52, "s": 24, "text": "\n17 Dec, 2021" }, { "code": null, "e": 307, "s": 52, "text": "Inheritance in C++: This is an OOPS concept. It allows creating classes that are derived from other classes so that they automatically include some of the functionality of its base class and some functionality of its own. (See this article for reference)" }, { "code": null, "e": 688, "s": 307, "text": "Friendship in C++: Usually, private and protected members of a class cannot be accessed from outside the same class in which they are declared. However, a friend class has the access to the protected and private members of the first one. Classes that are ‘friends’ can access not just the public members, but the private and protected members too. (See this article for reference)" }, { "code": null, "e": 887, "s": 688, "text": "Difference between Inheritance and Friendship in C++: In C++, friendship is not inherited. If a base class has a friend function, then the function doesn’t become a friend of the derived class(es). " }, { "code": null, "e": 1041, "s": 887, "text": "For example, the following program prints an error because the show() which is a friend of base class A tries to access private data of derived class B. " }, { "code": null, "e": 1045, "s": 1041, "text": "C++" }, { "code": "// CPP Program to demonstrate the relation between// Inheritance and Friendship#include <iostream>using namespace std; // Parent Classclass A {protected: int x; public: A() { x = 0; } friend void show();}; // Child Classclass B : public A {private: int y; public: B() { y = 0; }}; void show(){ B b; cout << \"The default value of A::x = \" << b.x; // Can't access private member declared in class 'B' cout << \"The default value of B::y = \" << b.y;} int main(){ show(); getchar(); return 0;}", "e": 1578, "s": 1045, "text": null }, { "code": null, "e": 1585, "s": 1578, "text": "Output" }, { "code": null, "e": 1831, "s": 1585, "text": "prog.cpp: In function ‘void show()’:\nprog.cpp:19:9: error: ‘int B::y’ is private\n int y;\n ^\nprog.cpp:31:49: error: within this context\n cout << \"The default value of B::y = \" << b.y;\n ^" }, { "code": null, "e": 1956, "s": 1831, "text": "Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above." }, { "code": null, "e": 1966, "s": 1956, "text": "vikas_m07" }, { "code": null, "e": 1983, "s": 1966, "text": "GauthamRubyseven" }, { "code": null, "e": 1997, "s": 1983, "text": "anshikajain26" }, { "code": null, "e": 2001, "s": 1997, "text": "C++" }, { "code": null, "e": 2005, "s": 2001, "text": "CPP" }, { "code": null, "e": 2103, "s": 2005, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 2146, "s": 2103, "text": "Set in C++ Standard Template Library (STL)" }, { "code": null, "e": 2180, "s": 2146, "text": "vector erase() and clear() in C++" }, { "code": null, "e": 2205, "s": 2180, "text": "unordered_map in C++ STL" }, { "code": null, "e": 2222, "s": 2205, "text": "Substring in C++" }, { "code": null, "e": 2246, "s": 2222, "text": "C++ Classes and Objects" }, { "code": null, "e": 2270, "s": 2246, "text": "Sorting a vector in C++" }, { "code": null, "e": 2324, "s": 2270, "text": "Priority Queue in C++ Standard Template Library (STL)" }, { "code": null, "e": 2364, "s": 2324, "text": "2D Vector In C++ With User Defined Size" }, { "code": null, "e": 2379, "s": 2364, "text": "C++ Data Types" } ]
Deploying Node.js Applications
11 May, 2022 To show how to deploy a nodejs app, we are first going to create a sample application for a better understanding of the process. I have created a directory/folder “example” for my sample project.Before procceding, make sure you have installed nodejs and git on your system. Now, open the command line and cd inside the example(or whatever is the name of your project folder) directoryFollow the following steps to create the sample application for this tutorialSTEP 1: Create a “package.json” file using the following command npm init STEP 2: Create a file called “app.js” inside your project folderSTEP 3: Create a html file “head.html”Fill the file with the following content This will be the homepage of our app which is connected to another page via hyperlink. html <!DOCTYPE html><html><head> <title>Hello World</title></head><body> <h1>This is the Homepage</h1> <p><a href="/tailPage">Go to Next Page</a></p> </body> STEP 4: Create another html file “tail.html” Content of tail.html is html <!DOCTYPE html><html><head> <title>Hello World</title></head><body> <h1>WORKING</h1> </body> STEP 5: Open “app.js” file created in step 2 and copy paste the following code in it javascript var http = require('http');var fs = require('fs'); // to get data from html file http.createServer(function (req, res) { res.writeHead(200, { 'Content-Type': 'text/html' }); // req.url stores the path in the url var url = req.url; if (url === "/") {// fs.readFile looks for the HTML file// the first parameter is the path to the HTML page// the second is the call back function// if no file is found the function gives an error// if the file is successfully found, the content of the file are contained in pgres fs.readFile("head.html", function (err, pgres) { if (err) res.write("HEAD.HTML NOT FOUND"); else { // The following 3 lines // are responsible for sending the html file // and ends the response process res.writeHead(200, { 'Content-Type': 'text/html' }); res.write(pgres); res.end(); } }); } else if (url === "/tailPage") { fs.readFile("tail.html", function (err, pgres) { if (err) res.write("TAIL.HTML NOT FOUND"); else { res.writeHead(200, { 'Content-Type': 'text/html' }); res.write(pgres); res.end(); } }); } }).listen(3000, function () { console.log("SERVER STARTED PORT: 3000");}); javascript var http = require('http');var fs = require('fs'); // to get data from html file http.createServer(function (req, res) { res.writeHead(200, { 'Content-Type': 'text/html' }); // req.url stores the path in the url var url = req.url; if (url === "/") {// fs.readFile looks for the HTML file// the first parameter is the path to the HTML page// the second is the call back function// if no file is found the function gives an error// if the file is successfully found, the content of the file are contained in pgres fs.readFile("head.html", function (err, pgres) { if (err) res.write("HEAD.HTML NOT FOUND"); else { // The following 3 lines // are responsible for sending the html file // and ends the response process res.writeHead(200, { 'Content-Type': 'text/html' }); res.write(pgres); res.end(); } }); } else if (url === "/tailPage") { fs.readFile("tail.html", function (err, pgres) { if (err) res.write("TAIL.HTML NOT FOUND"); else { res.writeHead(200, { 'Content-Type': 'text/html' }); res.write(pgres); res.end(); } }); } }).listen(3000, function () { console.log("SERVER STARTED PORT: 3000");}); Now, the above code displays the “head.html” file as the homepage which is connected to “tail.html”STEP 6: Open the terminal again and write the following command to run the server node app.js To see your application running, type “localhost:3000” in your browser as URL.We have successfully created the sample application, we are now going to deploy it on the web.There’s are many cloud platforms like AWS, Heroku, Digital Ocean, etc. Steps to Deploy Sample Application For this example, we are going to use Heroku since it’s easy to use and you can use it to test your apps for free. The free versions have some limitations thus if you want to use the site for commercial business it is recommended to get a paid package. Since this is a tutorial we gonna use the free version.NOTE: ALL THE COMMAND ARE PERFORMED INSIDE THE DIRECTORY/FOLDER WHICH CONTAINS YOUR PROJECTSTEP 1: Go to https://www.heroku.com/ and register.STEP 2: After completing the registration process, login and go to https://dashboard.heroku.com/appsBefore Proceeding any further, make sure you have installed the latest version of Git on your PC.STEP 3: Go to Getting Started on Heroku with Node.js and download the Heroku Cli for your system.You can check if Heroku CLI is successfully installed or not by typing the command heroku -v it should look like this STEP 4: Type heroku login in the command line Press any key to continue, it will open a new tab in your browser asking you to login in your Heroku account Click on Log in BottomAfter you successfully log in, the command line will look like this ( Heroku might not connect to Git bash, so use Command Prompt or terminal if it’s taking very long to connect i.e. if you were using git bash)STEP 5: Now, make sure we are using Git in the top level directory of our app. We can check if the directory have Git or not by the command git status To make it a git directory, type the command git init Now, type git add . in command line. (Ignore the warning for now)Now, we need to commit the files we have added to git. Type git commit -m "initial commit" STEP 6: Create heruko app by command heroku create This will create a git remote which is connected to our local git repositorySTEP 7: Type git push heroku master to deploy the app on heroku serverSTEP 8: After deploying the app type heroku ps:scale web=1 to make sure one instance of app is runningSTEP 9: Type heroku open this will open a app in your browser.Now, you might be getting a screen like this Go to command line and type heroku logs to check for error. It helps to debug the application. It says “npm ERR! missing script: start“To fix this problem, we need to set up a start script, the start script tells the server to run “node app.js” after installing the packages.STEP 10: To setup the start script, open package.json inside the example folder and type ‘ “start”: “node app.js” ‘ inside the “scripts” tag. See the image ( DON’T FORGET THE COMMA ‘, ‘ )STEP 11: Type the following command in command line We need to push the app to Heroku every time we make changes in it. git add . git commit -m "another commit" git push heroku master heroku open STEP 12: There’s still a problem.The problem is still not fixed. We are using PORT: 3000 but Heroku doesn’t. Heroku uses a dynamic port, we cannot fix it to 3000. If we want our application to work on Heroku we need to add the following line in the app.js file.listen(process.env.PORT || 3000, function(...));app.js will now look like this javascript // Write Javascript code here var http = require('http');var fs = require('fs'); // to get data from html file http.createServer(function (req, res) { res.writeHead(200, { 'Content-Type': 'text/html' }); // req.url stores the path in the url var url = req.url; if (url === "/") {// fs.readFile looks for the html file// the first parameter is the path to the html page// the second is the call back function// if no file is found the function gives an err// if the file is successfully found, the content of the file are contained in pgres fs.readFile("head.html", function (err, pgres) { if (err) res.write("HEAD.HTML NOT FOUND"); else { // The following 3 lines // are responsible for sending the html file // and ends the response process res.writeHead(200, { 'Content-Type': 'text/html' }); res.write(pgres); res.end(); } }); } else if (url === "/tailPage") { fs.readFile("tail.html", function (err, pgres) { if (err) res.write("TAIL.HTML NOT FOUND"); else { res.writeHead(200, { 'Content-Type': 'text/html' }); res.write(pgres); res.end(); } }); } }).listen(process.env.PORT || 3000, function () { console.log("SERVER STARTED PORT: 3000");}); STEP 13: Again type git add . git commit -m "another commit" git push heroku master heroku open Congratulations, you have successfully deployed your first web application.NOTE: 1. If your application uses MongoDB then you will have to deploy MongoDB server separately on some other cloud platform. 2. I was having some problem connected git bash to Heroku that’s why I switched to CMD in between. So, I recommend not to use Git Bash. Akanksha_Rai sweetyty Heroku Cloud Picked Node.js 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": "\n11 May, 2022" }, { "code": null, "e": 555, "s": 28, "text": "To show how to deploy a nodejs app, we are first going to create a sample application for a better understanding of the process. I have created a directory/folder “example” for my sample project.Before procceding, make sure you have installed nodejs and git on your system. Now, open the command line and cd inside the example(or whatever is the name of your project folder) directoryFollow the following steps to create the sample application for this tutorialSTEP 1: Create a “package.json” file using the following command " }, { "code": null, "e": 564, "s": 555, "text": "npm init" }, { "code": null, "e": 797, "s": 566, "text": "STEP 2: Create a file called “app.js” inside your project folderSTEP 3: Create a html file “head.html”Fill the file with the following content This will be the homepage of our app which is connected to another page via hyperlink. " }, { "code": null, "e": 802, "s": 797, "text": "html" }, { "code": "<!DOCTYPE html><html><head> <title>Hello World</title></head><body> <h1>This is the Homepage</h1> <p><a href=\"/tailPage\">Go to Next Page</a></p> </body>", "e": 971, "s": 802, "text": null }, { "code": null, "e": 1042, "s": 971, "text": "STEP 4: Create another html file “tail.html” Content of tail.html is " }, { "code": null, "e": 1047, "s": 1042, "text": "html" }, { "code": "<!DOCTYPE html><html><head> <title>Hello World</title></head><body> <h1>WORKING</h1> </body>", "e": 1149, "s": 1047, "text": null }, { "code": null, "e": 1236, "s": 1149, "text": "STEP 5: Open “app.js” file created in step 2 and copy paste the following code in it " }, { "code": null, "e": 1247, "s": 1236, "text": "javascript" }, { "code": "var http = require('http');var fs = require('fs'); // to get data from html file http.createServer(function (req, res) { res.writeHead(200, { 'Content-Type': 'text/html' }); // req.url stores the path in the url var url = req.url; if (url === \"/\") {// fs.readFile looks for the HTML file// the first parameter is the path to the HTML page// the second is the call back function// if no file is found the function gives an error// if the file is successfully found, the content of the file are contained in pgres fs.readFile(\"head.html\", function (err, pgres) { if (err) res.write(\"HEAD.HTML NOT FOUND\"); else { // The following 3 lines // are responsible for sending the html file // and ends the response process res.writeHead(200, { 'Content-Type': 'text/html' }); res.write(pgres); res.end(); } }); } else if (url === \"/tailPage\") { fs.readFile(\"tail.html\", function (err, pgres) { if (err) res.write(\"TAIL.HTML NOT FOUND\"); else { res.writeHead(200, { 'Content-Type': 'text/html' }); res.write(pgres); res.end(); } }); } }).listen(3000, function () { console.log(\"SERVER STARTED PORT: 3000\");});", "e": 2637, "s": 1247, "text": null }, { "code": null, "e": 2648, "s": 2637, "text": "javascript" }, { "code": "var http = require('http');var fs = require('fs'); // to get data from html file http.createServer(function (req, res) { res.writeHead(200, { 'Content-Type': 'text/html' }); // req.url stores the path in the url var url = req.url; if (url === \"/\") {// fs.readFile looks for the HTML file// the first parameter is the path to the HTML page// the second is the call back function// if no file is found the function gives an error// if the file is successfully found, the content of the file are contained in pgres fs.readFile(\"head.html\", function (err, pgres) { if (err) res.write(\"HEAD.HTML NOT FOUND\"); else { // The following 3 lines // are responsible for sending the html file // and ends the response process res.writeHead(200, { 'Content-Type': 'text/html' }); res.write(pgres); res.end(); } }); } else if (url === \"/tailPage\") { fs.readFile(\"tail.html\", function (err, pgres) { if (err) res.write(\"TAIL.HTML NOT FOUND\"); else { res.writeHead(200, { 'Content-Type': 'text/html' }); res.write(pgres); res.end(); } }); } }).listen(3000, function () { console.log(\"SERVER STARTED PORT: 3000\");});", "e": 4038, "s": 2648, "text": null }, { "code": null, "e": 4221, "s": 4038, "text": "Now, the above code displays the “head.html” file as the homepage which is connected to “tail.html”STEP 6: Open the terminal again and write the following command to run the server " }, { "code": null, "e": 4233, "s": 4221, "text": "node app.js" }, { "code": null, "e": 4479, "s": 4235, "text": "To see your application running, type “localhost:3000” in your browser as URL.We have successfully created the sample application, we are now going to deploy it on the web.There’s are many cloud platforms like AWS, Heroku, Digital Ocean, etc. " }, { "code": null, "e": 4514, "s": 4479, "text": "Steps to Deploy Sample Application" }, { "code": null, "e": 5342, "s": 4514, "text": "For this example, we are going to use Heroku since it’s easy to use and you can use it to test your apps for free. The free versions have some limitations thus if you want to use the site for commercial business it is recommended to get a paid package. Since this is a tutorial we gonna use the free version.NOTE: ALL THE COMMAND ARE PERFORMED INSIDE THE DIRECTORY/FOLDER WHICH CONTAINS YOUR PROJECTSTEP 1: Go to https://www.heroku.com/ and register.STEP 2: After completing the registration process, login and go to https://dashboard.heroku.com/appsBefore Proceeding any further, make sure you have installed the latest version of Git on your PC.STEP 3: Go to Getting Started on Heroku with Node.js and download the Heroku Cli for your system.You can check if Heroku CLI is successfully installed or not by typing the command " }, { "code": null, "e": 5352, "s": 5342, "text": "heroku -v" }, { "code": null, "e": 5378, "s": 5352, "text": "it should look like this " }, { "code": null, "e": 5393, "s": 5378, "text": "STEP 4: Type " }, { "code": null, "e": 5406, "s": 5393, "text": "heroku login" }, { "code": null, "e": 5427, "s": 5406, "text": "in the command line " }, { "code": null, "e": 5537, "s": 5427, "text": "Press any key to continue, it will open a new tab in your browser asking you to login in your Heroku account " }, { "code": null, "e": 5628, "s": 5537, "text": "Click on Log in BottomAfter you successfully log in, the command line will look like this " }, { "code": null, "e": 5912, "s": 5628, "text": "( Heroku might not connect to Git bash, so use Command Prompt or terminal if it’s taking very long to connect i.e. if you were using git bash)STEP 5: Now, make sure we are using Git in the top level directory of our app. We can check if the directory have Git or not by the command " }, { "code": null, "e": 5923, "s": 5912, "text": "git status" }, { "code": null, "e": 5972, "s": 5925, "text": "To make it a git directory, type the command " }, { "code": null, "e": 5981, "s": 5972, "text": "git init" }, { "code": null, "e": 5995, "s": 5983, "text": "Now, type " }, { "code": null, "e": 6006, "s": 5995, "text": "git add . " }, { "code": null, "e": 6024, "s": 6006, "text": "in command line. " }, { "code": null, "e": 6114, "s": 6024, "text": "(Ignore the warning for now)Now, we need to commit the files we have added to git. Type " }, { "code": null, "e": 6145, "s": 6114, "text": "git commit -m \"initial commit\"" }, { "code": null, "e": 6186, "s": 6147, "text": "STEP 6: Create heruko app by command " }, { "code": null, "e": 6200, "s": 6186, "text": "heroku create" }, { "code": null, "e": 6293, "s": 6202, "text": "This will create a git remote which is connected to our local git repositorySTEP 7: Type " }, { "code": null, "e": 6316, "s": 6293, "text": "git push heroku master" }, { "code": null, "e": 6389, "s": 6316, "text": "to deploy the app on heroku serverSTEP 8: After deploying the app type " }, { "code": null, "e": 6412, "s": 6389, "text": "heroku ps:scale web=1 " }, { "code": null, "e": 6470, "s": 6412, "text": "to make sure one instance of app is runningSTEP 9: Type " }, { "code": null, "e": 6483, "s": 6470, "text": "heroku open " }, { "code": null, "e": 6566, "s": 6483, "text": "this will open a app in your browser.Now, you might be getting a screen like this " }, { "code": null, "e": 6596, "s": 6566, "text": "Go to command line and type " }, { "code": null, "e": 6609, "s": 6596, "text": "heroku logs " }, { "code": null, "e": 6665, "s": 6609, "text": "to check for error. It helps to debug the application. " }, { "code": null, "e": 7003, "s": 6665, "text": "It says “npm ERR! missing script: start“To fix this problem, we need to set up a start script, the start script tells the server to run “node app.js” after installing the packages.STEP 10: To setup the start script, open package.json inside the example folder and type ‘ “start”: “node app.js” ‘ inside the “scripts” tag. See the image " }, { "code": null, "e": 7155, "s": 7003, "text": "( DON’T FORGET THE COMMA ‘, ‘ )STEP 11: Type the following command in command line We need to push the app to Heroku every time we make changes in it. " }, { "code": null, "e": 7231, "s": 7155, "text": "git add .\ngit commit -m \"another commit\"\ngit push heroku master\nheroku open" }, { "code": null, "e": 7572, "s": 7231, "text": "STEP 12: There’s still a problem.The problem is still not fixed. We are using PORT: 3000 but Heroku doesn’t. Heroku uses a dynamic port, we cannot fix it to 3000. If we want our application to work on Heroku we need to add the following line in the app.js file.listen(process.env.PORT || 3000, function(...));app.js will now look like this " }, { "code": null, "e": 7583, "s": 7572, "text": "javascript" }, { "code": "// Write Javascript code here var http = require('http');var fs = require('fs'); // to get data from html file http.createServer(function (req, res) { res.writeHead(200, { 'Content-Type': 'text/html' }); // req.url stores the path in the url var url = req.url; if (url === \"/\") {// fs.readFile looks for the html file// the first parameter is the path to the html page// the second is the call back function// if no file is found the function gives an err// if the file is successfully found, the content of the file are contained in pgres fs.readFile(\"head.html\", function (err, pgres) { if (err) res.write(\"HEAD.HTML NOT FOUND\"); else { // The following 3 lines // are responsible for sending the html file // and ends the response process res.writeHead(200, { 'Content-Type': 'text/html' }); res.write(pgres); res.end(); } }); } else if (url === \"/tailPage\") { fs.readFile(\"tail.html\", function (err, pgres) { if (err) res.write(\"TAIL.HTML NOT FOUND\"); else { res.writeHead(200, { 'Content-Type': 'text/html' }); res.write(pgres); res.end(); } }); } }).listen(process.env.PORT || 3000, function () { console.log(\"SERVER STARTED PORT: 3000\");});", "e": 9021, "s": 7583, "text": null }, { "code": null, "e": 9042, "s": 9021, "text": "STEP 13: Again type " }, { "code": null, "e": 9118, "s": 9042, "text": "git add .\ngit commit -m \"another commit\"\ngit push heroku master\nheroku open" }, { "code": null, "e": 9461, "s": 9122, "text": "Congratulations, you have successfully deployed your first web application.NOTE: 1. If your application uses MongoDB then you will have to deploy MongoDB server separately on some other cloud platform. 2. I was having some problem connected git bash to Heroku that’s why I switched to CMD in between. So, I recommend not to use Git Bash. " }, { "code": null, "e": 9474, "s": 9461, "text": "Akanksha_Rai" }, { "code": null, "e": 9483, "s": 9474, "text": "sweetyty" }, { "code": null, "e": 9496, "s": 9483, "text": "Heroku Cloud" }, { "code": null, "e": 9503, "s": 9496, "text": "Picked" }, { "code": null, "e": 9511, "s": 9503, "text": "Node.js" }, { "code": null, "e": 9528, "s": 9511, "text": "Web Technologies" } ]
ReactJS | PropTypes
20 Jan, 2021 In our previous articles on Props, we had seen how to pass information to any Component using props. We had passed different types of information like integers, strings, arrays, etc. as props to the components. So, let’s recall the process of how we were passing these props to a component. We can either create defaultProps or have passed props directly as attributes to the components. We were passing props from outside a component and using them inside that component. But did we have checked what type of values we are getting inside our Component through props? No, we do not. But then also everything worked fine. It’s totally upon us whether we validate the data we are getting using props inside a Component or not. But for larger Apps, it is always a good practice to validate the data we are getting through props. This will help in debugging and also helps in avoiding bugs in the future. Let us see how to do this. propTypes in React Before the release of React 15.5.0 version propTypes is available in the react package but in later versions of React have to add a dependency in your project. You can add the dependency in your project by using the command given below: npm install prop-types --save We can use the propType for validating any data we are receiving from props. But before using it we will have to import it. Add the below line at the top of your index.js file : import PropTypes from 'prop-types'; Once we have imported propTypes we are ready to work with them. Just like defaultProps, propTypes are also objects where keys are the prop names and values are their types. Below syntax shows how to use propTypes: ComponentClassName.propTypes{ propName1 : PropTypes.string, propName2 : PropTypes.bool, propName3 : PropTypes.array, . . . . propNamen : PropTypes.anyOtherType } In the above Syntax, the ComponentClassName is the name of the class of Component, anyOtherType can be any type that we are allowed to pass as props. For the props which do not validate the type of data specified by propTypes, a warning on the console will occur. Let us see a complete program that uses propTypes for validation for a better understanding: javascript import PropTypes from 'prop-types';import React from 'react';import ReactDOM from 'react-dom'; // Componentclass ComponentExample extends React.Component{ render(){ return( <div> {/* printing all props */} <h1> {this.props.arrayProp} <br /> {this.props.stringProp} <br /> {this.props.numberProp} <br /> {this.props.boolProp} <br /> </h1> </div> ); }} // Validating prop typesComponentExample.propTypes = { arrayProp: PropTypes.array, stringProp: PropTypes.string, numberProp: PropTypes.number, boolProp: PropTypes.bool,} // Creating default propsComponentExample.defaultProps = { arrayProp: ['Ram', 'Shyam', 'Raghav'], stringProp: "GeeksforGeeks", numberProp: "10", boolProp: true,} ReactDOM.render( <ComponentExample />, document.getElementById("root")); Output: You can see in the above program that we are passing the prop named numberProp as a string but validating it as a number. Still, everything is rendered perfectly on the browser but our browser console has a warning message. This message clearly tells us that the prop named numberProp was expected to contain a numeric value but instead a string value is passed. You can go to the official doc of ReactJS to see all the valid types a prop can take.Note: In recent versions of React the React.PropTypes is moved to a different package, and we will have to install that package separately in order to use it. Please go to https://www.npmjs.com/package/prop-types link for installation instructions. YashRajBothra shubhamyadav4 react-js Web Technologies Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. 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 ? Remove elements from a JavaScript Array REST API (Introduction) Node.js fs.readFileSync() Method How to set the default value for an HTML <select> element ? How to create footer to stay at the bottom of a Web page?
[ { "code": null, "e": 52, "s": 24, "text": "\n20 Jan, 2021" }, { "code": null, "e": 981, "s": 52, "text": "In our previous articles on Props, we had seen how to pass information to any Component using props. We had passed different types of information like integers, strings, arrays, etc. as props to the components. So, let’s recall the process of how we were passing these props to a component. We can either create defaultProps or have passed props directly as attributes to the components. We were passing props from outside a component and using them inside that component. But did we have checked what type of values we are getting inside our Component through props? No, we do not. But then also everything worked fine. It’s totally upon us whether we validate the data we are getting using props inside a Component or not. But for larger Apps, it is always a good practice to validate the data we are getting through props. This will help in debugging and also helps in avoiding bugs in the future. Let us see how to do this. " }, { "code": null, "e": 1000, "s": 981, "text": "propTypes in React" }, { "code": null, "e": 1237, "s": 1000, "text": "Before the release of React 15.5.0 version propTypes is available in the react package but in later versions of React have to add a dependency in your project. You can add the dependency in your project by using the command given below:" }, { "code": null, "e": 1267, "s": 1237, "text": "npm install prop-types --save" }, { "code": null, "e": 1447, "s": 1267, "text": "We can use the propType for validating any data we are receiving from props. But before using it we will have to import it. Add the below line at the top of your index.js file : " }, { "code": null, "e": 1483, "s": 1447, "text": "import PropTypes from 'prop-types';" }, { "code": null, "e": 1699, "s": 1483, "text": "Once we have imported propTypes we are ready to work with them. Just like defaultProps, propTypes are also objects where keys are the prop names and values are their types. Below syntax shows how to use propTypes: " }, { "code": null, "e": 1898, "s": 1699, "text": "ComponentClassName.propTypes{\n \n propName1 : PropTypes.string,\n propName2 : PropTypes.bool,\n propName3 : PropTypes.array,\n .\n .\n .\n .\n propNamen : PropTypes.anyOtherType\n}" }, { "code": null, "e": 2257, "s": 1898, "text": "In the above Syntax, the ComponentClassName is the name of the class of Component, anyOtherType can be any type that we are allowed to pass as props. For the props which do not validate the type of data specified by propTypes, a warning on the console will occur. Let us see a complete program that uses propTypes for validation for a better understanding: " }, { "code": null, "e": 2268, "s": 2257, "text": "javascript" }, { "code": "import PropTypes from 'prop-types';import React from 'react';import ReactDOM from 'react-dom'; // Componentclass ComponentExample extends React.Component{ render(){ return( <div> {/* printing all props */} <h1> {this.props.arrayProp} <br /> {this.props.stringProp} <br /> {this.props.numberProp} <br /> {this.props.boolProp} <br /> </h1> </div> ); }} // Validating prop typesComponentExample.propTypes = { arrayProp: PropTypes.array, stringProp: PropTypes.string, numberProp: PropTypes.number, boolProp: PropTypes.bool,} // Creating default propsComponentExample.defaultProps = { arrayProp: ['Ram', 'Shyam', 'Raghav'], stringProp: \"GeeksforGeeks\", numberProp: \"10\", boolProp: true,} ReactDOM.render( <ComponentExample />, document.getElementById(\"root\"));", "e": 3371, "s": 2268, "text": null }, { "code": null, "e": 3381, "s": 3371, "text": "Output: " }, { "code": null, "e": 4079, "s": 3381, "text": "You can see in the above program that we are passing the prop named numberProp as a string but validating it as a number. Still, everything is rendered perfectly on the browser but our browser console has a warning message. This message clearly tells us that the prop named numberProp was expected to contain a numeric value but instead a string value is passed. You can go to the official doc of ReactJS to see all the valid types a prop can take.Note: In recent versions of React the React.PropTypes is moved to a different package, and we will have to install that package separately in order to use it. Please go to https://www.npmjs.com/package/prop-types link for installation instructions. " }, { "code": null, "e": 4093, "s": 4079, "text": "YashRajBothra" }, { "code": null, "e": 4107, "s": 4093, "text": "shubhamyadav4" }, { "code": null, "e": 4116, "s": 4107, "text": "react-js" }, { "code": null, "e": 4133, "s": 4116, "text": "Web Technologies" }, { "code": null, "e": 4231, "s": 4133, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 4264, "s": 4231, "text": "Installation of Node.js on Linux" }, { "code": null, "e": 4326, "s": 4264, "text": "Top 10 Projects For Beginners To Practice HTML and CSS Skills" }, { "code": null, "e": 4387, "s": 4326, "text": "Difference between var, let and const keywords in JavaScript" }, { "code": null, "e": 4437, "s": 4387, "text": "How to insert spaces/tabs in text using HTML/CSS?" }, { "code": null, "e": 4480, "s": 4437, "text": "How to fetch data from an API in ReactJS ?" }, { "code": null, "e": 4520, "s": 4480, "text": "Remove elements from a JavaScript Array" }, { "code": null, "e": 4544, "s": 4520, "text": "REST API (Introduction)" }, { "code": null, "e": 4577, "s": 4544, "text": "Node.js fs.readFileSync() Method" }, { "code": null, "e": 4637, "s": 4577, "text": "How to set the default value for an HTML <select> element ?" } ]
How to set the state of the CheckBox in C#?
30 Sep, 2021 The CheckBox control is the part of the windows form that is used to take input from the user. Or in other words, CheckBox control allows us to select single or multiple elements from the given list. In CheckBox, you are allowed to get or set the state of the CheckBoxes using the CheckState property of the CheckBox. In CheckBox, there are three different types of states are available: The default value of the CheckState property is Unchecked. In Windows form, you can set this property in two different ways: 1. Design-Time: It is the simplest way to set the CheckState property of a CheckBox using the following steps: Step 1: Create a windows form as shown in the below image: Visual Studio -> File -> New -> Project -> WindowsFormApp Step 2: Drag the CheckBox control from the ToolBox and drop it on the windows form. You can place CheckBox anywhere on the windows form according to your need. Step 3: After drag and drop you will go to the properties of the CheckBox control to set the state of the CheckBox using CheckState property. Output: 2. Run-Time: It is a little bit trickier than the above method. In this method, you can set the CheckState property of a CheckBox programmatically using the following syntax: public System.Windows.Forms.CheckState CheckState { get; set; } Here, the CheckState is used to represent the CheckState enumeration values. It also throws an InvalidEnumArgumentException if the value assigned to the CheckState property does not belong to the CheckState enumeration values. Following steps are used to set the CheckState property of the CheckBox: Step 1: Create a checkbox using the CheckBox() constructor provided by the CheckBox class. // Creating checkbox CheckBox Mycheckbox = new CheckBox(); Step 2: After creating CheckBox, set the CheckState property of the CheckBox provided by the CheckBox class. // Set the CheckState property of the CheckBox Mycheckbox1.CheckState = CheckState.Indeterminate; Step 3: And last add this checkbox control to form using Add() method. // Add this checkbox to form this.Controls.Add(Mycheckbox); Example: C# using System;using System.Collections.Generic;using System.ComponentModel;using System.Data;using System.Drawing;using System.Linq;using System.Text;using System.Threading.Tasks;using System.Windows.Forms; namespace WindowsFormsApp5 { public partial class Form1 : Form { public Form1() { InitializeComponent(); } private void Form1_Load(object sender, EventArgs e) { // Creating and setting the properties of label Label l = new Label(); l.Text = "Select Gender:"; l.Location = new Point(233, 111); // Adding label to form this.Controls.Add(l); // Creating and setting the properties of CheckBox CheckBox Mycheckbox = new CheckBox(); Mycheckbox.Height = 50; Mycheckbox.Width = 100; Mycheckbox.Location = new Point(229, 136); Mycheckbox.Text = "Male"; Mycheckbox.CheckState = CheckState.Unchecked; // Adding checkbox to form this.Controls.Add(Mycheckbox); // Creating and setting the properties of CheckBox CheckBox Mycheckbox1 = new CheckBox(); Mycheckbox1.Height = 50; Mycheckbox1.Width = 100; Mycheckbox1.Location = new Point(230, 174); Mycheckbox1.Text = "Female"; Mycheckbox1.CheckState = CheckState.Indeterminate; // Adding checkbox to form this.Controls.Add(Mycheckbox1); }}} Output: arorakashish0911 C# Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. C# | Multiple inheritance using interfaces Differences Between .NET Core and .NET Framework Extension Method in C# C# | List Class HashSet in C# with Examples C# | .NET Framework (Basic Architecture and Component Stack) Switch Statement in C# Partial Classes in C# Lambda Expressions in C# Hello World in C#
[ { "code": null, "e": 28, "s": 0, "text": "\n30 Sep, 2021" }, { "code": null, "e": 417, "s": 28, "text": "The CheckBox control is the part of the windows form that is used to take input from the user. Or in other words, CheckBox control allows us to select single or multiple elements from the given list. In CheckBox, you are allowed to get or set the state of the CheckBoxes using the CheckState property of the CheckBox. In CheckBox, there are three different types of states are available: " }, { "code": null, "e": 542, "s": 417, "text": "The default value of the CheckState property is Unchecked. In Windows form, you can set this property in two different ways:" }, { "code": null, "e": 655, "s": 542, "text": "1. Design-Time: It is the simplest way to set the CheckState property of a CheckBox using the following steps: " }, { "code": null, "e": 773, "s": 655, "text": "Step 1: Create a windows form as shown in the below image: Visual Studio -> File -> New -> Project -> WindowsFormApp " }, { "code": null, "e": 934, "s": 773, "text": "Step 2: Drag the CheckBox control from the ToolBox and drop it on the windows form. You can place CheckBox anywhere on the windows form according to your need. " }, { "code": null, "e": 1077, "s": 934, "text": "Step 3: After drag and drop you will go to the properties of the CheckBox control to set the state of the CheckBox using CheckState property. " }, { "code": null, "e": 1086, "s": 1077, "text": "Output: " }, { "code": null, "e": 1261, "s": 1086, "text": "2. Run-Time: It is a little bit trickier than the above method. In this method, you can set the CheckState property of a CheckBox programmatically using the following syntax:" }, { "code": null, "e": 1325, "s": 1261, "text": "public System.Windows.Forms.CheckState CheckState { get; set; }" }, { "code": null, "e": 1626, "s": 1325, "text": "Here, the CheckState is used to represent the CheckState enumeration values. It also throws an InvalidEnumArgumentException if the value assigned to the CheckState property does not belong to the CheckState enumeration values. Following steps are used to set the CheckState property of the CheckBox: " }, { "code": null, "e": 1718, "s": 1626, "text": "Step 1: Create a checkbox using the CheckBox() constructor provided by the CheckBox class. " }, { "code": null, "e": 1777, "s": 1718, "text": "// Creating checkbox\nCheckBox Mycheckbox = new CheckBox();" }, { "code": null, "e": 1887, "s": 1777, "text": "Step 2: After creating CheckBox, set the CheckState property of the CheckBox provided by the CheckBox class. " }, { "code": null, "e": 1985, "s": 1887, "text": "// Set the CheckState property of the CheckBox\nMycheckbox1.CheckState = CheckState.Indeterminate;" }, { "code": null, "e": 2057, "s": 1985, "text": "Step 3: And last add this checkbox control to form using Add() method. " }, { "code": null, "e": 2117, "s": 2057, "text": "// Add this checkbox to form\nthis.Controls.Add(Mycheckbox);" }, { "code": null, "e": 2126, "s": 2117, "text": "Example:" }, { "code": null, "e": 2129, "s": 2126, "text": "C#" }, { "code": "using System;using System.Collections.Generic;using System.ComponentModel;using System.Data;using System.Drawing;using System.Linq;using System.Text;using System.Threading.Tasks;using System.Windows.Forms; namespace WindowsFormsApp5 { public partial class Form1 : Form { public Form1() { InitializeComponent(); } private void Form1_Load(object sender, EventArgs e) { // Creating and setting the properties of label Label l = new Label(); l.Text = \"Select Gender:\"; l.Location = new Point(233, 111); // Adding label to form this.Controls.Add(l); // Creating and setting the properties of CheckBox CheckBox Mycheckbox = new CheckBox(); Mycheckbox.Height = 50; Mycheckbox.Width = 100; Mycheckbox.Location = new Point(229, 136); Mycheckbox.Text = \"Male\"; Mycheckbox.CheckState = CheckState.Unchecked; // Adding checkbox to form this.Controls.Add(Mycheckbox); // Creating and setting the properties of CheckBox CheckBox Mycheckbox1 = new CheckBox(); Mycheckbox1.Height = 50; Mycheckbox1.Width = 100; Mycheckbox1.Location = new Point(230, 174); Mycheckbox1.Text = \"Female\"; Mycheckbox1.CheckState = CheckState.Indeterminate; // Adding checkbox to form this.Controls.Add(Mycheckbox1); }}}", "e": 3511, "s": 2129, "text": null }, { "code": null, "e": 3520, "s": 3511, "text": "Output: " }, { "code": null, "e": 3539, "s": 3522, "text": "arorakashish0911" }, { "code": null, "e": 3542, "s": 3539, "text": "C#" }, { "code": null, "e": 3640, "s": 3542, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 3683, "s": 3640, "text": "C# | Multiple inheritance using interfaces" }, { "code": null, "e": 3732, "s": 3683, "text": "Differences Between .NET Core and .NET Framework" }, { "code": null, "e": 3755, "s": 3732, "text": "Extension Method in C#" }, { "code": null, "e": 3771, "s": 3755, "text": "C# | List Class" }, { "code": null, "e": 3799, "s": 3771, "text": "HashSet in C# with Examples" }, { "code": null, "e": 3860, "s": 3799, "text": "C# | .NET Framework (Basic Architecture and Component Stack)" }, { "code": null, "e": 3883, "s": 3860, "text": "Switch Statement in C#" }, { "code": null, "e": 3905, "s": 3883, "text": "Partial Classes in C#" }, { "code": null, "e": 3930, "s": 3905, "text": "Lambda Expressions in C#" } ]
Lodash _.uniqWith() Method
31 Aug, 2020 The _.uniqWith() method is similar to _.uniq() method ( i.e. it creates a duplicate-free version of an array, in which only the first occurrence of each element is kept.) except that it accepts comparator which is invoked to compare elements of an array. Order of result values is determined by the order they occur in the array. Syntax: _.uniqWith(array, [comparator]) Parameters: This method accepts two parameters as mentioned above and described below: array: This parameter holds the array to inspect. [comparator] (Function): This parameter holds the comparator invoked per element and is invoked with two arguments (arrVal, othVal). Return Value: This method returns the new duplicate free array. Example 1: Here, const _ = require(‘lodash’) is used to import the lodash library in the file. javascript // Requiring the lodash library const _ = require("lodash"); // Original array var objects = [{ 'x': 5, 'y': 2 }, { 'x': 3, 'y': 4 }, { 'x': 5, 'y': 2 } ]; // Use of _.uniqWith() methodlet gfg = _.uniqWith(objects, _.isEqual); // Printing the output console.log(gfg); Output: [ { x: 5, y: 2 }, { x: 3, y: 4 } ] Example 2: javascript // Requiring the lodash library const _ = require("lodash"); // Original array var objects = [ 2.2, 3.2, 4.2, 3.2, 5.2, 4.2 ]; // Use of _.uniqWith() methodlet gfg = _.uniqWith(objects, _.isEqual); // Printing the output console.log(gfg); Output: [ 2.2, 3.2, 4.2, 5.2] Example 3: javascript // Requiring the lodash library const _ = require("lodash"); // Original array var objects = ['p', 'q', 'r', 'u', 's', 't', 'r', 'u']; // Use of _.uniqWith() methodlet gfg = _.uniqWith(objects, _.isEqual); // Printing the output console.log(gfg); Output: ['p', 'q', 'r', 'u', 's', 't'] Note: This code will not work in normal JavaScript because it requires the library lodash to be installed. JavaScript-Lodash JavaScript 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": "\n31 Aug, 2020" }, { "code": null, "e": 358, "s": 28, "text": "The _.uniqWith() method is similar to _.uniq() method ( i.e. it creates a duplicate-free version of an array, in which only the first occurrence of each element is kept.) except that it accepts comparator which is invoked to compare elements of an array. Order of result values is determined by the order they occur in the array." }, { "code": null, "e": 366, "s": 358, "text": "Syntax:" }, { "code": null, "e": 398, "s": 366, "text": "_.uniqWith(array, [comparator])" }, { "code": null, "e": 485, "s": 398, "text": "Parameters: This method accepts two parameters as mentioned above and described below:" }, { "code": null, "e": 535, "s": 485, "text": "array: This parameter holds the array to inspect." }, { "code": null, "e": 668, "s": 535, "text": "[comparator] (Function): This parameter holds the comparator invoked per element and is invoked with two arguments (arrVal, othVal)." }, { "code": null, "e": 732, "s": 668, "text": "Return Value: This method returns the new duplicate free array." }, { "code": null, "e": 827, "s": 732, "text": "Example 1: Here, const _ = require(‘lodash’) is used to import the lodash library in the file." }, { "code": null, "e": 838, "s": 827, "text": "javascript" }, { "code": "// Requiring the lodash library const _ = require(\"lodash\"); // Original array var objects = [{ 'x': 5, 'y': 2 }, { 'x': 3, 'y': 4 }, { 'x': 5, 'y': 2 } ]; // Use of _.uniqWith() methodlet gfg = _.uniqWith(objects, _.isEqual); // Printing the output console.log(gfg);", "e": 1124, "s": 838, "text": null }, { "code": null, "e": 1132, "s": 1124, "text": "Output:" }, { "code": null, "e": 1168, "s": 1132, "text": "[ { x: 5, y: 2 }, { x: 3, y: 4 } ]\n" }, { "code": null, "e": 1179, "s": 1168, "text": "Example 2:" }, { "code": null, "e": 1190, "s": 1179, "text": "javascript" }, { "code": "// Requiring the lodash library const _ = require(\"lodash\"); // Original array var objects = [ 2.2, 3.2, 4.2, 3.2, 5.2, 4.2 ]; // Use of _.uniqWith() methodlet gfg = _.uniqWith(objects, _.isEqual); // Printing the output console.log(gfg);", "e": 1445, "s": 1190, "text": null }, { "code": null, "e": 1453, "s": 1445, "text": "Output:" }, { "code": null, "e": 1476, "s": 1453, "text": "[ 2.2, 3.2, 4.2, 5.2]\n" }, { "code": null, "e": 1487, "s": 1476, "text": "Example 3:" }, { "code": null, "e": 1498, "s": 1487, "text": "javascript" }, { "code": "// Requiring the lodash library const _ = require(\"lodash\"); // Original array var objects = ['p', 'q', 'r', 'u', 's', 't', 'r', 'u']; // Use of _.uniqWith() methodlet gfg = _.uniqWith(objects, _.isEqual); // Printing the output console.log(gfg);", "e": 1767, "s": 1498, "text": null }, { "code": null, "e": 1775, "s": 1767, "text": "Output:" }, { "code": null, "e": 1807, "s": 1775, "text": "['p', 'q', 'r', 'u', 's', 't']\n" }, { "code": null, "e": 1914, "s": 1807, "text": "Note: This code will not work in normal JavaScript because it requires the library lodash to be installed." }, { "code": null, "e": 1932, "s": 1914, "text": "JavaScript-Lodash" }, { "code": null, "e": 1943, "s": 1932, "text": "JavaScript" }, { "code": null, "e": 1960, "s": 1943, "text": "Web Technologies" } ]
Collections.reverse() Method in Java with Examples
07 Jul, 2022 reverse() method of Collections class as the name itself suggests is used for reversing elements been there up in the object in which they are stored. It reverses the order of elements in a list passed as an argument. This class is present in java.util package so do syntax is as follows: import java.util.Collections; Collections.reverse(class_obj); Illustration: Input : {1, 2, 3, 4} Output : {4, 3, 2, 1} Parameter: Object of a class whose elements are to be reversed. public static void reverse(List myList) Exception Thrown: It throws UnsupportedOperationException if the specified list or its list-iterator does not support the set operation. Let us see the usage of this method via use cases listed below as follows: Reversing an ArrayList Reversing a LinkedList Reversing an array Let us implement this method of Collections class by implementing the same in clan java codes as provided below as follows: Case 1: Reversing an ArrayList JAVA // Java program to illustrate reverse() method// of Collections class over ArrayList // Importing utility classesimport java.util.*; // Main classpublic class GFG { // main driver method public static void main(String[] args) { // Let us create a list of strings List<String> mylist = new ArrayList<String>(); // Adding elements to the List // Custom input elements mylist.add("practice"); mylist.add("code"); mylist.add("quiz"); mylist.add("geeksforgeeks"); // Print all elements originally System.out.println("Original List : " + mylist); // Using reverse() method to // reverse the element order of mylist Collections.reverse(mylist); // Print all elements of list in reverse order // using reverse() method System.out.println("Modified List: " + mylist); }} Original List : [practice, code, quiz, geeksforgeeks] Modified List: [geeksforgeeks, quiz, code, practice] Case 2: Reversing a LinkedList Java // Java program to illustrate reverse() method// of Collections class over ArrayList // Importing utility classesimport java.util.*; // Main classpublic class GFG { // main driver method public static void main(String[] args) { // Let us create a list of strings List<String> mylist = new LinkedList<String>(); // Adding elements to the List // Custom input elements mylist.add("practice"); mylist.add("code"); mylist.add("quiz"); mylist.add("geeksforgeeks"); // Print all elements originally System.out.println("Original List : " + mylist); // Using reverse() method to // reverse the element order of mylist Collections.reverse(mylist); // Print all elements of list in reverse order // using reverse() method System.out.println("Modified List: " + mylist); }} Original List : [practice, code, quiz, geeksforgeeks] Modified List: [geeksforgeeks, quiz, code, practice] If we peek through the above programs then there is only a minute signature detail that we are just creating an object of LinkedList class instead of Array class as seen in example1A. For LinkedList, we just did change as shown below in the above codes: LinkedList in "List mylist = new ArrayList();". Case 3: Reversing an array: Arrays class in Java doesn’t have a reverse method. We can use Collections.reverse() to reverse an array also as shown below as follows: Example Java // Java program to Illustrate Reversal of Array// using reverse() method of Collections class // Importing utility classesimport java.util.*; // Main classpublic class GFG { // Main driver method public static void main(String[] args) { // Creating input integer array Integer arr[] = { 10, 20, 30, 40, 50 }; // Print elements of array System.out.println("Original Array : " + Arrays.toString(arr)); // Reversing elements of array using reverse() // method of Arrays class and fetching as // list via asList() Collections.reverse(Arrays.asList(arr)); // Print and display reverse updated array System.out.println("Modified Array : " + Arrays.toString(arr)); }} Original Array : [10, 20, 30, 40, 50] Modified Array : [50, 40, 30, 20, 10] This article is contributed by Mohit Gupta. If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to review-team@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks. Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above. solankimayank Java - util package Java-Collections Java-Collections-Class Java-Functions Java Java Java-Collections Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Object Oriented Programming (OOPs) Concept in Java How to iterate any Map in Java Interfaces in Java HashMap in Java with Examples ArrayList in Java Stream In Java Collections in Java Multidimensional Arrays in Java Singleton Class in Java Stack Class in Java
[ { "code": null, "e": 53, "s": 25, "text": "\n07 Jul, 2022" }, { "code": null, "e": 271, "s": 53, "text": "reverse() method of Collections class as the name itself suggests is used for reversing elements been there up in the object in which they are stored. It reverses the order of elements in a list passed as an argument." }, { "code": null, "e": 342, "s": 271, "text": "This class is present in java.util package so do syntax is as follows:" }, { "code": null, "e": 372, "s": 342, "text": "import java.util.Collections;" }, { "code": null, "e": 404, "s": 372, "text": "Collections.reverse(class_obj);" }, { "code": null, "e": 418, "s": 404, "text": "Illustration:" }, { "code": null, "e": 462, "s": 418, "text": "Input : {1, 2, 3, 4}\nOutput : {4, 3, 2, 1}" }, { "code": null, "e": 526, "s": 462, "text": "Parameter: Object of a class whose elements are to be reversed." }, { "code": null, "e": 566, "s": 526, "text": "public static void reverse(List myList)" }, { "code": null, "e": 703, "s": 566, "text": "Exception Thrown: It throws UnsupportedOperationException if the specified list or its list-iterator does not support the set operation." }, { "code": null, "e": 778, "s": 703, "text": "Let us see the usage of this method via use cases listed below as follows:" }, { "code": null, "e": 801, "s": 778, "text": "Reversing an ArrayList" }, { "code": null, "e": 824, "s": 801, "text": "Reversing a LinkedList" }, { "code": null, "e": 843, "s": 824, "text": "Reversing an array" }, { "code": null, "e": 967, "s": 843, "text": "Let us implement this method of Collections class by implementing the same in clan java codes as provided below as follows:" }, { "code": null, "e": 998, "s": 967, "text": "Case 1: Reversing an ArrayList" }, { "code": null, "e": 1003, "s": 998, "text": "JAVA" }, { "code": "// Java program to illustrate reverse() method// of Collections class over ArrayList // Importing utility classesimport java.util.*; // Main classpublic class GFG { // main driver method public static void main(String[] args) { // Let us create a list of strings List<String> mylist = new ArrayList<String>(); // Adding elements to the List // Custom input elements mylist.add(\"practice\"); mylist.add(\"code\"); mylist.add(\"quiz\"); mylist.add(\"geeksforgeeks\"); // Print all elements originally System.out.println(\"Original List : \" + mylist); // Using reverse() method to // reverse the element order of mylist Collections.reverse(mylist); // Print all elements of list in reverse order // using reverse() method System.out.println(\"Modified List: \" + mylist); }}", "e": 1901, "s": 1003, "text": null }, { "code": null, "e": 2008, "s": 1901, "text": "Original List : [practice, code, quiz, geeksforgeeks]\nModified List: [geeksforgeeks, quiz, code, practice]" }, { "code": null, "e": 2039, "s": 2008, "text": "Case 2: Reversing a LinkedList" }, { "code": null, "e": 2044, "s": 2039, "text": "Java" }, { "code": "// Java program to illustrate reverse() method// of Collections class over ArrayList // Importing utility classesimport java.util.*; // Main classpublic class GFG { // main driver method public static void main(String[] args) { // Let us create a list of strings List<String> mylist = new LinkedList<String>(); // Adding elements to the List // Custom input elements mylist.add(\"practice\"); mylist.add(\"code\"); mylist.add(\"quiz\"); mylist.add(\"geeksforgeeks\"); // Print all elements originally System.out.println(\"Original List : \" + mylist); // Using reverse() method to // reverse the element order of mylist Collections.reverse(mylist); // Print all elements of list in reverse order // using reverse() method System.out.println(\"Modified List: \" + mylist); }}", "e": 2943, "s": 2044, "text": null }, { "code": null, "e": 3050, "s": 2943, "text": "Original List : [practice, code, quiz, geeksforgeeks]\nModified List: [geeksforgeeks, quiz, code, practice]" }, { "code": null, "e": 3304, "s": 3050, "text": "If we peek through the above programs then there is only a minute signature detail that we are just creating an object of LinkedList class instead of Array class as seen in example1A. For LinkedList, we just did change as shown below in the above codes:" }, { "code": null, "e": 3352, "s": 3304, "text": "LinkedList in \"List mylist = new ArrayList();\"." }, { "code": null, "e": 3517, "s": 3352, "text": "Case 3: Reversing an array: Arrays class in Java doesn’t have a reverse method. We can use Collections.reverse() to reverse an array also as shown below as follows:" }, { "code": null, "e": 3526, "s": 3517, "text": "Example " }, { "code": null, "e": 3531, "s": 3526, "text": "Java" }, { "code": "// Java program to Illustrate Reversal of Array// using reverse() method of Collections class // Importing utility classesimport java.util.*; // Main classpublic class GFG { // Main driver method public static void main(String[] args) { // Creating input integer array Integer arr[] = { 10, 20, 30, 40, 50 }; // Print elements of array System.out.println(\"Original Array : \" + Arrays.toString(arr)); // Reversing elements of array using reverse() // method of Arrays class and fetching as // list via asList() Collections.reverse(Arrays.asList(arr)); // Print and display reverse updated array System.out.println(\"Modified Array : \" + Arrays.toString(arr)); }}", "e": 4338, "s": 3531, "text": null }, { "code": null, "e": 4414, "s": 4338, "text": "Original Array : [10, 20, 30, 40, 50]\nModified Array : [50, 40, 30, 20, 10]" }, { "code": null, "e": 4834, "s": 4414, "text": "This article is contributed by Mohit Gupta. If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to review-team@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks. Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above." }, { "code": null, "e": 4848, "s": 4834, "text": "solankimayank" }, { "code": null, "e": 4868, "s": 4848, "text": "Java - util package" }, { "code": null, "e": 4885, "s": 4868, "text": "Java-Collections" }, { "code": null, "e": 4908, "s": 4885, "text": "Java-Collections-Class" }, { "code": null, "e": 4923, "s": 4908, "text": "Java-Functions" }, { "code": null, "e": 4928, "s": 4923, "text": "Java" }, { "code": null, "e": 4933, "s": 4928, "text": "Java" }, { "code": null, "e": 4950, "s": 4933, "text": "Java-Collections" }, { "code": null, "e": 5048, "s": 4950, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 5099, "s": 5048, "text": "Object Oriented Programming (OOPs) Concept in Java" }, { "code": null, "e": 5130, "s": 5099, "text": "How to iterate any Map in Java" }, { "code": null, "e": 5149, "s": 5130, "text": "Interfaces in Java" }, { "code": null, "e": 5179, "s": 5149, "text": "HashMap in Java with Examples" }, { "code": null, "e": 5197, "s": 5179, "text": "ArrayList in Java" }, { "code": null, "e": 5212, "s": 5197, "text": "Stream In Java" }, { "code": null, "e": 5232, "s": 5212, "text": "Collections in Java" }, { "code": null, "e": 5264, "s": 5232, "text": "Multidimensional Arrays in Java" }, { "code": null, "e": 5288, "s": 5264, "text": "Singleton Class in Java" } ]
Display date and time in videos using OpenCV – Python
16 Jul, 2021 OpenCV-Python is a library of Python bindings designed to solve computer vision problems. It can process images and videos to identify objects, faces, or even the handwriting of a humanNote: For more information, refer to Introduction to OpenCV It sometimes becomes necessary to display date and time on videos when we are processing videos of live feed or videos which are of a large duration. Time and date will be helpful to know and analyze any anomaly detected in the video with reference to its time and date. To display date and time on videos we do the following.Code Python3 # Import librariesimport numpyimport cv2import datetime # open the videovid = cv2.VideoCapture('sample.mp4') # Process until end.while(vid.isOpened()): ret, frame = vid.read() if ret: # describe the type of # font you want to display font = cv2.FONT_HERSHEY_SCRIPT_COMPLEX # Get date and time and # save it inside a variable dt = str(datetime.datetime.now()) # put the dt variable over the # video frame frame = cv2.putText(frame, dt, (10, 100), font, 1, (210, 155, 155), 4, cv2.LINE_8) # show the video cv2.imshow('frame', frame) key = cv2.waitKey(1) # define the key to # close the window if key == 'q' or key == 27: break else: break # release the vid objectvid.release() # close all the opened windows.cv2.destroyAllWindows() Output saurabh1990aror Python-OpenCV Python Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. How to Install PIP on Windows ? Python Classes and Objects Python OOPs Concepts Introduction To PYTHON Python | os.path.join() method How to drop one or multiple columns in Pandas Dataframe How To Convert Python Dictionary To JSON? Check if element exists in list in Python Python | Get unique values from a list Python | datetime.timedelta() function
[ { "code": null, "e": 28, "s": 0, "text": "\n16 Jul, 2021" }, { "code": null, "e": 274, "s": 28, "text": "OpenCV-Python is a library of Python bindings designed to solve computer vision problems. It can process images and videos to identify objects, faces, or even the handwriting of a humanNote: For more information, refer to Introduction to OpenCV " }, { "code": null, "e": 607, "s": 274, "text": "It sometimes becomes necessary to display date and time on videos when we are processing videos of live feed or videos which are of a large duration. Time and date will be helpful to know and analyze any anomaly detected in the video with reference to its time and date. To display date and time on videos we do the following.Code " }, { "code": null, "e": 615, "s": 607, "text": "Python3" }, { "code": "# Import librariesimport numpyimport cv2import datetime # open the videovid = cv2.VideoCapture('sample.mp4') # Process until end.while(vid.isOpened()): ret, frame = vid.read() if ret: # describe the type of # font you want to display font = cv2.FONT_HERSHEY_SCRIPT_COMPLEX # Get date and time and # save it inside a variable dt = str(datetime.datetime.now()) # put the dt variable over the # video frame frame = cv2.putText(frame, dt, (10, 100), font, 1, (210, 155, 155), 4, cv2.LINE_8) # show the video cv2.imshow('frame', frame) key = cv2.waitKey(1) # define the key to # close the window if key == 'q' or key == 27: break else: break # release the vid objectvid.release() # close all the opened windows.cv2.destroyAllWindows()", "e": 1633, "s": 615, "text": null }, { "code": null, "e": 1642, "s": 1633, "text": "Output " }, { "code": null, "e": 1660, "s": 1644, "text": "saurabh1990aror" }, { "code": null, "e": 1674, "s": 1660, "text": "Python-OpenCV" }, { "code": null, "e": 1681, "s": 1674, "text": "Python" }, { "code": null, "e": 1779, "s": 1681, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 1811, "s": 1779, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 1838, "s": 1811, "text": "Python Classes and Objects" }, { "code": null, "e": 1859, "s": 1838, "text": "Python OOPs Concepts" }, { "code": null, "e": 1882, "s": 1859, "text": "Introduction To PYTHON" }, { "code": null, "e": 1913, "s": 1882, "text": "Python | os.path.join() method" }, { "code": null, "e": 1969, "s": 1913, "text": "How to drop one or multiple columns in Pandas Dataframe" }, { "code": null, "e": 2011, "s": 1969, "text": "How To Convert Python Dictionary To JSON?" }, { "code": null, "e": 2053, "s": 2011, "text": "Check if element exists in list in Python" }, { "code": null, "e": 2092, "s": 2053, "text": "Python | Get unique values from a list" } ]
Implementation of Teaching Learning Based Optimization
10 Dec, 2021 The previous article Teaching Learning Based Optimization (TLBO) talked about the inspiration of teaching learning-based optimization, it’s mathematical modeling and algorithms. In this article we will implement Teaching learning-based optimization (TLBO) for two fitness functions 1) Rastrigin function 2) Sphere function. The algorithm will run for a predefined number of maximum iterations and will try to find the minimum value of these fitness functions. Rastrigin function is a non-convex function and is often used as a performance test problem for optimization algorithms. Fig1: Rastrigin function for 2 variables For an optimization algorithm, rastrigin function is a very challenging one. Its complex behavior causes optimization algorithms to often be stuck at local minima. Having a lot of cosine oscillations on the plane introduces the complex behavior to this function. Sphere function is a standard function for evaluating the performance of an optimization algorithm. Fig 2: Sphere function for 2 variables Number of dimensions (d) = 3 Lower bound (minx) = -10.0 Upper bound (maxx) = 10.0 Number of particles (N) = 50 Maximum number of iterations (max_iter) = 100 Fitness function Problem parameters ( mentioned above) Population size (N) and Maximum number of iterations (max_iter) Algorithm Specific hyperparameters (None in teaching-learning based optimization) The pseudocode of the teaching-learning-based optimization is already described in the previous article. Data structures to store students as well as a data structure to store data specific to the individual students were also discussed. Python3 # python implementation of Teaching learning based optimization (TLBO)# minimizing rastrigin and sphere function import randomimport math # cos() for Rastriginimport copy # array-copying convenienceimport sys # max float #-------fitness functions--------- # rastrigin functiondef fitness_rastrigin(position): fitness_value = 0.0 for i in range(len(position)): xi = position[i] fitness_value += (xi * xi) - (10 * math.cos(2 * math.pi * xi)) + 10 return fitness_value #sphere functiondef fitness_sphere(position): fitness_value = 0.0 for i in range(len(position)): xi = position[i] fitness_value += (xi*xi); return fitness_value;#------------------------- #Student classclass Student: def __init__(self, fitness, dim, minx, maxx, seed): self.rnd = random.Random(seed) # a list of size dim # with 0.0 as value of all the elements self.position = [0.0 for i in range(dim)] # loop dim times and randomly select value of decision var # value should be in between minx and maxx for i in range(dim): self.position[i] = ((maxx - minx) * self.rnd.random() + minx) # compute the fitness of student self.fitness = fitness(self.position) # Teaching learning based optimizationdef tlbo(fitness, max_iter, n, dim, minx, maxx): rnd = random.Random(0) # create n random students classroom = [Student(fitness, dim, minx, maxx, i) for i in range(n)] # compute the value of best_position and best_fitness in the classroom Xbest = [0.0 for i in range(dim)] Fbest = sys.float_info.max for i in range(n): # check each Student if classroom[i].fitness < Fbest: Fbest = classroom[i].fitness Xbest = copy.copy(classroom[i].position) # main loop of tlbo Iter = 0 while Iter < max_iter: # after every 10 iterations # print iteration number and best fitness value so far if Iter % 10 == 0 and Iter > 1: print("Iter = " + str(Iter) + " best fitness = %.3f" % Fbest) # for each student of classroom for i in range(n): ### Teaching phase of ith student # compute the mean of all the students in the class Xmean = [0.0 for i in range(dim)] for k in range(n): for j in range(dim): Xmean[j]+= classroom[k].position[j] for j in range(dim): Xmean[j]/= n; # initialize new solution Xnew = [0.0 for i in range(dim)] # teaching factor (TF) # either 1 or 2 ( randomly chosen) TF = random.randint(1, 3) # best student of the class is teacher Xteacher = Xbest # compute new solution for j in range(dim): Xnew[j] = classroom[i].position[j] + rnd.random()*(Xteacher[j] - TF*Xmean[j]) # if Xnew < minx OR Xnew > maxx # then clip it for j in range(dim): Xnew[j] = max(Xnew[j], minx) Xnew[j] = min(Xnew[j], maxx) # compute fitness of new solution fnew = fitness(Xnew) # if new solution is better than old # replace old with new solution if(fnew < classroom[i].fitness): classroom[i].position = Xnew classroom[i].fitness = fnew # update best student if(fnew < Fbest): Fbest = fnew Xbest = Xnew ### learning phase of ith student # randomly choose a solution from classroom # chosen solution should not be ith student p = random.randint(0, n-1) while(p==i): p = random.randint(0, n-1) # partner solution Xpartner = classroom[p] Xnew = [0.0 for i in range(dim)] if(classroom[i].fitness < Xpartner.fitness): for j in range(dim): Xnew[j] = classroom[i].position[j] + rnd.random()*(classroom[i].position[j] - Xpartner.position[j]) else: for j in range(dim): Xnew[j] = classroom[i].position[j] - rnd.random()*(classroom[i].position[j] - Xpartner.position[j]) # if Xnew < minx OR Xnew > maxx # then clip it for j in range(dim): Xnew[j] = max(Xnew[j], minx) Xnew[j] = min(Xnew[j], maxx) # compute fitness of new solution fnew = fitness(Xnew) # if new solution is better than old # replace old with new solution if(fnew < classroom[i].fitness): classroom[i].position = Xnew classroom[i].fitness = fnew # update best student if(fnew < Fbest): Fbest = fnew Xbest = Xnew Iter += 1 # end-while # return best student from classroom return Xbest# end pso #----------------------------# Driver code for rastrigin function print("\nBegin teaching learning based optimization on rastrigin function\n")dim = 3fitness = fitness_rastrigin print("Goal is to minimize Rastrigin's function in " + str(dim) + " variables")print("Function has known min = 0.0 at (", end="")for i in range(dim-1): print("0, ", end="")print("0)") num_particles = 50max_iter = 100 print("Setting num_particles = " + str(num_particles))print("Setting max_iter = " + str(max_iter))print("\nStarting TLBO algorithm\n") best_position = tlbo(fitness, max_iter, num_particles, dim, -10.0, 10.0) print("\nTLBO completed\n")print("\nBest Student found:")print(["%.6f"%best_position[k] for k in range(dim)])fitness_value = fitness(best_position)print("fitness of best Student = %.6f" % fitness_value) print("\nEnd TLBO for rastrigin function\n") print()print() # Driver code for Sphere functionprint("\nBegin teaching learning based optimization on sphere function\n")dim = 3fitness = fitness_sphere print("Goal is to minimize sphere function in " + str(dim) + " variables")print("Function has known min = 0.0 at (", end="")for i in range(dim-1): print("0, ", end="")print("0)") num_particles = 50max_iter = 100 print("Setting num_particles = " + str(num_particles))print("Setting max_iter = " + str(max_iter))print("\nStarting TLBO algorithm\n") best_position = tlbo(fitness, max_iter, num_particles, dim, -10.0, 10.0) print("\nTLBO completed\n")print("\nBest Student found:")print(["%.6f"%best_position[k] for k in range(dim)])fitness_value = fitness(best_position)print("fitness of best Student = %.6f" % fitness_value) print("\nEnd TLBO for sphere function\n") Begin teaching learning based optimization on rastrigin function Goal is to minimize Rastrigin's function in 3 variables Function has known min = 0.0 at (0, 0, 0) Setting num_particles = 50 Setting max_iter = 100 Starting TLBO algorithm Iter = 10 best fitness = 3.662 Iter = 20 best fitness = 0.389 Iter = 30 best fitness = 0.389 Iter = 40 best fitness = 0.389 Iter = 50 best fitness = 0.200 Iter = 60 best fitness = 0.132 Iter = 70 best fitness = 0.051 Iter = 80 best fitness = 0.003 Iter = 90 best fitness = 0.001 TLBO completed Best Student found: ['0.000593', '-0.000040', '-0.000461'] fitness of best Student = 0.000112 End TLBO for rastrigin function Begin teaching learning based optimization on sphere function Goal is to minimize sphere function in 3 variables Function has known min = 0.0 at (0, 0, 0) Setting num_particles = 50 Setting max_iter = 100 Starting TLBO algorithm Iter = 10 best fitness = 0.009 Iter = 20 best fitness = 0.000 Iter = 30 best fitness = 0.000 Iter = 40 best fitness = 0.000 Iter = 50 best fitness = 0.000 Iter = 60 best fitness = 0.000 Iter = 70 best fitness = 0.000 Iter = 80 best fitness = 0.000 Iter = 90 best fitness = 0.000 TLBO completed Best Student found: ['0.000000', '-0.000000', '-0.000000'] fitness of best Student = 0.000000 End TLBO for sphere function Research paper: R. V. Rao, V. J. Savsani & J. Balic (2012) Teaching–learning-based optimization algorithm for unconstrained and constrained real-parameter optimization problems, Engineering Optimization, 44:12, 1447-1462, DOI: 10.1080/0305215X.2011.652103 Inspiration of the implementation: https://www.mathworks.com/matlabcentral/fileexchange/65628-teaching-learning-based-optimization#:~:text=Teaching%20Learning%20Based%20Optimization%20is,teacher%20and%20the%20student%20phase. varshagumber28 ddeevviissaavviittaa Artificial Intelligence Machine Learning Python Machine Learning Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. ML | Linear Regression Reinforcement learning Supervised and Unsupervised learning Decision Tree Introduction with example Search Algorithms in AI 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": 28, "s": 0, "text": "\n10 Dec, 2021" }, { "code": null, "e": 492, "s": 28, "text": "The previous article Teaching Learning Based Optimization (TLBO) talked about the inspiration of teaching learning-based optimization, it’s mathematical modeling and algorithms. In this article we will implement Teaching learning-based optimization (TLBO) for two fitness functions 1) Rastrigin function 2) Sphere function. The algorithm will run for a predefined number of maximum iterations and will try to find the minimum value of these fitness functions." }, { "code": null, "e": 613, "s": 492, "text": "Rastrigin function is a non-convex function and is often used as a performance test problem for optimization algorithms." }, { "code": null, "e": 654, "s": 613, "text": "Fig1: Rastrigin function for 2 variables" }, { "code": null, "e": 917, "s": 654, "text": "For an optimization algorithm, rastrigin function is a very challenging one. Its complex behavior causes optimization algorithms to often be stuck at local minima. Having a lot of cosine oscillations on the plane introduces the complex behavior to this function." }, { "code": null, "e": 1017, "s": 917, "text": "Sphere function is a standard function for evaluating the performance of an optimization algorithm." }, { "code": null, "e": 1056, "s": 1017, "text": "Fig 2: Sphere function for 2 variables" }, { "code": null, "e": 1085, "s": 1056, "text": "Number of dimensions (d) = 3" }, { "code": null, "e": 1112, "s": 1085, "text": "Lower bound (minx) = -10.0" }, { "code": null, "e": 1138, "s": 1112, "text": "Upper bound (maxx) = 10.0" }, { "code": null, "e": 1167, "s": 1138, "text": "Number of particles (N) = 50" }, { "code": null, "e": 1213, "s": 1167, "text": "Maximum number of iterations (max_iter) = 100" }, { "code": null, "e": 1230, "s": 1213, "text": "Fitness function" }, { "code": null, "e": 1268, "s": 1230, "text": "Problem parameters ( mentioned above)" }, { "code": null, "e": 1333, "s": 1268, "text": "Population size (N) and Maximum number of iterations (max_iter)" }, { "code": null, "e": 1415, "s": 1333, "text": "Algorithm Specific hyperparameters (None in teaching-learning based optimization)" }, { "code": null, "e": 1653, "s": 1415, "text": "The pseudocode of the teaching-learning-based optimization is already described in the previous article. Data structures to store students as well as a data structure to store data specific to the individual students were also discussed." }, { "code": null, "e": 1661, "s": 1653, "text": "Python3" }, { "code": "# python implementation of Teaching learning based optimization (TLBO)# minimizing rastrigin and sphere function import randomimport math # cos() for Rastriginimport copy # array-copying convenienceimport sys # max float #-------fitness functions--------- # rastrigin functiondef fitness_rastrigin(position): fitness_value = 0.0 for i in range(len(position)): xi = position[i] fitness_value += (xi * xi) - (10 * math.cos(2 * math.pi * xi)) + 10 return fitness_value #sphere functiondef fitness_sphere(position): fitness_value = 0.0 for i in range(len(position)): xi = position[i] fitness_value += (xi*xi); return fitness_value;#------------------------- #Student classclass Student: def __init__(self, fitness, dim, minx, maxx, seed): self.rnd = random.Random(seed) # a list of size dim # with 0.0 as value of all the elements self.position = [0.0 for i in range(dim)] # loop dim times and randomly select value of decision var # value should be in between minx and maxx for i in range(dim): self.position[i] = ((maxx - minx) * self.rnd.random() + minx) # compute the fitness of student self.fitness = fitness(self.position) # Teaching learning based optimizationdef tlbo(fitness, max_iter, n, dim, minx, maxx): rnd = random.Random(0) # create n random students classroom = [Student(fitness, dim, minx, maxx, i) for i in range(n)] # compute the value of best_position and best_fitness in the classroom Xbest = [0.0 for i in range(dim)] Fbest = sys.float_info.max for i in range(n): # check each Student if classroom[i].fitness < Fbest: Fbest = classroom[i].fitness Xbest = copy.copy(classroom[i].position) # main loop of tlbo Iter = 0 while Iter < max_iter: # after every 10 iterations # print iteration number and best fitness value so far if Iter % 10 == 0 and Iter > 1: print(\"Iter = \" + str(Iter) + \" best fitness = %.3f\" % Fbest) # for each student of classroom for i in range(n): ### Teaching phase of ith student # compute the mean of all the students in the class Xmean = [0.0 for i in range(dim)] for k in range(n): for j in range(dim): Xmean[j]+= classroom[k].position[j] for j in range(dim): Xmean[j]/= n; # initialize new solution Xnew = [0.0 for i in range(dim)] # teaching factor (TF) # either 1 or 2 ( randomly chosen) TF = random.randint(1, 3) # best student of the class is teacher Xteacher = Xbest # compute new solution for j in range(dim): Xnew[j] = classroom[i].position[j] + rnd.random()*(Xteacher[j] - TF*Xmean[j]) # if Xnew < minx OR Xnew > maxx # then clip it for j in range(dim): Xnew[j] = max(Xnew[j], minx) Xnew[j] = min(Xnew[j], maxx) # compute fitness of new solution fnew = fitness(Xnew) # if new solution is better than old # replace old with new solution if(fnew < classroom[i].fitness): classroom[i].position = Xnew classroom[i].fitness = fnew # update best student if(fnew < Fbest): Fbest = fnew Xbest = Xnew ### learning phase of ith student # randomly choose a solution from classroom # chosen solution should not be ith student p = random.randint(0, n-1) while(p==i): p = random.randint(0, n-1) # partner solution Xpartner = classroom[p] Xnew = [0.0 for i in range(dim)] if(classroom[i].fitness < Xpartner.fitness): for j in range(dim): Xnew[j] = classroom[i].position[j] + rnd.random()*(classroom[i].position[j] - Xpartner.position[j]) else: for j in range(dim): Xnew[j] = classroom[i].position[j] - rnd.random()*(classroom[i].position[j] - Xpartner.position[j]) # if Xnew < minx OR Xnew > maxx # then clip it for j in range(dim): Xnew[j] = max(Xnew[j], minx) Xnew[j] = min(Xnew[j], maxx) # compute fitness of new solution fnew = fitness(Xnew) # if new solution is better than old # replace old with new solution if(fnew < classroom[i].fitness): classroom[i].position = Xnew classroom[i].fitness = fnew # update best student if(fnew < Fbest): Fbest = fnew Xbest = Xnew Iter += 1 # end-while # return best student from classroom return Xbest# end pso #----------------------------# Driver code for rastrigin function print(\"\\nBegin teaching learning based optimization on rastrigin function\\n\")dim = 3fitness = fitness_rastrigin print(\"Goal is to minimize Rastrigin's function in \" + str(dim) + \" variables\")print(\"Function has known min = 0.0 at (\", end=\"\")for i in range(dim-1): print(\"0, \", end=\"\")print(\"0)\") num_particles = 50max_iter = 100 print(\"Setting num_particles = \" + str(num_particles))print(\"Setting max_iter = \" + str(max_iter))print(\"\\nStarting TLBO algorithm\\n\") best_position = tlbo(fitness, max_iter, num_particles, dim, -10.0, 10.0) print(\"\\nTLBO completed\\n\")print(\"\\nBest Student found:\")print([\"%.6f\"%best_position[k] for k in range(dim)])fitness_value = fitness(best_position)print(\"fitness of best Student = %.6f\" % fitness_value) print(\"\\nEnd TLBO for rastrigin function\\n\") print()print() # Driver code for Sphere functionprint(\"\\nBegin teaching learning based optimization on sphere function\\n\")dim = 3fitness = fitness_sphere print(\"Goal is to minimize sphere function in \" + str(dim) + \" variables\")print(\"Function has known min = 0.0 at (\", end=\"\")for i in range(dim-1): print(\"0, \", end=\"\")print(\"0)\") num_particles = 50max_iter = 100 print(\"Setting num_particles = \" + str(num_particles))print(\"Setting max_iter = \" + str(max_iter))print(\"\\nStarting TLBO algorithm\\n\") best_position = tlbo(fitness, max_iter, num_particles, dim, -10.0, 10.0) print(\"\\nTLBO completed\\n\")print(\"\\nBest Student found:\")print([\"%.6f\"%best_position[k] for k in range(dim)])fitness_value = fitness(best_position)print(\"fitness of best Student = %.6f\" % fitness_value) print(\"\\nEnd TLBO for sphere function\\n\")", "e": 7885, "s": 1661, "text": null }, { "code": null, "e": 9213, "s": 7885, "text": "Begin teaching learning based optimization on rastrigin function\n\nGoal is to minimize Rastrigin's function in 3 variables\nFunction has known min = 0.0 at (0, 0, 0)\nSetting num_particles = 50\nSetting max_iter = 100\n\nStarting TLBO algorithm\n\nIter = 10 best fitness = 3.662\nIter = 20 best fitness = 0.389\nIter = 30 best fitness = 0.389\nIter = 40 best fitness = 0.389\nIter = 50 best fitness = 0.200\nIter = 60 best fitness = 0.132\nIter = 70 best fitness = 0.051\nIter = 80 best fitness = 0.003\nIter = 90 best fitness = 0.001\n\nTLBO completed\n\n\nBest Student found:\n['0.000593', '-0.000040', '-0.000461']\nfitness of best Student = 0.000112\n\nEnd TLBO for rastrigin function\n\n\n\n\nBegin teaching learning based optimization on sphere function\n\nGoal is to minimize sphere function in 3 variables\nFunction has known min = 0.0 at (0, 0, 0)\nSetting num_particles = 50\nSetting max_iter = 100\n\nStarting TLBO algorithm\n\nIter = 10 best fitness = 0.009\nIter = 20 best fitness = 0.000\nIter = 30 best fitness = 0.000\nIter = 40 best fitness = 0.000\nIter = 50 best fitness = 0.000\nIter = 60 best fitness = 0.000\nIter = 70 best fitness = 0.000\nIter = 80 best fitness = 0.000\nIter = 90 best fitness = 0.000\n\nTLBO completed\n\n\nBest Student found:\n['0.000000', '-0.000000', '-0.000000']\nfitness of best Student = 0.000000\n\nEnd TLBO for sphere function" }, { "code": null, "e": 9469, "s": 9213, "text": "Research paper: R. V. Rao, V. J. Savsani & J. Balic (2012) Teaching–learning-based optimization algorithm for unconstrained and constrained real-parameter optimization problems, Engineering Optimization, 44:12, 1447-1462, DOI: 10.1080/0305215X.2011.652103" }, { "code": null, "e": 9695, "s": 9469, "text": "Inspiration of the implementation: https://www.mathworks.com/matlabcentral/fileexchange/65628-teaching-learning-based-optimization#:~:text=Teaching%20Learning%20Based%20Optimization%20is,teacher%20and%20the%20student%20phase." }, { "code": null, "e": 9710, "s": 9695, "text": "varshagumber28" }, { "code": null, "e": 9731, "s": 9710, "text": "ddeevviissaavviittaa" }, { "code": null, "e": 9755, "s": 9731, "text": "Artificial Intelligence" }, { "code": null, "e": 9772, "s": 9755, "text": "Machine Learning" }, { "code": null, "e": 9779, "s": 9772, "text": "Python" }, { "code": null, "e": 9796, "s": 9779, "text": "Machine Learning" }, { "code": null, "e": 9894, "s": 9796, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 9917, "s": 9894, "text": "ML | Linear Regression" }, { "code": null, "e": 9940, "s": 9917, "text": "Reinforcement learning" }, { "code": null, "e": 9977, "s": 9940, "text": "Supervised and Unsupervised learning" }, { "code": null, "e": 10017, "s": 9977, "text": "Decision Tree Introduction with example" }, { "code": null, "e": 10041, "s": 10017, "text": "Search Algorithms in AI" }, { "code": null, "e": 10069, "s": 10041, "text": "Read JSON file using Python" }, { "code": null, "e": 10119, "s": 10069, "text": "Adding new column to existing DataFrame in Pandas" }, { "code": null, "e": 10141, "s": 10119, "text": "Python map() function" } ]
Reading the CSV file into Dataframes in R
09 May, 2021 In this article, we will learn how to import or read a CSV file into a dataframe in R Programming Language. Data set in use: In order to import or read the given CSV file into our data frame, we first need to check our current working directory, and make sure that the CSV file is in the same directory as our R studio is in, or else it might show “File not found Error”. To check the current working directory we need to use getwd() function, and to change the current working directory to some other working directory, we need to use stewd() function. getwd() returns an absolute file-path representing the current working directory of the R process. Syntax: getwd() setwd(dir) used to set the working directory to dir. Syntax: setwd(path) Example: R # gives the current working directorygetwd() # changes the location setwd("C:/Users/Vanshi/Desktop/gfg") Output: C:/Users/Vanshi/Documents Now that we have set our working path, we will import the CSV file into the data frame, and name our data frame as sdata. Here, we are reading the .csv file named “SampleData” using read.csv command, into our R studio, which means we are feeding the values to the Rstudio to extract some important information out of it. read.csv() function reads a file in table format and creates a data frame from it, with cases corresponding to lines and variables to fields in the file. Syntax: read.csv(file, header = TRUE, sep = “,”, quote = “\””, dec = “.”, fill = TRUE, comment.char = “”, ...) Arguments: file: the name of the file which the data are to be read from. header: a logical value indicating whether the file contains the names of the variables as its first line. If missing, the value is determined from the file format: header is set to TRUE if and only if the first row contains one fewer field than the number of columns. sep: the field separator character. Values on each line of the file are separated by this character. If sep = “” (the default for read.table) the separator is ‘white space’, that is one or more spaces, tabs, newlines or carriage returns. quote: the set of quoting characters. dec: the character used in the file for decimal points. fill: logical. If TRUE then in case the rows have unequal length, blank fields are implicitly added. comment.char: character: a character vector of length one containing a single character or an empty string. ... : Further arguments to be passed. Example: R sdata <- read.csv("SampleData.csv", header = TRUE, sep = ",")sdata # views the data frame formed from the csv fileView(sdata) Output: Now that, we have created our dataframe, we can perform some operations on it. The data read according to the usage from dataframe. Given below are two examples who read the data as per their requirement. Example 1: R sdata <- read.csv( "SampleData.csv", header = TRUE, sep = ",") highspeed <- subset( sdata, sdata$speed == max(sdata$speed)) # views the subsetted value in # tabular formView(highspeed) Output: Example 2: R sdata <- read.csv( "SampleData.csv", header = TRUE, sep = ",") highfreq <- subset( sdata, sdata$cyc_freq == "Several times per week") # views the information, of the above # condition in tabular formatView(highfreq) Output: Picked R-CSV R Language Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Change Color of Bars in Barchart using ggplot2 in R How to Split Column Into Multiple Columns in R DataFrame? Group by function in R using Dplyr How to Change Axis Scales in R Plots? How to filter R DataFrame by values in a column? R - if statement Logistic Regression in R Programming Replace Specific Characters in String in R How to import an Excel File into R ? Joining of Dataframes in R Programming
[ { "code": null, "e": 28, "s": 0, "text": "\n09 May, 2021" }, { "code": null, "e": 136, "s": 28, "text": "In this article, we will learn how to import or read a CSV file into a dataframe in R Programming Language." }, { "code": null, "e": 153, "s": 136, "text": "Data set in use:" }, { "code": null, "e": 400, "s": 153, "text": "In order to import or read the given CSV file into our data frame, we first need to check our current working directory, and make sure that the CSV file is in the same directory as our R studio is in, or else it might show “File not found Error”." }, { "code": null, "e": 582, "s": 400, "text": "To check the current working directory we need to use getwd() function, and to change the current working directory to some other working directory, we need to use stewd() function." }, { "code": null, "e": 681, "s": 582, "text": "getwd() returns an absolute file-path representing the current working directory of the R process." }, { "code": null, "e": 689, "s": 681, "text": "Syntax:" }, { "code": null, "e": 697, "s": 689, "text": "getwd()" }, { "code": null, "e": 750, "s": 697, "text": "setwd(dir) used to set the working directory to dir." }, { "code": null, "e": 759, "s": 750, "text": "Syntax: " }, { "code": null, "e": 771, "s": 759, "text": "setwd(path)" }, { "code": null, "e": 780, "s": 771, "text": "Example:" }, { "code": null, "e": 782, "s": 780, "text": "R" }, { "code": "# gives the current working directorygetwd() # changes the location setwd(\"C:/Users/Vanshi/Desktop/gfg\")", "e": 888, "s": 782, "text": null }, { "code": null, "e": 896, "s": 888, "text": "Output:" }, { "code": null, "e": 922, "s": 896, "text": "C:/Users/Vanshi/Documents" }, { "code": null, "e": 1045, "s": 922, "text": "Now that we have set our working path, we will import the CSV file into the data frame, and name our data frame as sdata. " }, { "code": null, "e": 1244, "s": 1045, "text": "Here, we are reading the .csv file named “SampleData” using read.csv command, into our R studio, which means we are feeding the values to the Rstudio to extract some important information out of it." }, { "code": null, "e": 1398, "s": 1244, "text": "read.csv() function reads a file in table format and creates a data frame from it, with cases corresponding to lines and variables to fields in the file." }, { "code": null, "e": 1509, "s": 1398, "text": "Syntax: read.csv(file, header = TRUE, sep = “,”, quote = “\\””, dec = “.”, fill = TRUE, comment.char = “”, ...)" }, { "code": null, "e": 1520, "s": 1509, "text": "Arguments:" }, { "code": null, "e": 1583, "s": 1520, "text": "file: the name of the file which the data are to be read from." }, { "code": null, "e": 1852, "s": 1583, "text": "header: a logical value indicating whether the file contains the names of the variables as its first line. If missing, the value is determined from the file format: header is set to TRUE if and only if the first row contains one fewer field than the number of columns." }, { "code": null, "e": 2090, "s": 1852, "text": "sep: the field separator character. Values on each line of the file are separated by this character. If sep = “” (the default for read.table) the separator is ‘white space’, that is one or more spaces, tabs, newlines or carriage returns." }, { "code": null, "e": 2128, "s": 2090, "text": "quote: the set of quoting characters." }, { "code": null, "e": 2184, "s": 2128, "text": "dec: the character used in the file for decimal points." }, { "code": null, "e": 2285, "s": 2184, "text": "fill: logical. If TRUE then in case the rows have unequal length, blank fields are implicitly added." }, { "code": null, "e": 2393, "s": 2285, "text": "comment.char: character: a character vector of length one containing a single character or an empty string." }, { "code": null, "e": 2432, "s": 2393, "text": "... : Further arguments to be passed." }, { "code": null, "e": 2441, "s": 2432, "text": "Example:" }, { "code": null, "e": 2443, "s": 2441, "text": "R" }, { "code": "sdata <- read.csv(\"SampleData.csv\", header = TRUE, sep = \",\")sdata # views the data frame formed from the csv fileView(sdata)", "e": 2570, "s": 2443, "text": null }, { "code": null, "e": 2578, "s": 2570, "text": "Output:" }, { "code": null, "e": 2783, "s": 2578, "text": "Now that, we have created our dataframe, we can perform some operations on it. The data read according to the usage from dataframe. Given below are two examples who read the data as per their requirement." }, { "code": null, "e": 2794, "s": 2783, "text": "Example 1:" }, { "code": null, "e": 2796, "s": 2794, "text": "R" }, { "code": "sdata <- read.csv( \"SampleData.csv\", header = TRUE, sep = \",\") highspeed <- subset( sdata, sdata$speed == max(sdata$speed)) # views the subsetted value in # tabular formView(highspeed)", "e": 2985, "s": 2796, "text": null }, { "code": null, "e": 2993, "s": 2985, "text": "Output:" }, { "code": null, "e": 3004, "s": 2993, "text": "Example 2:" }, { "code": null, "e": 3006, "s": 3004, "text": "R" }, { "code": "sdata <- read.csv( \"SampleData.csv\", header = TRUE, sep = \",\") highfreq <- subset( sdata, sdata$cyc_freq == \"Several times per week\") # views the information, of the above # condition in tabular formatView(highfreq)", "e": 3226, "s": 3006, "text": null }, { "code": null, "e": 3234, "s": 3226, "text": "Output:" }, { "code": null, "e": 3241, "s": 3234, "text": "Picked" }, { "code": null, "e": 3247, "s": 3241, "text": "R-CSV" }, { "code": null, "e": 3258, "s": 3247, "text": "R Language" }, { "code": null, "e": 3356, "s": 3258, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 3408, "s": 3356, "text": "Change Color of Bars in Barchart using ggplot2 in R" }, { "code": null, "e": 3466, "s": 3408, "text": "How to Split Column Into Multiple Columns in R DataFrame?" }, { "code": null, "e": 3501, "s": 3466, "text": "Group by function in R using Dplyr" }, { "code": null, "e": 3539, "s": 3501, "text": "How to Change Axis Scales in R Plots?" }, { "code": null, "e": 3588, "s": 3539, "text": "How to filter R DataFrame by values in a column?" }, { "code": null, "e": 3605, "s": 3588, "text": "R - if statement" }, { "code": null, "e": 3642, "s": 3605, "text": "Logistic Regression in R Programming" }, { "code": null, "e": 3685, "s": 3642, "text": "Replace Specific Characters in String in R" }, { "code": null, "e": 3722, "s": 3685, "text": "How to import an Excel File into R ?" } ]
Python next() method
20 Jun, 2022 Python next() function returns the next item of an iterator. In this article, we will cover next() syntax, next() parameters, next() returns. Syntax : next(iter, stopdef) Parameters : iter : The iterator over which iteration is to be performed. stopdef : Default value to be printed if we reach end of iterator. Returns : Returns next element from the list, if not present prints the default value. If default value is not present, raises the StopIteration error. Here we will see the python next() in loop. Python3 # Python code to demonstrate# working of next() # initializing listlist1 = [1, 2, 3, 4, 5] # converting list to iteratorlist1 = iter(list1) print("The contents of list are : ") # printing using next()# using defaultwhile (1): val = next(list1, 'end') if val == 'end': print('list end') break else: print(val) Output: The contents of list are : 1 2 3 4 5 list end Python3 list1 = [1, 2, 3, 4, 5] # converting list to iteratorlist1 = iter(list1) print(list1)print(next(list1))print(next(list1))print(next(list1)) Output: <list_iterator object at 0x0000021D7C801D88> 1 2 3 Python3 list1 = [1, 2, 3, 4, 5] # converting list to iteratorlist1 = iter(list1) print(list1)print(next(list1, -1))print(next(list1, -1))print(next(list1, -1))print(next(list1, -1))print(next(list1, -1))print(next(list1, -1))print(next(list1, -1)) Output: <list_iterator object at 0x0000021D7AE08908> 1 2 3 4 5 -1 -1 Python3 list1 = [1, 2, 3, 4, 5] # converting list to iteratorlist1 = iter(list1) print(list1)print(next(list1))print(next(list1))print(next(list1))print(next(list1))print(next(list1))print(next(list1)) Output: <list_iterator object at 0x0000021D7ADF55C8> 1 2 3 4 5 --------------------------------------------------------------------------- StopIteration Traceback (most recent call last) <ipython-input-17-02f0e1df3bbe> in <module> 10 print(next(list1)) 11 print(next(list1)) ---> 12 print(next(list1)) StopIteration: While calling out of the range of iterator then it rises Stopiteration error, to avoid this error we will use the default value as an argument. Python3 # Python code to demonstrate# next() vs for loopimport time # initializing listlist1 = [1, 2, 3, 4, 5] # keeping list2list2 = list1 # converting list to iteratorlist1 = iter(list1) print("The contents of list are : ") # printing using next()# using defaultstart_next = time.time()while (1): val = next(list1, 'end') if val == 'end': break else: print(val)print("Time taken for next() is : " + str(time.time() - start_next)) # printing using for loopstart_for = time.time()for i in list2: print(i)print("Time taken for loop is : " + str(time.time() - start_for)) Output: The contents of list are : 1 2 3 4 5 Time taken for next() is : 5.96046447754e-06 1 2 3 4 5 Time taken for loop is : 1.90734863281e-06 Result: Python next in For loop is a better choice when printing the contents of the list than next(). Applications: next() is the utility function for printing the components of the container of iter type. Its usage is when the size of the container is not known or we need to give a prompt when the list/iterator has exhausted. kumar_satyam vinayedula Python-Built-in-functions Python Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 28, "s": 0, "text": "\n20 Jun, 2022" }, { "code": null, "e": 170, "s": 28, "text": "Python next() function returns the next item of an iterator. In this article, we will cover next() syntax, next() parameters, next() returns." }, { "code": null, "e": 199, "s": 170, "text": "Syntax : next(iter, stopdef)" }, { "code": null, "e": 213, "s": 199, "text": "Parameters : " }, { "code": null, "e": 274, "s": 213, "text": "iter : The iterator over which iteration is to be performed." }, { "code": null, "e": 341, "s": 274, "text": "stopdef : Default value to be printed if we reach end of iterator." }, { "code": null, "e": 493, "s": 341, "text": "Returns : Returns next element from the list, if not present prints the default value. If default value is not present, raises the StopIteration error." }, { "code": null, "e": 537, "s": 493, "text": "Here we will see the python next() in loop." }, { "code": null, "e": 545, "s": 537, "text": "Python3" }, { "code": "# Python code to demonstrate# working of next() # initializing listlist1 = [1, 2, 3, 4, 5] # converting list to iteratorlist1 = iter(list1) print(\"The contents of list are : \") # printing using next()# using defaultwhile (1): val = next(list1, 'end') if val == 'end': print('list end') break else: print(val)", "e": 884, "s": 545, "text": null }, { "code": null, "e": 892, "s": 884, "text": "Output:" }, { "code": null, "e": 939, "s": 892, "text": "The contents of list are : \n1\n2\n3\n4\n5\nlist end" }, { "code": null, "e": 947, "s": 939, "text": "Python3" }, { "code": "list1 = [1, 2, 3, 4, 5] # converting list to iteratorlist1 = iter(list1) print(list1)print(next(list1))print(next(list1))print(next(list1))", "e": 1087, "s": 947, "text": null }, { "code": null, "e": 1095, "s": 1087, "text": "Output:" }, { "code": null, "e": 1146, "s": 1095, "text": "<list_iterator object at 0x0000021D7C801D88>\n1\n2\n3" }, { "code": null, "e": 1154, "s": 1146, "text": "Python3" }, { "code": "list1 = [1, 2, 3, 4, 5] # converting list to iteratorlist1 = iter(list1) print(list1)print(next(list1, -1))print(next(list1, -1))print(next(list1, -1))print(next(list1, -1))print(next(list1, -1))print(next(list1, -1))print(next(list1, -1))", "e": 1394, "s": 1154, "text": null }, { "code": null, "e": 1402, "s": 1394, "text": "Output:" }, { "code": null, "e": 1463, "s": 1402, "text": "<list_iterator object at 0x0000021D7AE08908>\n1\n2\n3\n4\n5\n-1\n-1" }, { "code": null, "e": 1471, "s": 1463, "text": "Python3" }, { "code": "list1 = [1, 2, 3, 4, 5] # converting list to iteratorlist1 = iter(list1) print(list1)print(next(list1))print(next(list1))print(next(list1))print(next(list1))print(next(list1))print(next(list1))", "e": 1665, "s": 1471, "text": null }, { "code": null, "e": 1673, "s": 1665, "text": "Output:" }, { "code": null, "e": 2020, "s": 1673, "text": "<list_iterator object at 0x0000021D7ADF55C8>\n1\n2\n3\n4\n5\n---------------------------------------------------------------------------\nStopIteration Traceback (most recent call last)\n<ipython-input-17-02f0e1df3bbe> in <module>\n 10 print(next(list1))\n 11 print(next(list1))\n---> 12 print(next(list1))\n\nStopIteration: " }, { "code": null, "e": 2164, "s": 2020, "text": "While calling out of the range of iterator then it rises Stopiteration error, to avoid this error we will use the default value as an argument." }, { "code": null, "e": 2172, "s": 2164, "text": "Python3" }, { "code": "# Python code to demonstrate# next() vs for loopimport time # initializing listlist1 = [1, 2, 3, 4, 5] # keeping list2list2 = list1 # converting list to iteratorlist1 = iter(list1) print(\"The contents of list are : \") # printing using next()# using defaultstart_next = time.time()while (1): val = next(list1, 'end') if val == 'end': break else: print(val)print(\"Time taken for next() is : \" + str(time.time() - start_next)) # printing using for loopstart_for = time.time()for i in list2: print(i)print(\"Time taken for loop is : \" + str(time.time() - start_for))", "e": 2760, "s": 2172, "text": null }, { "code": null, "e": 2769, "s": 2760, "text": "Output: " }, { "code": null, "e": 2905, "s": 2769, "text": "The contents of list are : \n1\n2\n3\n4\n5\nTime taken for next() is : 5.96046447754e-06\n1\n2\n3\n4\n5\nTime taken for loop is : 1.90734863281e-06" }, { "code": null, "e": 3008, "s": 2905, "text": "Result: Python next in For loop is a better choice when printing the contents of the list than next()." }, { "code": null, "e": 3235, "s": 3008, "text": "Applications: next() is the utility function for printing the components of the container of iter type. Its usage is when the size of the container is not known or we need to give a prompt when the list/iterator has exhausted." }, { "code": null, "e": 3248, "s": 3235, "text": "kumar_satyam" }, { "code": null, "e": 3259, "s": 3248, "text": "vinayedula" }, { "code": null, "e": 3285, "s": 3259, "text": "Python-Built-in-functions" }, { "code": null, "e": 3292, "s": 3285, "text": "Python" } ]
Java String join() with examples
04 Dec, 2018 The java.lang.string.join() method concatenates the given elements with the delimiter and returns the concatenated string.Note that if an element is null, then null is added.The join() method is included in java string since JDK 1.8.There are two types of join() methods in java string.Syntax: public static String join(CharSequence deli, CharSequence... ele) and public static String join (CharSequence deli, Iterable<? extends CharSequence> ele) Parameters: deli- delimiter to be attached with each element ele- string or char to be attached with delimiter Returns : string joined with delimiter. // Java program to demonstrate// working of join() method class Gfg1 { public static void main(String args[]) { // delimiter is "<" and elements are "Four", "Five", "Six", "Seven" String gfg1 = String.join(" < ", "Four", "Five", "Six", "Seven"); System.out.println(gfg1); }} Output: Four < Five < Six < Seven // Java program to demonstrate// working of join() method class Gfg2 { public static void main(String args[]) { // delimiter is " " and elements are "My", // "name", "is", "Niraj", "Pandey" String gfg2 = String.join(" ", "My", "name", "is", "Niraj", "Pandey"); System.out.println(gfg2); }} Output: My name is Niraj Pandey // Java program to demonstrate// working of join() method class Gfg3 { public static void main(String args[]) { // delimiter is "->" and elements are "Wake up", // "Eat", "Play", "Sleep", "Wake up" String gfg3 = String.join("-> ", "Wake up", "Eat", "Play", "Sleep", "Wake up"); System.out.println(gfg3); }} Output: Wake up-> Eat-> Play-> Sleep-> Wake up Java-Functions Java-lang package Java-Strings Java Java-Strings Java Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Object Oriented Programming (OOPs) Concept in Java How to iterate any Map in Java Interfaces in Java HashMap in Java with Examples ArrayList in Java Stream In Java Collections in Java Multidimensional Arrays in Java Singleton Class in Java Stack Class in Java
[ { "code": null, "e": 52, "s": 24, "text": "\n04 Dec, 2018" }, { "code": null, "e": 346, "s": 52, "text": "The java.lang.string.join() method concatenates the given elements with the delimiter and returns the concatenated string.Note that if an element is null, then null is added.The join() method is included in java string since JDK 1.8.There are two types of join() methods in java string.Syntax:" }, { "code": null, "e": 663, "s": 346, "text": "public static String join(CharSequence deli, CharSequence... ele) \nand \npublic static String join\n(CharSequence deli, Iterable<? extends CharSequence> ele) \nParameters:\ndeli- delimiter to be attached with each element \nele- string or char to be attached with delimiter\nReturns : string joined with delimiter.\n" }, { "code": "// Java program to demonstrate// working of join() method class Gfg1 { public static void main(String args[]) { // delimiter is \"<\" and elements are \"Four\", \"Five\", \"Six\", \"Seven\" String gfg1 = String.join(\" < \", \"Four\", \"Five\", \"Six\", \"Seven\"); System.out.println(gfg1); }}", "e": 971, "s": 663, "text": null }, { "code": null, "e": 979, "s": 971, "text": "Output:" }, { "code": null, "e": 1006, "s": 979, "text": "Four < Five < Six < Seven\n" }, { "code": "// Java program to demonstrate// working of join() method class Gfg2 { public static void main(String args[]) { // delimiter is \" \" and elements are \"My\", // \"name\", \"is\", \"Niraj\", \"Pandey\" String gfg2 = String.join(\" \", \"My\", \"name\", \"is\", \"Niraj\", \"Pandey\"); System.out.println(gfg2); }}", "e": 1338, "s": 1006, "text": null }, { "code": null, "e": 1346, "s": 1338, "text": "Output:" }, { "code": null, "e": 1371, "s": 1346, "text": "My name is Niraj Pandey\n" }, { "code": "// Java program to demonstrate// working of join() method class Gfg3 { public static void main(String args[]) { // delimiter is \"->\" and elements are \"Wake up\", // \"Eat\", \"Play\", \"Sleep\", \"Wake up\" String gfg3 = String.join(\"-> \", \"Wake up\", \"Eat\", \"Play\", \"Sleep\", \"Wake up\"); System.out.println(gfg3); }}", "e": 1742, "s": 1371, "text": null }, { "code": null, "e": 1750, "s": 1742, "text": "Output:" }, { "code": null, "e": 1790, "s": 1750, "text": "Wake up-> Eat-> Play-> Sleep-> Wake up\n" }, { "code": null, "e": 1805, "s": 1790, "text": "Java-Functions" }, { "code": null, "e": 1823, "s": 1805, "text": "Java-lang package" }, { "code": null, "e": 1836, "s": 1823, "text": "Java-Strings" }, { "code": null, "e": 1841, "s": 1836, "text": "Java" }, { "code": null, "e": 1854, "s": 1841, "text": "Java-Strings" }, { "code": null, "e": 1859, "s": 1854, "text": "Java" }, { "code": null, "e": 1957, "s": 1859, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 2008, "s": 1957, "text": "Object Oriented Programming (OOPs) Concept in Java" }, { "code": null, "e": 2039, "s": 2008, "text": "How to iterate any Map in Java" }, { "code": null, "e": 2058, "s": 2039, "text": "Interfaces in Java" }, { "code": null, "e": 2088, "s": 2058, "text": "HashMap in Java with Examples" }, { "code": null, "e": 2106, "s": 2088, "text": "ArrayList in Java" }, { "code": null, "e": 2121, "s": 2106, "text": "Stream In Java" }, { "code": null, "e": 2141, "s": 2121, "text": "Collections in Java" }, { "code": null, "e": 2173, "s": 2141, "text": "Multidimensional Arrays in Java" }, { "code": null, "e": 2197, "s": 2173, "text": "Singleton Class in Java" } ]
Print Left View of a Binary Tree
21 Jun, 2022 Given a Binary Tree, print left view of it. Left view of a Binary Tree is set of nodes visible when tree is visited from left side. Examples: Input : 1 / \ 2 3 / \ \ 4 5 6 Output : 1 2 4 Input : 1 / \ 2 3 \ 4 \ 5 \ 6 Output :1 2 4 5 6 Method-1 (Using Recursion): The left view contains all nodes that are first nodes in their levels. A simple solution is to do level order traversal and print the first node in every level. The problem can also be solved using simple recursive traversal. We can keep track of the level of a node by passing a parameter to all recursive calls. The idea is to keep track of the maximum level also. Whenever we see a node whose level is more than maximum level so far, we print the node because this is the first node in its level (Note that we traverse the left subtree before right subtree). Chapters descriptions off, selected captions settings, opens captions settings dialog captions off, selected English This is a modal window. Beginning of dialog window. Escape will cancel and close the window. End of dialog window. Below is the implementation of the above idea- C++ C Java Python C# Javascript // C++ program to print left view of Binary Tree#include <bits/stdc++.h>using namespace std; struct Node{ int data; struct Node *left, *right;}; // A utility function to// create a new Binary Tree Nodestruct Node *newNode(int item){ struct Node *temp = (struct Node *)malloc( sizeof(struct Node)); temp->data = item; temp->left = temp->right = NULL; return temp;} // Recursive function to print// left view of a binary tree.void leftViewUtil(struct Node *root, int level, int *max_level){ // Base Case if (root == NULL) return; // If this is the first Node of its level if (*max_level < level) { cout << root->data << " "; *max_level = level; } // Recur for left subtree first, // then right subtree leftViewUtil(root->left, level + 1, max_level); leftViewUtil(root->right, level + 1, max_level); } // A wrapper over leftViewUtil()void leftView(struct Node *root){ int max_level = 0; leftViewUtil(root, 1, &max_level);} // Driver Codeint main(){ Node* root = newNode(10); root->left = newNode(2); root->right = newNode(3); root->left->left = newNode(7); root->left->right = newNode(8); root->right->right = newNode(15); root->right->left = newNode(12); root->right->right->left = newNode(14); leftView(root); return 0;} // C program to print left view of Binary Tree#include <stdio.h>#include <stdlib.h> struct node { int data; struct node *left, *right;}; // A utility function to create a new Binary Tree nodestruct node* newNode(int item){ struct node* temp = (struct node*)malloc(sizeof(struct node)); temp->data = item; temp->left = temp->right = NULL; return temp;} // Recursive function to print left view of a binary tree.void leftViewUtil(struct node* root, int level, int* max_level){ // Base Case if (root == NULL) return; // If this is the first node of its level if (*max_level < level) { printf("%d\t", root->data); *max_level = level; } // Recur for left and right subtrees leftViewUtil(root->left, level + 1, max_level); leftViewUtil(root->right, level + 1, max_level);} // A wrapper over leftViewUtil()void leftView(struct node* root){ int max_level = 0; leftViewUtil(root, 1, &max_level);} // Driver codeint main(){ struct node* root = newNode(10); root->left = newNode(2); root->right = newNode(3); root->left->left = newNode(7); root->left->right = newNode(8); root->right->right = newNode(15); root->right->left = newNode(12); root->right->right->left = newNode(14); leftView(root); return 0;} // Java program to print left view of binary tree /* Class containing left and right child of currentnode and key value*/class Node { int data; Node left, right; public Node(int item) { data = item; left = right = null; }} /* Class to print the left view */class BinaryTree { Node root; static int max_level = 0; // recursive function to print left view void leftViewUtil(Node node, int level) { // Base Case if (node == null) return; // If this is the first node of its level if (max_level < level) { System.out.print(" " + node.data); max_level = level; } // Recur for left and right subtrees leftViewUtil(node.left, level + 1); leftViewUtil(node.right, level + 1); } // A wrapper over leftViewUtil() void leftView() { max_level = 0; leftViewUtil(root, 1); } /* testing for example nodes */ public static void main(String args[]) { /* creating a binary tree and entering the nodes */ BinaryTree tree = new BinaryTree(); tree.root = new Node(10); tree.root.left = new Node(2); tree.root.right = new Node(3); tree.root.left.left = new Node(7); tree.root.left.right = new Node(8); tree.root.right.right = new Node(15); tree.root.right.left = new Node(12); tree.root.right.right.left = new Node(14); tree.leftView(); }} # Python program to print left view of Binary Tree # A binary tree nodeclass Node: # Constructor to create a new node def __init__(self, data): self.data = data self.left = None self.right = None # Recursive function print left view of a binary treedef leftViewUtil(root, level, max_level): # Base Case if root is None: return # If this is the first node of its level if (max_level[0] < level): print "% d\t" %(root.data), max_level[0] = level # Recur for left and right subtree leftViewUtil(root.left, level + 1, max_level) leftViewUtil(root.right, level + 1, max_level) # A wrapper over leftViewUtil()def leftView(root): max_level = [0] leftViewUtil(root, 1, max_level) # Driver program to test above function root = Node(10)root.left = Node(2)root.right = Node(3)root.left.left = Node(7)root.left.right = Node(8)root.right.right = Node(15)root.right.left = Node(12)root.right.right.left = Node(14) leftView(root) # This code is contributed by Nikhil Kumar Singh(nickzuck_007) using System; // C# program to print left view of binary tree /* Class containing left and right child of currentnode and key value*/public class Node { public int data; public Node left, right; public Node(int item) { data = item; left = right = null; }} /* Class to print the left view */public class BinaryTree { public Node root; public static int max_level = 0; // recursive function to print left view public virtual void leftViewUtil(Node node, int level) { // Base Case if (node == null) { return; } // If this is the first node of its level if (max_level < level) { Console.Write(" " + node.data); max_level = level; } // Recur for left and right subtrees leftViewUtil(node.left, level + 1); leftViewUtil(node.right, level + 1); } // A wrapper over leftViewUtil() public virtual void leftView() { leftViewUtil(root, 1); } /* testing for example nodes */ public static void Main(string[] args) { /* creating a binary tree and entering the nodes */ BinaryTree tree = new BinaryTree(); tree.root = new Node(10); tree.root.left = new Node(2); tree.root.right = new Node(3); tree.root.left.left = new Node(7); tree.root.left.right = new Node(8); tree.root.right.right = new Node(15); tree.root.right.left = new Node(12); tree.root.right.right.left = new Node(14); tree.leftView(); }} // This code is contributed by Shrikant13 <script> // Javascript program to print left view// of binary tree // Class containing left and right// child of current node and key valueclass Node{ constructor(item) { this.data = item; this.left = null; this.right = null; }} // Class to print the left viewvar root ;var max_level = 0; // Recursive function to print left viewfunction leftViewUtil(node, level){ // Base Case if (node == null) { return; } // If this is the first node of its level if (max_level < level) { document.write(" " + node.data); max_level = level; } // Recur for left and right subtrees leftViewUtil(node.left, level + 1); leftViewUtil(node.right, level + 1);} // A wrapper over leftViewUtil()function leftView(){ leftViewUtil(root, 1);} // Driver code // Testing for example nodes// Creating a binary tree and// entering the nodesroot = Node(10)root.left = new Node(2)root.right = new Node(3)root.left.left = new Node(7)root.left.right = new Node(8)root.right.right = new Node(15)root.right.left = new Node(12)root.right.right.left = new Node(14) leftView(); // This code is contributed by rrrtnx </script> 10 2 7 14 Time Complexity: The function does a simple traversal of the tree, so the complexity is O(n). Auxiliary Space: O(n), due to the stack space during recursive call. Method-2 (Using Queue): In this method, level order traversal based solution is discussed. If we observe carefully, we will see that our main task is to print the left most node of every level. So, we will do a level order traversal on the tree and print the leftmost node at every level. Below is the implementation of above approach: C++ Java Python C# Javascript // C++ program to print left view of// Binary Tree #include<bits/stdc++.h>using namespace std; // A Binary Tree Nodestruct Node{ int data; struct Node *left, *right;}; // Utility function to create a new tree nodeNode* newNode(int data){ Node *temp = new Node; temp->data = data; temp->left = temp->right = NULL; return temp;} // function to print left view of// binary treevoid printLeftView(Node* root){ if (!root) return; queue<Node*> q; q.push(root); while (!q.empty()) { // number of nodes at current level int n = q.size(); // Traverse all nodes of current level for(int i = 1; i <= n; i++) { Node* temp = q.front(); q.pop(); // Print the left most element // at the level if (i == 1) cout<<temp->data<<" "; // Add left node to queue if (temp->left != NULL) q.push(temp->left); // Add right node to queue if (temp->right != NULL) q.push(temp->right); } }} // Driver codeint main(){ // Let's construct the tree as // shown in example Node* root = newNode(10); root->left = newNode(2); root->right = newNode(3); root->left->left = newNode(7); root->left->right = newNode(8); root->right->right = newNode(15); root->right->left = newNode(12); root->right->right->left = newNode(14); printLeftView(root);} // This code is contributed by// Manne SreeCharan // Java program to print left view of Binary// Treeimport java.util.*; public class PrintRightView { // Binary tree node private static class Node { int data; Node left, right; public Node(int data) { this.data = data; this.left = null; this.right = null; } } // function to print left view of binary tree private static void printLeftView(Node root) { if (root == null) return; Queue<Node> queue = new LinkedList<>(); queue.add(root); while (!queue.isEmpty()) { // number of nodes at current level int n = queue.size(); // Traverse all nodes of current level for (int i = 1; i <= n; i++) { Node temp = queue.poll(); // Print the left most element at // the level if (i == 1) System.out.print(temp.data + " "); // Add left node to queue if (temp.left != null) queue.add(temp.left); // Add right node to queue if (temp.right != null) queue.add(temp.right); } } } // Driver code public static void main(String[] args) { // construct binary tree as shown in // above diagram Node root = new Node(10); root.left = new Node(2); root.right = new Node(3); root.left.left = new Node(7); root.left.right = new Node(8); root.right.right = new Node(15); root.right.left = new Node(12); root.right.right.left = new Node(14); printLeftView(root); }} // This code is contributed by// Manne SreeCharan # Python3 program to print left view of# Binary Tree # Binary Tree Node""" utility that allocates a newNodewith the given key """ class newNode: # Construct to create a newNode def __init__(self, key): self.data = key self.left = None self.right = None self.hd = 0 # function to print left view of# binary tree def printLeftView(root): if (not root): return q = [] q.append(root) while (len(q)): # number of nodes at current level n = len(q) # Traverse all nodes of current level for i in range(1, n + 1): temp = q[0] q.pop(0) # Print the left most element # at the level if (i == 1): print(temp.data, end=" ") # Add left node to queue if (temp.left != None): q.append(temp.left) # Add right node to queue if (temp.right != None): q.append(temp.right) # Driver Codeif __name__ == '__main__': root = newNode(10) root.left = newNode(2) root.right = newNode(3) root.left.left = newNode(7) root.left.right = newNode(8) root.right.right = newNode(15) root.right.left = newNode(12) root.right.right.left = newNode(14) printLeftView(root) # This code is contributed by# Manne SreeCharan // C# program to print left view// of Binary Treeusing System;using System.Collections.Generic; public class PrintRightView { // Binary tree node private class Node { public int data; public Node left, right; public Node(int data) { this.data = data; this.left = null; this.right = null; } } // function to print left view of binary tree private static void printRightView(Node root) { if (root == null) return; Queue<Node> queue = new Queue<Node>(); queue.Enqueue(root); while (queue.Count != 0) { // number of nodes at current level int n = queue.Count; // Traverse all nodes of current level for (int i = 1; i <= n; i++) { Node temp = queue.Dequeue(); // Print the left most element at // the level if (i == n) Console.Write(temp.data + " "); // Add left node to queue if (temp.left != null) queue.Enqueue(temp.left); // Add right node to queue if (temp.right != null) queue.Enqueue(temp.right); } } } // Driver code public static void Main(String[] args) { // construct binary tree as shown in // above diagram Node root = new Node(10); root.left = new Node(2); root.right = new Node(3); root.left.left = new Node(7); root.left.right = new Node(8); root.right.right = new Node(15); root.right.left = new Node(12); root.right.right.left = new Node(14); printRightView(root); }} // This code is contributed Manne SreeCharan <script> // JavaScript program to print left view of// Binary Treeclass newNode{ // Construct to create a newNode constructor(key){ this.data = key this.left = null this.right = null this.hd = 0 }} // function to print left view of// binary treefunction printLeftView(root){ if (root == null) return let q = [] q.push(root) while (q.length){ // number of nodes at current level let n = q.length // Traverse all nodes of current level for(let i=1;i< n + 1;i++){ let temp = q.shift() // Print the left most element // at the level if (i == 1) document.write(temp.data," ") // Add left node to queue if (temp.left != null) q.push(temp.left) // Add right node to queue if (temp.right != null) q.push(temp.right) } }} // Driver Codelet root = new newNode(10)root.left = new newNode(2)root.right = new newNode(3)root.left.left = new newNode(7)root.left.right = new newNode(8)root.right.right = new newNode(15)root.right.left = new newNode(12)root.right.right.left = new newNode(14)printLeftView(root) // This code is contributed by shinjanpatra </script> 10 2 7 14 Time Complexity: O(n), where n is the number of nodes in the binary tree.Auxiliary Space: O(n) since using space for auxiliary queue Method 3: Using queue and a null pointer to mark the first element of each level. we insert a null pointer in the first and as reach that null pointer we mark bool as true and take the next element as our left view element C++ #include <bits/stdc++.h>using namespace std; struct Node{ int data; struct Node *left, *right;}; // A utility function to// create a new Binary Tree Nodestruct Node *newNode(int item){ struct Node *temp = (struct Node *)malloc( sizeof(struct Node)); temp->data = item; temp->left = temp->right = NULL; return temp;} vector<int> leftView(Node *root){ // Your code here vector<int>ans; if(!root) { return ans; } queue<Node*>q; q.push(root); q.push(NULL); bool ok=true; while(!q.empty()) { auto it=q.front(); q.pop(); if(it==NULL) { if(ok==false) { ok=true; } if(q.size()==0) { break; } else { q.push(NULL); } } else { if(ok) { ans.push_back(it->data); ok=false; } if(it->left) { q.push(it->left); } if(it->right) { q.push(it->right); } } } return ans;}int main(){ Node* root = newNode(10); root->left = newNode(2); root->right = newNode(3); root->left->left = newNode(7); root->left->right = newNode(8); root->right->right = newNode(15); root->right->left = newNode(12); root->right->right->left = newNode(14); vector<int> vec = leftView(root); for(int x : vec) cout<<x<<" "; cout << endl; return 0;} 10 2 7 14 Time Complexity: O(n) where n is the total number of nodes.Auxiliary Space: O(n) due to the space occupied by queue. shrikanth13 rathbhupendra hunter2000 sukhoi33 gnitish31 AakashYadav4 Rakesh Kumar Mallick rrrtnx sweetyty iliyazali44 zaid47304 noah28 cc8gcwb6nkmesp932i6tfsqsu6dl3vthdbax4wf0 shinjanpatra sarthak17jain polymatir3j hardikkoriintern Accolite Amazon Flipkart Knowlarity MakeMyTrip Ola Cabs Open Solutions Paytm Qualcomm Samsung Snapdeal tree-view Twitter Tree Paytm Flipkart Accolite Amazon Samsung Snapdeal MakeMyTrip Ola Cabs Qualcomm Twitter Knowlarity Open Solutions Tree Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. AVL Tree | Set 1 (Insertion) Introduction to Data Structures What is Data Structure: Types, Classifications and Applications A program to check if a binary tree is BST or not Decision Tree Top 50 Tree Coding Problems for Interviews Segment Tree | Set 1 (Sum of given range) Overview of Data Structures | Set 2 (Binary Tree, BST, Heap and Hash) Complexity of different operations in Binary tree, Binary Search Tree and AVL tree Sorted Array to Balanced BST
[ { "code": null, "e": 54, "s": 26, "text": "\n21 Jun, 2022" }, { "code": null, "e": 186, "s": 54, "text": "Given a Binary Tree, print left view of it. Left view of a Binary Tree is set of nodes visible when tree is visited from left side." }, { "code": null, "e": 197, "s": 186, "text": "Examples: " }, { "code": null, "e": 487, "s": 197, "text": "Input : \n 1\n / \\\n 2 3\n / \\ \\\n 4 5 6 \nOutput : 1 2 4\n\nInput :\n 1\n / \\\n 2 3\n \\ \n 4 \n \\\n 5\n \\\n 6\nOutput :1 2 4 5 6" }, { "code": null, "e": 676, "s": 487, "text": "Method-1 (Using Recursion): The left view contains all nodes that are first nodes in their levels. A simple solution is to do level order traversal and print the first node in every level." }, { "code": null, "e": 1078, "s": 676, "text": "The problem can also be solved using simple recursive traversal. We can keep track of the level of a node by passing a parameter to all recursive calls. The idea is to keep track of the maximum level also. Whenever we see a node whose level is more than maximum level so far, we print the node because this is the first node in its level (Note that we traverse the left subtree before right subtree). " }, { "code": null, "e": 1087, "s": 1078, "text": "Chapters" }, { "code": null, "e": 1114, "s": 1087, "text": "descriptions off, selected" }, { "code": null, "e": 1164, "s": 1114, "text": "captions settings, opens captions settings dialog" }, { "code": null, "e": 1187, "s": 1164, "text": "captions off, selected" }, { "code": null, "e": 1195, "s": 1187, "text": "English" }, { "code": null, "e": 1219, "s": 1195, "text": "This is a modal window." }, { "code": null, "e": 1288, "s": 1219, "text": "Beginning of dialog window. Escape will cancel and close the window." }, { "code": null, "e": 1310, "s": 1288, "text": "End of dialog window." }, { "code": null, "e": 1358, "s": 1310, "text": "Below is the implementation of the above idea- " }, { "code": null, "e": 1362, "s": 1358, "text": "C++" }, { "code": null, "e": 1364, "s": 1362, "text": "C" }, { "code": null, "e": 1369, "s": 1364, "text": "Java" }, { "code": null, "e": 1376, "s": 1369, "text": "Python" }, { "code": null, "e": 1379, "s": 1376, "text": "C#" }, { "code": null, "e": 1390, "s": 1379, "text": "Javascript" }, { "code": "// C++ program to print left view of Binary Tree#include <bits/stdc++.h>using namespace std; struct Node{ int data; struct Node *left, *right;}; // A utility function to// create a new Binary Tree Nodestruct Node *newNode(int item){ struct Node *temp = (struct Node *)malloc( sizeof(struct Node)); temp->data = item; temp->left = temp->right = NULL; return temp;} // Recursive function to print// left view of a binary tree.void leftViewUtil(struct Node *root, int level, int *max_level){ // Base Case if (root == NULL) return; // If this is the first Node of its level if (*max_level < level) { cout << root->data << \" \"; *max_level = level; } // Recur for left subtree first, // then right subtree leftViewUtil(root->left, level + 1, max_level); leftViewUtil(root->right, level + 1, max_level); } // A wrapper over leftViewUtil()void leftView(struct Node *root){ int max_level = 0; leftViewUtil(root, 1, &max_level);} // Driver Codeint main(){ Node* root = newNode(10); root->left = newNode(2); root->right = newNode(3); root->left->left = newNode(7); root->left->right = newNode(8); root->right->right = newNode(15); root->right->left = newNode(12); root->right->right->left = newNode(14); leftView(root); return 0;}", "e": 2756, "s": 1390, "text": null }, { "code": "// C program to print left view of Binary Tree#include <stdio.h>#include <stdlib.h> struct node { int data; struct node *left, *right;}; // A utility function to create a new Binary Tree nodestruct node* newNode(int item){ struct node* temp = (struct node*)malloc(sizeof(struct node)); temp->data = item; temp->left = temp->right = NULL; return temp;} // Recursive function to print left view of a binary tree.void leftViewUtil(struct node* root, int level, int* max_level){ // Base Case if (root == NULL) return; // If this is the first node of its level if (*max_level < level) { printf(\"%d\\t\", root->data); *max_level = level; } // Recur for left and right subtrees leftViewUtil(root->left, level + 1, max_level); leftViewUtil(root->right, level + 1, max_level);} // A wrapper over leftViewUtil()void leftView(struct node* root){ int max_level = 0; leftViewUtil(root, 1, &max_level);} // Driver codeint main(){ struct node* root = newNode(10); root->left = newNode(2); root->right = newNode(3); root->left->left = newNode(7); root->left->right = newNode(8); root->right->right = newNode(15); root->right->left = newNode(12); root->right->right->left = newNode(14); leftView(root); return 0;}", "e": 4080, "s": 2756, "text": null }, { "code": "// Java program to print left view of binary tree /* Class containing left and right child of currentnode and key value*/class Node { int data; Node left, right; public Node(int item) { data = item; left = right = null; }} /* Class to print the left view */class BinaryTree { Node root; static int max_level = 0; // recursive function to print left view void leftViewUtil(Node node, int level) { // Base Case if (node == null) return; // If this is the first node of its level if (max_level < level) { System.out.print(\" \" + node.data); max_level = level; } // Recur for left and right subtrees leftViewUtil(node.left, level + 1); leftViewUtil(node.right, level + 1); } // A wrapper over leftViewUtil() void leftView() { max_level = 0; leftViewUtil(root, 1); } /* testing for example nodes */ public static void main(String args[]) { /* creating a binary tree and entering the nodes */ BinaryTree tree = new BinaryTree(); tree.root = new Node(10); tree.root.left = new Node(2); tree.root.right = new Node(3); tree.root.left.left = new Node(7); tree.root.left.right = new Node(8); tree.root.right.right = new Node(15); tree.root.right.left = new Node(12); tree.root.right.right.left = new Node(14); tree.leftView(); }}", "e": 5576, "s": 4080, "text": null }, { "code": "# Python program to print left view of Binary Tree # A binary tree nodeclass Node: # Constructor to create a new node def __init__(self, data): self.data = data self.left = None self.right = None # Recursive function print left view of a binary treedef leftViewUtil(root, level, max_level): # Base Case if root is None: return # If this is the first node of its level if (max_level[0] < level): print \"% d\\t\" %(root.data), max_level[0] = level # Recur for left and right subtree leftViewUtil(root.left, level + 1, max_level) leftViewUtil(root.right, level + 1, max_level) # A wrapper over leftViewUtil()def leftView(root): max_level = [0] leftViewUtil(root, 1, max_level) # Driver program to test above function root = Node(10)root.left = Node(2)root.right = Node(3)root.left.left = Node(7)root.left.right = Node(8)root.right.right = Node(15)root.right.left = Node(12)root.right.right.left = Node(14) leftView(root) # This code is contributed by Nikhil Kumar Singh(nickzuck_007)", "e": 6663, "s": 5576, "text": null }, { "code": "using System; // C# program to print left view of binary tree /* Class containing left and right child of currentnode and key value*/public class Node { public int data; public Node left, right; public Node(int item) { data = item; left = right = null; }} /* Class to print the left view */public class BinaryTree { public Node root; public static int max_level = 0; // recursive function to print left view public virtual void leftViewUtil(Node node, int level) { // Base Case if (node == null) { return; } // If this is the first node of its level if (max_level < level) { Console.Write(\" \" + node.data); max_level = level; } // Recur for left and right subtrees leftViewUtil(node.left, level + 1); leftViewUtil(node.right, level + 1); } // A wrapper over leftViewUtil() public virtual void leftView() { leftViewUtil(root, 1); } /* testing for example nodes */ public static void Main(string[] args) { /* creating a binary tree and entering the nodes */ BinaryTree tree = new BinaryTree(); tree.root = new Node(10); tree.root.left = new Node(2); tree.root.right = new Node(3); tree.root.left.left = new Node(7); tree.root.left.right = new Node(8); tree.root.right.right = new Node(15); tree.root.right.left = new Node(12); tree.root.right.right.left = new Node(14); tree.leftView(); }} // This code is contributed by Shrikant13", "e": 8257, "s": 6663, "text": null }, { "code": "<script> // Javascript program to print left view// of binary tree // Class containing left and right// child of current node and key valueclass Node{ constructor(item) { this.data = item; this.left = null; this.right = null; }} // Class to print the left viewvar root ;var max_level = 0; // Recursive function to print left viewfunction leftViewUtil(node, level){ // Base Case if (node == null) { return; } // If this is the first node of its level if (max_level < level) { document.write(\" \" + node.data); max_level = level; } // Recur for left and right subtrees leftViewUtil(node.left, level + 1); leftViewUtil(node.right, level + 1);} // A wrapper over leftViewUtil()function leftView(){ leftViewUtil(root, 1);} // Driver code // Testing for example nodes// Creating a binary tree and// entering the nodesroot = Node(10)root.left = new Node(2)root.right = new Node(3)root.left.left = new Node(7)root.left.right = new Node(8)root.right.right = new Node(15)root.right.left = new Node(12)root.right.right.left = new Node(14) leftView(); // This code is contributed by rrrtnx </script>", "e": 9451, "s": 8257, "text": null }, { "code": null, "e": 9462, "s": 9451, "text": "10 2 7 14 " }, { "code": null, "e": 9627, "s": 9462, "text": "Time Complexity: The function does a simple traversal of the tree, so the complexity is O(n). Auxiliary Space: O(n), due to the stack space during recursive call. " }, { "code": null, "e": 9963, "s": 9627, "text": "Method-2 (Using Queue): In this method, level order traversal based solution is discussed. If we observe carefully, we will see that our main task is to print the left most node of every level. So, we will do a level order traversal on the tree and print the leftmost node at every level. Below is the implementation of above approach:" }, { "code": null, "e": 9967, "s": 9963, "text": "C++" }, { "code": null, "e": 9972, "s": 9967, "text": "Java" }, { "code": null, "e": 9979, "s": 9972, "text": "Python" }, { "code": null, "e": 9982, "s": 9979, "text": "C#" }, { "code": null, "e": 9993, "s": 9982, "text": "Javascript" }, { "code": "// C++ program to print left view of// Binary Tree #include<bits/stdc++.h>using namespace std; // A Binary Tree Nodestruct Node{ int data; struct Node *left, *right;}; // Utility function to create a new tree nodeNode* newNode(int data){ Node *temp = new Node; temp->data = data; temp->left = temp->right = NULL; return temp;} // function to print left view of// binary treevoid printLeftView(Node* root){ if (!root) return; queue<Node*> q; q.push(root); while (!q.empty()) { // number of nodes at current level int n = q.size(); // Traverse all nodes of current level for(int i = 1; i <= n; i++) { Node* temp = q.front(); q.pop(); // Print the left most element // at the level if (i == 1) cout<<temp->data<<\" \"; // Add left node to queue if (temp->left != NULL) q.push(temp->left); // Add right node to queue if (temp->right != NULL) q.push(temp->right); } }} // Driver codeint main(){ // Let's construct the tree as // shown in example Node* root = newNode(10); root->left = newNode(2); root->right = newNode(3); root->left->left = newNode(7); root->left->right = newNode(8); root->right->right = newNode(15); root->right->left = newNode(12); root->right->right->left = newNode(14); printLeftView(root);} // This code is contributed by// Manne SreeCharan", "e": 11565, "s": 9993, "text": null }, { "code": "// Java program to print left view of Binary// Treeimport java.util.*; public class PrintRightView { // Binary tree node private static class Node { int data; Node left, right; public Node(int data) { this.data = data; this.left = null; this.right = null; } } // function to print left view of binary tree private static void printLeftView(Node root) { if (root == null) return; Queue<Node> queue = new LinkedList<>(); queue.add(root); while (!queue.isEmpty()) { // number of nodes at current level int n = queue.size(); // Traverse all nodes of current level for (int i = 1; i <= n; i++) { Node temp = queue.poll(); // Print the left most element at // the level if (i == 1) System.out.print(temp.data + \" \"); // Add left node to queue if (temp.left != null) queue.add(temp.left); // Add right node to queue if (temp.right != null) queue.add(temp.right); } } } // Driver code public static void main(String[] args) { // construct binary tree as shown in // above diagram Node root = new Node(10); root.left = new Node(2); root.right = new Node(3); root.left.left = new Node(7); root.left.right = new Node(8); root.right.right = new Node(15); root.right.left = new Node(12); root.right.right.left = new Node(14); printLeftView(root); }} // This code is contributed by// Manne SreeCharan", "e": 13318, "s": 11565, "text": null }, { "code": "# Python3 program to print left view of# Binary Tree # Binary Tree Node\"\"\" utility that allocates a newNodewith the given key \"\"\" class newNode: # Construct to create a newNode def __init__(self, key): self.data = key self.left = None self.right = None self.hd = 0 # function to print left view of# binary tree def printLeftView(root): if (not root): return q = [] q.append(root) while (len(q)): # number of nodes at current level n = len(q) # Traverse all nodes of current level for i in range(1, n + 1): temp = q[0] q.pop(0) # Print the left most element # at the level if (i == 1): print(temp.data, end=\" \") # Add left node to queue if (temp.left != None): q.append(temp.left) # Add right node to queue if (temp.right != None): q.append(temp.right) # Driver Codeif __name__ == '__main__': root = newNode(10) root.left = newNode(2) root.right = newNode(3) root.left.left = newNode(7) root.left.right = newNode(8) root.right.right = newNode(15) root.right.left = newNode(12) root.right.right.left = newNode(14) printLeftView(root) # This code is contributed by# Manne SreeCharan", "e": 14663, "s": 13318, "text": null }, { "code": "// C# program to print left view// of Binary Treeusing System;using System.Collections.Generic; public class PrintRightView { // Binary tree node private class Node { public int data; public Node left, right; public Node(int data) { this.data = data; this.left = null; this.right = null; } } // function to print left view of binary tree private static void printRightView(Node root) { if (root == null) return; Queue<Node> queue = new Queue<Node>(); queue.Enqueue(root); while (queue.Count != 0) { // number of nodes at current level int n = queue.Count; // Traverse all nodes of current level for (int i = 1; i <= n; i++) { Node temp = queue.Dequeue(); // Print the left most element at // the level if (i == n) Console.Write(temp.data + \" \"); // Add left node to queue if (temp.left != null) queue.Enqueue(temp.left); // Add right node to queue if (temp.right != null) queue.Enqueue(temp.right); } } } // Driver code public static void Main(String[] args) { // construct binary tree as shown in // above diagram Node root = new Node(10); root.left = new Node(2); root.right = new Node(3); root.left.left = new Node(7); root.left.right = new Node(8); root.right.right = new Node(15); root.right.left = new Node(12); root.right.right.left = new Node(14); printRightView(root); }} // This code is contributed Manne SreeCharan", "e": 16454, "s": 14663, "text": null }, { "code": "<script> // JavaScript program to print left view of// Binary Treeclass newNode{ // Construct to create a newNode constructor(key){ this.data = key this.left = null this.right = null this.hd = 0 }} // function to print left view of// binary treefunction printLeftView(root){ if (root == null) return let q = [] q.push(root) while (q.length){ // number of nodes at current level let n = q.length // Traverse all nodes of current level for(let i=1;i< n + 1;i++){ let temp = q.shift() // Print the left most element // at the level if (i == 1) document.write(temp.data,\" \") // Add left node to queue if (temp.left != null) q.push(temp.left) // Add right node to queue if (temp.right != null) q.push(temp.right) } }} // Driver Codelet root = new newNode(10)root.left = new newNode(2)root.right = new newNode(3)root.left.left = new newNode(7)root.left.right = new newNode(8)root.right.right = new newNode(15)root.right.left = new newNode(12)root.right.right.left = new newNode(14)printLeftView(root) // This code is contributed by shinjanpatra </script>", "e": 17739, "s": 16454, "text": null }, { "code": null, "e": 17750, "s": 17739, "text": "10 2 7 14 " }, { "code": null, "e": 17883, "s": 17750, "text": "Time Complexity: O(n), where n is the number of nodes in the binary tree.Auxiliary Space: O(n) since using space for auxiliary queue" }, { "code": null, "e": 18106, "s": 17883, "text": "Method 3: Using queue and a null pointer to mark the first element of each level. we insert a null pointer in the first and as reach that null pointer we mark bool as true and take the next element as our left view element" }, { "code": null, "e": 18110, "s": 18106, "text": "C++" }, { "code": "#include <bits/stdc++.h>using namespace std; struct Node{ int data; struct Node *left, *right;}; // A utility function to// create a new Binary Tree Nodestruct Node *newNode(int item){ struct Node *temp = (struct Node *)malloc( sizeof(struct Node)); temp->data = item; temp->left = temp->right = NULL; return temp;} vector<int> leftView(Node *root){ // Your code here vector<int>ans; if(!root) { return ans; } queue<Node*>q; q.push(root); q.push(NULL); bool ok=true; while(!q.empty()) { auto it=q.front(); q.pop(); if(it==NULL) { if(ok==false) { ok=true; } if(q.size()==0) { break; } else { q.push(NULL); } } else { if(ok) { ans.push_back(it->data); ok=false; } if(it->left) { q.push(it->left); } if(it->right) { q.push(it->right); } } } return ans;}int main(){ Node* root = newNode(10); root->left = newNode(2); root->right = newNode(3); root->left->left = newNode(7); root->left->right = newNode(8); root->right->right = newNode(15); root->right->left = newNode(12); root->right->right->left = newNode(14); vector<int> vec = leftView(root); for(int x : vec) cout<<x<<\" \"; cout << endl; return 0;}", "e": 19800, "s": 18110, "text": null }, { "code": null, "e": 19811, "s": 19800, "text": "10 2 7 14 " }, { "code": null, "e": 19928, "s": 19811, "text": "Time Complexity: O(n) where n is the total number of nodes.Auxiliary Space: O(n) due to the space occupied by queue." }, { "code": null, "e": 19940, "s": 19928, "text": "shrikanth13" }, { "code": null, "e": 19954, "s": 19940, "text": "rathbhupendra" }, { "code": null, "e": 19965, "s": 19954, "text": "hunter2000" }, { "code": null, "e": 19974, "s": 19965, "text": "sukhoi33" }, { "code": null, "e": 19984, "s": 19974, "text": "gnitish31" }, { "code": null, "e": 19997, "s": 19984, "text": "AakashYadav4" }, { "code": null, "e": 20018, "s": 19997, "text": "Rakesh Kumar Mallick" }, { "code": null, "e": 20025, "s": 20018, "text": "rrrtnx" }, { "code": null, "e": 20034, "s": 20025, "text": "sweetyty" }, { "code": null, "e": 20046, "s": 20034, "text": "iliyazali44" }, { "code": null, "e": 20056, "s": 20046, "text": "zaid47304" }, { "code": null, "e": 20063, "s": 20056, "text": "noah28" }, { "code": null, "e": 20104, "s": 20063, "text": "cc8gcwb6nkmesp932i6tfsqsu6dl3vthdbax4wf0" }, { "code": null, "e": 20117, "s": 20104, "text": "shinjanpatra" }, { "code": null, "e": 20131, "s": 20117, "text": "sarthak17jain" }, { "code": null, "e": 20143, "s": 20131, "text": "polymatir3j" }, { "code": null, "e": 20160, "s": 20143, "text": "hardikkoriintern" }, { "code": null, "e": 20169, "s": 20160, "text": "Accolite" }, { "code": null, "e": 20176, "s": 20169, "text": "Amazon" }, { "code": null, "e": 20185, "s": 20176, "text": "Flipkart" }, { "code": null, "e": 20196, "s": 20185, "text": "Knowlarity" }, { "code": null, "e": 20207, "s": 20196, "text": "MakeMyTrip" }, { "code": null, "e": 20216, "s": 20207, "text": "Ola Cabs" }, { "code": null, "e": 20231, "s": 20216, "text": "Open Solutions" }, { "code": null, "e": 20237, "s": 20231, "text": "Paytm" }, { "code": null, "e": 20246, "s": 20237, "text": "Qualcomm" }, { "code": null, "e": 20254, "s": 20246, "text": "Samsung" }, { "code": null, "e": 20263, "s": 20254, "text": "Snapdeal" }, { "code": null, "e": 20273, "s": 20263, "text": "tree-view" }, { "code": null, "e": 20281, "s": 20273, "text": "Twitter" }, { "code": null, "e": 20286, "s": 20281, "text": "Tree" }, { "code": null, "e": 20292, "s": 20286, "text": "Paytm" }, { "code": null, "e": 20301, "s": 20292, "text": "Flipkart" }, { "code": null, "e": 20310, "s": 20301, "text": "Accolite" }, { "code": null, "e": 20317, "s": 20310, "text": "Amazon" }, { "code": null, "e": 20325, "s": 20317, "text": "Samsung" }, { "code": null, "e": 20334, "s": 20325, "text": "Snapdeal" }, { "code": null, "e": 20345, "s": 20334, "text": "MakeMyTrip" }, { "code": null, "e": 20354, "s": 20345, "text": "Ola Cabs" }, { "code": null, "e": 20363, "s": 20354, "text": "Qualcomm" }, { "code": null, "e": 20371, "s": 20363, "text": "Twitter" }, { "code": null, "e": 20382, "s": 20371, "text": "Knowlarity" }, { "code": null, "e": 20397, "s": 20382, "text": "Open Solutions" }, { "code": null, "e": 20402, "s": 20397, "text": "Tree" }, { "code": null, "e": 20500, "s": 20402, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 20529, "s": 20500, "text": "AVL Tree | Set 1 (Insertion)" }, { "code": null, "e": 20561, "s": 20529, "text": "Introduction to Data Structures" }, { "code": null, "e": 20625, "s": 20561, "text": "What is Data Structure: Types, Classifications and Applications" }, { "code": null, "e": 20675, "s": 20625, "text": "A program to check if a binary tree is BST or not" }, { "code": null, "e": 20689, "s": 20675, "text": "Decision Tree" }, { "code": null, "e": 20732, "s": 20689, "text": "Top 50 Tree Coding Problems for Interviews" }, { "code": null, "e": 20774, "s": 20732, "text": "Segment Tree | Set 1 (Sum of given range)" }, { "code": null, "e": 20844, "s": 20774, "text": "Overview of Data Structures | Set 2 (Binary Tree, BST, Heap and Hash)" }, { "code": null, "e": 20927, "s": 20844, "text": "Complexity of different operations in Binary tree, Binary Search Tree and AVL tree" } ]
Read/Write structure to a file using C
fwrite() and fread() is used to write to a file in C. fwrite(const void *ptr, size_t size, size_t nmemb, FILE *stream) where ptr - A pointer to array of elements to be written size - Size in bytes of each element to be written nmemb - Number of elements, each one with a size of bytes stream – A pointer to a FILE object that specifies an output stream fread(void *ptr, size_t size, size_t nmemb, FILE *stream) where ptr - A pointer to a block of memory with a minimum size of size*nmemb bytes. size - Size in bytes of each element to be read. nmemb - Number of elements, each one with a size of bytes. stream - A pointer to a FILE object that specifies an input stream. Begin Create a structure Student to declare variables. Open file to write. Check if any error occurs in file opening. Initialize the variables with data. If file open successfully, write struct using write method. Close the file for writing. Open the file to read. Check if any error occurs in file opening. If file open successfully, read the file using read method. Close the file for reading. Check if any error occurs. Print the data. End. This is an example to read/write structure in C: #include <stdio.h> #include <stdlib.h> #include <string.h> struct Student { int roll_no; char name[20]; }; int main () { FILE *of; of= fopen ("c1.txt", "w"); if (of == NULL) { fprintf(stderr, "\nError to open the file\n"); exit (1); } struct Student inp1 = {1, "Ram"}; struct Student inp2 = {2, "Shyam"}; fwrite (&inp1, sizeof(struct Student), 1, of); fwrite (&inp2, sizeof(struct Student), 1, of); if(fwrite != 0) printf("Contents to file written successfully !\n"); else printf("Error writing file !\n"); fclose (of); FILE *inf; struct Student inp; inf = fopen ("c1.txt", "r"); if (inf == NULL) { fprintf(stderr, "\nError to open the file\n"); exit (1); } while(fread(&inp, sizeof(struct Student), 1, inf)) printf ("roll_no = %d name = %s\n", inp.roll_no, inp.name); fclose (inf); } Contents to file written successfully ! roll_no = 1 name = Ram roll_no = 2 name = Shyam
[ { "code": null, "e": 1241, "s": 1187, "text": "fwrite() and fread() is used to write to a file in C." }, { "code": null, "e": 1306, "s": 1241, "text": "fwrite(const void *ptr, size_t size, size_t nmemb, FILE *stream)" }, { "code": null, "e": 1312, "s": 1306, "text": "where" }, { "code": null, "e": 1363, "s": 1312, "text": "ptr - A pointer to array of elements to be written" }, { "code": null, "e": 1414, "s": 1363, "text": "size - Size in bytes of each element to be written" }, { "code": null, "e": 1472, "s": 1414, "text": "nmemb - Number of elements, each one with a size of bytes" }, { "code": null, "e": 1540, "s": 1472, "text": "stream – A pointer to a FILE object that specifies an output stream" }, { "code": null, "e": 1598, "s": 1540, "text": "fread(void *ptr, size_t size, size_t nmemb, FILE *stream)" }, { "code": null, "e": 1604, "s": 1598, "text": "where" }, { "code": null, "e": 1682, "s": 1604, "text": "ptr - A pointer to a block of memory with a minimum size of size*nmemb bytes." }, { "code": null, "e": 1731, "s": 1682, "text": "size - Size in bytes of each element to be read." }, { "code": null, "e": 1790, "s": 1731, "text": "nmemb - Number of elements, each one with a size of bytes." }, { "code": null, "e": 1858, "s": 1790, "text": "stream - A pointer to a FILE object that specifies an input stream." }, { "code": null, "e": 2344, "s": 1858, "text": "Begin\n Create a structure Student to declare variables.\n Open file to write.\n Check if any error occurs in file opening.\n Initialize the variables with data.\n If file open successfully, write struct using write method.\n Close the file for writing.\n Open the file to read.\n Check if any error occurs in file opening.\n If file open successfully, read the file using read method.\n Close the file for reading.\n Check if any error occurs.\n Print the data.\nEnd." }, { "code": null, "e": 2393, "s": 2344, "text": "This is an example to read/write structure in C:" }, { "code": null, "e": 3280, "s": 2393, "text": "#include <stdio.h>\n#include <stdlib.h>\n#include <string.h>\nstruct Student {\n int roll_no;\n char name[20];\n};\nint main () {\n FILE *of;\n of= fopen (\"c1.txt\", \"w\");\n if (of == NULL) {\n fprintf(stderr, \"\\nError to open the file\\n\");\n exit (1);\n }\n struct Student inp1 = {1, \"Ram\"};\n struct Student inp2 = {2, \"Shyam\"};\n fwrite (&inp1, sizeof(struct Student), 1, of);\n fwrite (&inp2, sizeof(struct Student), 1, of);\n if(fwrite != 0)\n printf(\"Contents to file written successfully !\\n\");\n else\n printf(\"Error writing file !\\n\");\n fclose (of);\n FILE *inf;\n struct Student inp;\n inf = fopen (\"c1.txt\", \"r\");\n if (inf == NULL) {\n fprintf(stderr, \"\\nError to open the file\\n\");\n exit (1);\n }\n while(fread(&inp, sizeof(struct Student), 1, inf))\n printf (\"roll_no = %d name = %s\\n\", inp.roll_no, inp.name);\n fclose (inf);\n}" }, { "code": null, "e": 3368, "s": 3280, "text": "Contents to file written successfully !\nroll_no = 1 name = Ram\nroll_no = 2 name = Shyam" } ]
Swap two nibbles in a byte
10 Jun, 2022 A nibble is a four-bit aggregation, or half an octet. There are two nibbles in a byte. Given a byte, swap the two nibbles in it. For example 100 is be represented as 01100100 in a byte (or 8 bits). The two nibbles are (0110) and (0100). If we swap the two nibbles, we get 01000110 which is 70 in decimal. To swap the nibbles, we can use bitwise &, bitwise ” operators. A byte can be represented using a unsigned char in C as size of char is 1 byte in a typical C compiler. Below is the implementation of above idea. C++ C Java Python3 C# PHP Javascript // C++ program to swap two// nibbles in a byte#include <bits/stdc++.h>using namespace std; int swapNibbles(int x){ return ( (x & 0x0F) << 4 | (x & 0xF0) >> 4 );} // Driver codeint main(){ int x = 100; cout << swapNibbles(x); return 0;} //This code is contributed by Shivi_Aggarwal #include <stdio.h> unsigned char swapNibbles(unsigned char x){ return ( (x & 0x0F)<<4 | (x & 0xF0)>>4 );} int main(){ unsigned char x = 100; printf("%u", swapNibbles(x)); return 0;} // Java program to swap two// nibbles in a byte class GFG { static int swapNibbles(int x){ return ((x & 0x0F) << 4 | (x & 0xF0) >> 4);} // Driver codepublic static void main(String arg[]){ int x = 100; System.out.print(swapNibbles(x));}} // This code is contributed by Anant Agarwal. # python program Swap# two nibbles in a byte def swapNibbles(x): return ( (x & 0x0F)<<4 | (x & 0xF0)>>4 ) # Driver code x = 100print(swapNibbles(x)) # This code is contributed# by Anant Agarwal. // C# program to swap two// nibbles in a byteusing System; class GFG { // Function for swapping static int swapNibbles(int x){ return ((x & 0x0F) << 4 | (x & 0xF0) >> 4);} // Driver codepublic static void Main(){ int x = 100; Console.Write(swapNibbles(x));}} // This code is contributed by Nitin Mittal. <?php// PHP program to swap two// nibbles in a byte // function to Swap two nibbles// in a byte in php programfunction swapNibbles($x){ return ( ($x & 0x0F) << 4 | ($x & 0xF0) >> 4 );} // Driver Code $x = 100; echo swapNibbles($x); // This Code is Contributed by Ajit?> <script>// javascript program to swap two// nibbles in a byte function swapNibbles(x){ return ((x & 0x0F) << 4 | (x & 0xF0) >> 4);} // Driver codevar x = 100;document.write(swapNibbles(x)); // This code is contributed by Princi Singh</script> 70 Explanation: 100 is 01100100 in binary. The operation can be split mainly in two parts 1) The expression “x & 0x0F” gives us last 4 bits of x. For x = 100, the result is 00000100. Using bitwise ‘<<‘ operator, we shift the last four bits to the left 4 times and make the new last four bits as 0. The result after shift is 01000000.2) The expression “x & 0xF0” gives us first four bits of x. For x = 100, the result is 01100000. Using bitwise ‘>>’ operator, we shift the digit to the right 4 times and make the first four bits as 0. The result after shift is 00000110.At the end we use the bitwise OR ‘|’ operation of the two expressions explained above. The OR operator places first nibble to the end and last nibble to first. For x = 100, the value of (01000000) OR (00000110) gives the result 01000110 which is equal to 70 in decimal.This article is contributed by Anuj Garg. Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above Another Approach: Using binary instead of hexadecimal values. It is much clearer to beginners. Step 1: Take & of 00001111 with number to get right nibble i.e. 0b00001111 & N Step 2: Take & of 11110000 with number to get left nibble i.e. 0b11110000 & N Step 3: Left shift the right nibble obtained in step 1 by 4 positions to get it as left nibble in the final answer i.e. <<4 Step 4: Right shift the left nibble obtained in step 2 by 4 positions to get it as right nibble in final answer >>4 Step 5: Do or( | ) operation between values obtained in step 3 & 4 to get the answer C++ Java Python3 C# Javascript // C++ program to swap two// nibbles in a byte#include <bits/stdc++.h>using namespace std; int swapNibbles(int N) { // Step 1 int right = (N & 0b00001111); // Step 3 right= (right<<4); // Step 2 int left = (N & 0b11110000); // Step 4 left = (left>>4); // Step 5 return (right | left); } // Driver codeint main(){ int n = 100; cout << "Original: " << n << " Swapped: " << swapNibbles(n); return 0;} // This code is contributed by sanjoy_62. /*package whatever //do not write package name here */ import java.io.*;class Solution{ static int swapNibbles(int N) { // Step 1 int right = (N & 0b00001111); // Step 3 right= (right<<4); // Step 2 int left = (N & 0b11110000); // Step 4 left = (left>>4); // Step 5 return (right | left); }}class GFG { public static void main (String[] args) { Solution s = new Solution(); int n = 100; System.out.println("Original: "+ n + " Swapped: " + s.swapNibbles(n)); }} # Python code for the above approachfrom math import ceil, sqrt def swapNibbles(N) : # Step 1 right = (N & 0b00001111) # Step 3 right= (right<<4) # Step 2 left = (N & 0b11110000) # Step 4 left = (left>>4) # Step 5 return (right | left) # Driver Coden = 100;print("Original: ", n, end = " ")print(" Swapped: " , swapNibbles(n)) # This code is contributed by code_hunt. // C# program to swap two// nibbles in a byteusing System; public class GFG{ static int swapNibbles(int N) { // Step 1 int right = (N & 0b00001111); // Step 3 right= (right<<4); // Step 2 int left = (N & 0b11110000); // Step 4 left = (left>>4); // Step 5 return (right | left); } // Driver Code static public void Main (){ int n = 100; Console.Write("Original: "+ n + " Swapped: " + swapNibbles(n)); }} // This code is contributed by shruti456rawal // JavaScript code for the above approachfunction swapNibbles(N){ // Step 1 var right = (N & 0b00001111); // Step 3 var right= (right<<4); // Step 2 var left = (N & 0b11110000); // Step 4 var left = (left>>4); // Step 5 return (right | left); } // Driver Codevar n = 100;console.log("Original:", n, " Swapped:", swapNibbles(n)); // This code is contributed by phasing17 Original: 100 Swapped: 70 This article is contributed by Arvind Bakshi. Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above. nitin mittal jit_t Shivi_Aggarwal princi singh Abcool sanjoy_62 code_hunt shruti456rawal phasing17 Accolite Qualcomm Samsung Bit Magic Accolite Samsung Qualcomm Bit Magic Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Little and Big Endian Mystery Program to find whether a given number is power of 2 Binary representation of a given number Josephus problem | Set 1 (A O(n) Solution) Bit Fields in C Divide two integers without using multiplication, division and mod operator Find the element that appears once Add two numbers without using arithmetic operators C++ bitset and its application Set, Clear and Toggle a given bit of a number in C
[ { "code": null, "e": 52, "s": 24, "text": "\n10 Jun, 2022" }, { "code": null, "e": 358, "s": 52, "text": "A nibble is a four-bit aggregation, or half an octet. There are two nibbles in a byte. Given a byte, swap the two nibbles in it. For example 100 is be represented as 01100100 in a byte (or 8 bits). The two nibbles are (0110) and (0100). If we swap the two nibbles, we get 01000110 which is 70 in decimal. " }, { "code": null, "e": 571, "s": 358, "text": "To swap the nibbles, we can use bitwise &, bitwise ” operators. A byte can be represented using a unsigned char in C as size of char is 1 byte in a typical C compiler. Below is the implementation of above idea. " }, { "code": null, "e": 575, "s": 571, "text": "C++" }, { "code": null, "e": 577, "s": 575, "text": "C" }, { "code": null, "e": 582, "s": 577, "text": "Java" }, { "code": null, "e": 590, "s": 582, "text": "Python3" }, { "code": null, "e": 593, "s": 590, "text": "C#" }, { "code": null, "e": 597, "s": 593, "text": "PHP" }, { "code": null, "e": 608, "s": 597, "text": "Javascript" }, { "code": "// C++ program to swap two// nibbles in a byte#include <bits/stdc++.h>using namespace std; int swapNibbles(int x){ return ( (x & 0x0F) << 4 | (x & 0xF0) >> 4 );} // Driver codeint main(){ int x = 100; cout << swapNibbles(x); return 0;} //This code is contributed by Shivi_Aggarwal", "e": 901, "s": 608, "text": null }, { "code": "#include <stdio.h> unsigned char swapNibbles(unsigned char x){ return ( (x & 0x0F)<<4 | (x & 0xF0)>>4 );} int main(){ unsigned char x = 100; printf(\"%u\", swapNibbles(x)); return 0;}", "e": 1095, "s": 901, "text": null }, { "code": "// Java program to swap two// nibbles in a byte class GFG { static int swapNibbles(int x){ return ((x & 0x0F) << 4 | (x & 0xF0) >> 4);} // Driver codepublic static void main(String arg[]){ int x = 100; System.out.print(swapNibbles(x));}} // This code is contributed by Anant Agarwal.", "e": 1392, "s": 1095, "text": null }, { "code": "# python program Swap# two nibbles in a byte def swapNibbles(x): return ( (x & 0x0F)<<4 | (x & 0xF0)>>4 ) # Driver code x = 100print(swapNibbles(x)) # This code is contributed# by Anant Agarwal.", "e": 1590, "s": 1392, "text": null }, { "code": "// C# program to swap two// nibbles in a byteusing System; class GFG { // Function for swapping static int swapNibbles(int x){ return ((x & 0x0F) << 4 | (x & 0xF0) >> 4);} // Driver codepublic static void Main(){ int x = 100; Console.Write(swapNibbles(x));}} // This code is contributed by Nitin Mittal.", "e": 1916, "s": 1590, "text": null }, { "code": "<?php// PHP program to swap two// nibbles in a byte // function to Swap two nibbles// in a byte in php programfunction swapNibbles($x){ return ( ($x & 0x0F) << 4 | ($x & 0xF0) >> 4 );} // Driver Code $x = 100; echo swapNibbles($x); // This Code is Contributed by Ajit?>", "e": 2209, "s": 1916, "text": null }, { "code": "<script>// javascript program to swap two// nibbles in a byte function swapNibbles(x){ return ((x & 0x0F) << 4 | (x & 0xF0) >> 4);} // Driver codevar x = 100;document.write(swapNibbles(x)); // This code is contributed by Princi Singh</script>", "e": 2456, "s": 2209, "text": null }, { "code": null, "e": 2459, "s": 2456, "text": "70" }, { "code": null, "e": 3460, "s": 2459, "text": "Explanation: 100 is 01100100 in binary. The operation can be split mainly in two parts 1) The expression “x & 0x0F” gives us last 4 bits of x. For x = 100, the result is 00000100. Using bitwise ‘<<‘ operator, we shift the last four bits to the left 4 times and make the new last four bits as 0. The result after shift is 01000000.2) The expression “x & 0xF0” gives us first four bits of x. For x = 100, the result is 01100000. Using bitwise ‘>>’ operator, we shift the digit to the right 4 times and make the first four bits as 0. The result after shift is 00000110.At the end we use the bitwise OR ‘|’ operation of the two expressions explained above. The OR operator places first nibble to the end and last nibble to first. For x = 100, the value of (01000000) OR (00000110) gives the result 01000110 which is equal to 70 in decimal.This article is contributed by Anuj Garg. Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above" }, { "code": null, "e": 3478, "s": 3460, "text": "Another Approach:" }, { "code": null, "e": 3555, "s": 3478, "text": "Using binary instead of hexadecimal values. It is much clearer to beginners." }, { "code": null, "e": 3634, "s": 3555, "text": "Step 1: Take & of 00001111 with number to get right nibble i.e. 0b00001111 & N" }, { "code": null, "e": 3712, "s": 3634, "text": "Step 2: Take & of 11110000 with number to get left nibble i.e. 0b11110000 & N" }, { "code": null, "e": 3836, "s": 3712, "text": "Step 3: Left shift the right nibble obtained in step 1 by 4 positions to get it as left nibble in the final answer i.e. <<4" }, { "code": null, "e": 3952, "s": 3836, "text": "Step 4: Right shift the left nibble obtained in step 2 by 4 positions to get it as right nibble in final answer >>4" }, { "code": null, "e": 4037, "s": 3952, "text": "Step 5: Do or( | ) operation between values obtained in step 3 & 4 to get the answer" }, { "code": null, "e": 4041, "s": 4037, "text": "C++" }, { "code": null, "e": 4046, "s": 4041, "text": "Java" }, { "code": null, "e": 4054, "s": 4046, "text": "Python3" }, { "code": null, "e": 4057, "s": 4054, "text": "C#" }, { "code": null, "e": 4068, "s": 4057, "text": "Javascript" }, { "code": "// C++ program to swap two// nibbles in a byte#include <bits/stdc++.h>using namespace std; int swapNibbles(int N) { // Step 1 int right = (N & 0b00001111); // Step 3 right= (right<<4); // Step 2 int left = (N & 0b11110000); // Step 4 left = (left>>4); // Step 5 return (right | left); } // Driver codeint main(){ int n = 100; cout << \"Original: \" << n << \" Swapped: \" << swapNibbles(n); return 0;} // This code is contributed by sanjoy_62.", "e": 4590, "s": 4068, "text": null }, { "code": "/*package whatever //do not write package name here */ import java.io.*;class Solution{ static int swapNibbles(int N) { // Step 1 int right = (N & 0b00001111); // Step 3 right= (right<<4); // Step 2 int left = (N & 0b11110000); // Step 4 left = (left>>4); // Step 5 return (right | left); }}class GFG { public static void main (String[] args) { Solution s = new Solution(); int n = 100; System.out.println(\"Original: \"+ n + \" Swapped: \" + s.swapNibbles(n)); }}", "e": 5140, "s": 4590, "text": null }, { "code": "# Python code for the above approachfrom math import ceil, sqrt def swapNibbles(N) : # Step 1 right = (N & 0b00001111) # Step 3 right= (right<<4) # Step 2 left = (N & 0b11110000) # Step 4 left = (left>>4) # Step 5 return (right | left) # Driver Coden = 100;print(\"Original: \", n, end = \" \")print(\" Swapped: \" , swapNibbles(n)) # This code is contributed by code_hunt.", "e": 5565, "s": 5140, "text": null }, { "code": "// C# program to swap two// nibbles in a byteusing System; public class GFG{ static int swapNibbles(int N) { // Step 1 int right = (N & 0b00001111); // Step 3 right= (right<<4); // Step 2 int left = (N & 0b11110000); // Step 4 left = (left>>4); // Step 5 return (right | left); } // Driver Code static public void Main (){ int n = 100; Console.Write(\"Original: \"+ n + \" Swapped: \" + swapNibbles(n)); }} // This code is contributed by shruti456rawal", "e": 6057, "s": 5565, "text": null }, { "code": "// JavaScript code for the above approachfunction swapNibbles(N){ // Step 1 var right = (N & 0b00001111); // Step 3 var right= (right<<4); // Step 2 var left = (N & 0b11110000); // Step 4 var left = (left>>4); // Step 5 return (right | left); } // Driver Codevar n = 100;console.log(\"Original:\", n, \" Swapped:\", swapNibbles(n)); // This code is contributed by phasing17", "e": 6484, "s": 6057, "text": null }, { "code": null, "e": 6510, "s": 6484, "text": "Original: 100 Swapped: 70" }, { "code": null, "e": 6681, "s": 6510, "text": "This article is contributed by Arvind Bakshi. Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above." }, { "code": null, "e": 6694, "s": 6681, "text": "nitin mittal" }, { "code": null, "e": 6700, "s": 6694, "text": "jit_t" }, { "code": null, "e": 6715, "s": 6700, "text": "Shivi_Aggarwal" }, { "code": null, "e": 6728, "s": 6715, "text": "princi singh" }, { "code": null, "e": 6735, "s": 6728, "text": "Abcool" }, { "code": null, "e": 6745, "s": 6735, "text": "sanjoy_62" }, { "code": null, "e": 6755, "s": 6745, "text": "code_hunt" }, { "code": null, "e": 6770, "s": 6755, "text": "shruti456rawal" }, { "code": null, "e": 6780, "s": 6770, "text": "phasing17" }, { "code": null, "e": 6789, "s": 6780, "text": "Accolite" }, { "code": null, "e": 6798, "s": 6789, "text": "Qualcomm" }, { "code": null, "e": 6806, "s": 6798, "text": "Samsung" }, { "code": null, "e": 6816, "s": 6806, "text": "Bit Magic" }, { "code": null, "e": 6825, "s": 6816, "text": "Accolite" }, { "code": null, "e": 6833, "s": 6825, "text": "Samsung" }, { "code": null, "e": 6842, "s": 6833, "text": "Qualcomm" }, { "code": null, "e": 6852, "s": 6842, "text": "Bit Magic" }, { "code": null, "e": 6950, "s": 6852, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 6980, "s": 6950, "text": "Little and Big Endian Mystery" }, { "code": null, "e": 7033, "s": 6980, "text": "Program to find whether a given number is power of 2" }, { "code": null, "e": 7073, "s": 7033, "text": "Binary representation of a given number" }, { "code": null, "e": 7116, "s": 7073, "text": "Josephus problem | Set 1 (A O(n) Solution)" }, { "code": null, "e": 7132, "s": 7116, "text": "Bit Fields in C" }, { "code": null, "e": 7208, "s": 7132, "text": "Divide two integers without using multiplication, division and mod operator" }, { "code": null, "e": 7243, "s": 7208, "text": "Find the element that appears once" }, { "code": null, "e": 7294, "s": 7243, "text": "Add two numbers without using arithmetic operators" }, { "code": null, "e": 7325, "s": 7294, "text": "C++ bitset and its application" } ]
Python – Extract String till Numeric
01 Aug, 2020 Given a string, extract all its content till first appearance of numeric character. Input : test_str = “geeksforgeeks7 is best”Output : geeksforgeeksExplanation : All characters before 7 are extracted. Input : test_str = “2geeksforgeeks7 is best”Output : “”Explanation : No character extracted as 1st letter is numeric. Method #1 : Using isdigit() + index() + loop The combination of above functions can be used to solve this problem. In this, we check for first occurrence of numeric using isdigit() and index() is used to get required index till which content needs to be extracted. Python3 # Python3 code to demonstrate working of # Extract String till Numeric# Using isdigit() + index() + loop # initializing stringtest_str = "geeks4geeks is best" # printing original stringprint("The original string is : " + str(test_str)) # loop to iterating characterstemp = 0for chr in test_str: # checking if character is numeric, # saving index if chr.isdigit(): temp = test_str.index(chr) # printing result print("Extracted String : " + str(test_str[0 : temp])) The original string is : geeks4geeks is best Extracted String : geeks Method #2 : Using regex() This is yet another way in which this task can be performed. Using appropriate regex(), one can get content before possible numerics. Python3 # Python3 code to demonstrate working of # Extract String till Numeric# Using regex()import re # initializing stringtest_str = "geeks4geeks is best" # printing original stringprint("The original string is : " + str(test_str)) # regex to get all elements before numericsres = re.findall('([a-zA-Z ]*)\d*.*', test_str) # printing result print("Extracted String : " + str(res[0])) The original string is : geeks4geeks is best Extracted String : geeks Python string-programs 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": "\n01 Aug, 2020" }, { "code": null, "e": 112, "s": 28, "text": "Given a string, extract all its content till first appearance of numeric character." }, { "code": null, "e": 230, "s": 112, "text": "Input : test_str = “geeksforgeeks7 is best”Output : geeksforgeeksExplanation : All characters before 7 are extracted." }, { "code": null, "e": 348, "s": 230, "text": "Input : test_str = “2geeksforgeeks7 is best”Output : “”Explanation : No character extracted as 1st letter is numeric." }, { "code": null, "e": 393, "s": 348, "text": "Method #1 : Using isdigit() + index() + loop" }, { "code": null, "e": 613, "s": 393, "text": "The combination of above functions can be used to solve this problem. In this, we check for first occurrence of numeric using isdigit() and index() is used to get required index till which content needs to be extracted." }, { "code": null, "e": 621, "s": 613, "text": "Python3" }, { "code": "# Python3 code to demonstrate working of # Extract String till Numeric# Using isdigit() + index() + loop # initializing stringtest_str = \"geeks4geeks is best\" # printing original stringprint(\"The original string is : \" + str(test_str)) # loop to iterating characterstemp = 0for chr in test_str: # checking if character is numeric, # saving index if chr.isdigit(): temp = test_str.index(chr) # printing result print(\"Extracted String : \" + str(test_str[0 : temp])) ", "e": 1103, "s": 621, "text": null }, { "code": null, "e": 1174, "s": 1103, "text": "The original string is : geeks4geeks is best\nExtracted String : geeks\n" }, { "code": null, "e": 1200, "s": 1174, "text": "Method #2 : Using regex()" }, { "code": null, "e": 1334, "s": 1200, "text": "This is yet another way in which this task can be performed. Using appropriate regex(), one can get content before possible numerics." }, { "code": null, "e": 1342, "s": 1334, "text": "Python3" }, { "code": "# Python3 code to demonstrate working of # Extract String till Numeric# Using regex()import re # initializing stringtest_str = \"geeks4geeks is best\" # printing original stringprint(\"The original string is : \" + str(test_str)) # regex to get all elements before numericsres = re.findall('([a-zA-Z ]*)\\d*.*', test_str) # printing result print(\"Extracted String : \" + str(res[0])) ", "e": 1725, "s": 1342, "text": null }, { "code": null, "e": 1796, "s": 1725, "text": "The original string is : geeks4geeks is best\nExtracted String : geeks\n" }, { "code": null, "e": 1819, "s": 1796, "text": "Python string-programs" }, { "code": null, "e": 1826, "s": 1819, "text": "Python" }, { "code": null, "e": 1842, "s": 1826, "text": "Python Programs" } ]
Merge two sorted arrays using C++.
Given 2 sorted arrays list. Write a function to merge given two sorted arrays into one Arr1[] = {10,15, 17, 20} Arr2[] = {5, 9, 13, 19} Result[] = {5, 9, 10, 13, 15, 17, 19, 20} 1. Traverse both array 1.1. If arr1[i] < arr2[j] 1.1.1. Add arr[i] to new array 1.1.2. Increment ‘i’ and index of result array ‘k’ 1.2. If arr2[i] < arr1[j] 1.2.1. Add arr[j] to new array 1.2.2. Increment ‘j’ and index of result array ‘k’ 2. Repeat procedure until both arrays are exhausted 3. Return resultant array #include <iostream> #define SIZE(arr) (sizeof(arr) / sizeof(arr[0])) using namespace std; void mergeSortedArrays(int *arr1, int n1, int *arr2, int n2, int *result){ int i, j, k; i = 0; j = 0; k = 0; while (i < n1 && j < n2) { if (arr1[i] < arr2[j]) { result[k] = arr1[i]; ++k; ++i; } else { result[k] = arr2[j]; ++k; ++j; } } while (i < n1) { result[k] = arr1[i]; ++k; ++i; } while (j < n2) { result[k] = arr2[j]; ++k; ++j; } } void dispalyArray(int *arr, int n){ for (int i = 0; i < n; ++i) { cout << arr[i] << " "; } cout << endl; } int main(){ int arr1[] = {10, 15, 17, 20}; int arr2[] = {5, 9, 7, 13, 19}; int result[SIZE(arr1) + SIZE(arr2)]; cout << "First sorted array:" << endl; dispalyArray(arr1, SIZE(arr1)); cout << "Second sorted array:" << endl; dispalyArray(arr2, SIZE(arr2)); mergeSortedArrays(arr1, SIZE(arr1), arr2, SIZE(arr2), result); cout << "Final sorted array:" << endl; dispalyArray(result, SIZE(result)); return 0; } When you compile and execute the above program. It generates the following output − First sorted array: 10 15 17 20 Second sorted array: 5 9 7 13 19 Final sorted array: 5 9 7 10 13 15 17 19 20
[ { "code": null, "e": 1274, "s": 1187, "text": "Given 2 sorted arrays list. Write a function to merge given two sorted arrays into one" }, { "code": null, "e": 1365, "s": 1274, "text": "Arr1[] = {10,15, 17, 20}\nArr2[] = {5, 9, 13, 19}\nResult[] = {5, 9, 10, 13, 15, 17, 19, 20}" }, { "code": null, "e": 1712, "s": 1365, "text": "1. Traverse both array\n 1.1. If arr1[i] < arr2[j]\n 1.1.1. Add arr[i] to new array\n 1.1.2. Increment ‘i’ and index of result array ‘k’\n 1.2. If arr2[i] < arr1[j]\n 1.2.1. Add arr[j] to new array\n 1.2.2. Increment ‘j’ and index of result array ‘k’\n2. Repeat procedure until both arrays are exhausted\n3. Return resultant array" }, { "code": null, "e": 2838, "s": 1712, "text": "#include <iostream>\n#define SIZE(arr) (sizeof(arr) / sizeof(arr[0]))\nusing namespace std;\nvoid mergeSortedArrays(int *arr1, int n1, int *arr2, int n2, int *result){\n int i, j, k;\n i = 0;\n j = 0;\n k = 0;\n while (i < n1 && j < n2) {\n if (arr1[i] < arr2[j]) {\n result[k] = arr1[i];\n ++k;\n ++i;\n } else {\n result[k] = arr2[j];\n ++k;\n ++j;\n }\n }\n while (i < n1) {\n result[k] = arr1[i];\n ++k;\n ++i;\n }\n while (j < n2) {\n result[k] = arr2[j];\n ++k;\n ++j;\n }\n}\nvoid dispalyArray(int *arr, int n){\n for (int i = 0; i < n; ++i) {\n cout << arr[i] << \" \";\n }\n cout << endl;\n}\nint main(){\n int arr1[] = {10, 15, 17, 20};\n int arr2[] = {5, 9, 7, 13, 19};\n int result[SIZE(arr1) + SIZE(arr2)];\n cout << \"First sorted array:\" << endl;\n dispalyArray(arr1, SIZE(arr1));\n cout << \"Second sorted array:\" << endl;\n dispalyArray(arr2, SIZE(arr2));\n mergeSortedArrays(arr1, SIZE(arr1), arr2, SIZE(arr2), result);\n cout << \"Final sorted array:\" << endl;\n dispalyArray(result, SIZE(result));\n return 0;\n}" }, { "code": null, "e": 2922, "s": 2838, "text": "When you compile and execute the above program. It generates the following output −" }, { "code": null, "e": 3031, "s": 2922, "text": "First sorted array:\n10 15 17 20\nSecond sorted array:\n5 9 7 13 19\nFinal sorted array:\n5 9 7 10 13 15 17 19 20" } ]
StringBuilder delete() in Java with Examples
22 Sep, 2021 The delete(int start, int end) method of StringBuilder class removes the characters starting from index start to index end-1 from String contained by StringBuilder. This method takes two indexes as a parameter first start represents index of the first character and endIndex represents index after the last character of the substring to be removed from String contained by StringBuilder and returns the remaining String as StringBuilder Object. Syntax: public StringBuilder delete(int start, int end) Parameters: This method accepts two parameters: start: index of the first character of the substring. end: index after the last character of the substring. Return Value: This method returns this StringBuilder object after removing the substring. Exception: This method throws StringIndexOutOfBoundsException if the start is less than zero, or start is larger than the length of String, or start is larger than end. Below programs demonstrate the delete() method of StringBuilder Class: Example 1: Java // Java program to demonstrate// the delete() Method. class GFG { public static void main(String[] args) { // create a StringBuilder object // with a String pass as parameter StringBuilder str = new StringBuilder("WelcomeGeeks"); // print string System.out.println("Before removal String = " + str.toString()); // remove the substring from index 2 to 8 StringBuilder afterRemoval = str.delete(2, 8); // print string after removal of substring System.out.println("After removal String = " + afterRemoval.toString()); }} Before removal String = WelcomeGeeks After removal String = Weeeks Example 2: Java // Java program to demonstrate// the delete() Method. class GFG { public static void main(String[] args) { // create a StringBuilder object // with a String pass as parameter StringBuilder str = new StringBuilder("GeeksforGeeks"); // print string System.out.println("Before removal String = " + str.toString()); // remove the substring from index 8 to 8 StringBuilder afterRemoval = str.delete(8, 8); // start equal to end so no change in string // print string after removal of substring System.out.println("After removal of SubString" + " start=8 to end=8" + " String becomes => " + afterRemoval.toString()); // remove the substring from index 1 to 8 afterRemoval = str.delete(1, 8); // print string after removal of substring System.out.println("After removal of SubString" + " start=1 to end=8" + " String becomes => " + afterRemoval.toString()); }} Before removal String = GeeksforGeeks After removal of SubString start=8 to end=8 String becomes => GeeksforGeeks After removal of SubString start=1 to end=8 String becomes => GGeeks Example 3: To demonstrate IndexOutOfBoundException Java // Java program to demonstrate// exception thrown by the delete() Method. class GFG { public static void main(String[] args) { // create a StringBuilder object // with a String pass as parameter StringBuilder str = new StringBuilder("GeeksforGeeks"); try { // make start greater than end StringBuilder afterRemoval = str.delete(7, 4); } catch (Exception e) { System.out.println("Exception: " + e); } }} Exception: java.lang.StringIndexOutOfBoundsException Reference: https://docs.oracle.com/javase/10/docs/api/java/lang/StringBuilder.html#delete(int, int) surinderdawra388 java-basics Java-Functions Java-StringBuilder 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 Stream In Java Collections in Java Singleton Class in Java Multidimensional Arrays in Java Set in Java
[ { "code": null, "e": 28, "s": 0, "text": "\n22 Sep, 2021" }, { "code": null, "e": 474, "s": 28, "text": "The delete(int start, int end) method of StringBuilder class removes the characters starting from index start to index end-1 from String contained by StringBuilder. This method takes two indexes as a parameter first start represents index of the first character and endIndex represents index after the last character of the substring to be removed from String contained by StringBuilder and returns the remaining String as StringBuilder Object. " }, { "code": null, "e": 483, "s": 474, "text": "Syntax: " }, { "code": null, "e": 531, "s": 483, "text": "public StringBuilder delete(int start, int end)" }, { "code": null, "e": 580, "s": 531, "text": "Parameters: This method accepts two parameters: " }, { "code": null, "e": 634, "s": 580, "text": "start: index of the first character of the substring." }, { "code": null, "e": 688, "s": 634, "text": "end: index after the last character of the substring." }, { "code": null, "e": 778, "s": 688, "text": "Return Value: This method returns this StringBuilder object after removing the substring." }, { "code": null, "e": 947, "s": 778, "text": "Exception: This method throws StringIndexOutOfBoundsException if the start is less than zero, or start is larger than the length of String, or start is larger than end." }, { "code": null, "e": 1018, "s": 947, "text": "Below programs demonstrate the delete() method of StringBuilder Class:" }, { "code": null, "e": 1031, "s": 1018, "text": "Example 1: " }, { "code": null, "e": 1036, "s": 1031, "text": "Java" }, { "code": "// Java program to demonstrate// the delete() Method. class GFG { public static void main(String[] args) { // create a StringBuilder object // with a String pass as parameter StringBuilder str = new StringBuilder(\"WelcomeGeeks\"); // print string System.out.println(\"Before removal String = \" + str.toString()); // remove the substring from index 2 to 8 StringBuilder afterRemoval = str.delete(2, 8); // print string after removal of substring System.out.println(\"After removal String = \" + afterRemoval.toString()); }}", "e": 1705, "s": 1036, "text": null }, { "code": null, "e": 1772, "s": 1705, "text": "Before removal String = WelcomeGeeks\nAfter removal String = Weeeks" }, { "code": null, "e": 1784, "s": 1772, "text": "Example 2: " }, { "code": null, "e": 1789, "s": 1784, "text": "Java" }, { "code": "// Java program to demonstrate// the delete() Method. class GFG { public static void main(String[] args) { // create a StringBuilder object // with a String pass as parameter StringBuilder str = new StringBuilder(\"GeeksforGeeks\"); // print string System.out.println(\"Before removal String = \" + str.toString()); // remove the substring from index 8 to 8 StringBuilder afterRemoval = str.delete(8, 8); // start equal to end so no change in string // print string after removal of substring System.out.println(\"After removal of SubString\" + \" start=8 to end=8\" + \" String becomes => \" + afterRemoval.toString()); // remove the substring from index 1 to 8 afterRemoval = str.delete(1, 8); // print string after removal of substring System.out.println(\"After removal of SubString\" + \" start=1 to end=8\" + \" String becomes => \" + afterRemoval.toString()); }}", "e": 2960, "s": 1789, "text": null }, { "code": null, "e": 3143, "s": 2960, "text": "Before removal String = GeeksforGeeks\nAfter removal of SubString start=8 to end=8 String becomes => GeeksforGeeks\nAfter removal of SubString start=1 to end=8 String becomes => GGeeks" }, { "code": null, "e": 3196, "s": 3145, "text": "Example 3: To demonstrate IndexOutOfBoundException" }, { "code": null, "e": 3201, "s": 3196, "text": "Java" }, { "code": "// Java program to demonstrate// exception thrown by the delete() Method. class GFG { public static void main(String[] args) { // create a StringBuilder object // with a String pass as parameter StringBuilder str = new StringBuilder(\"GeeksforGeeks\"); try { // make start greater than end StringBuilder afterRemoval = str.delete(7, 4); } catch (Exception e) { System.out.println(\"Exception: \" + e); } }}", "e": 3721, "s": 3201, "text": null }, { "code": null, "e": 3774, "s": 3721, "text": "Exception: java.lang.StringIndexOutOfBoundsException" }, { "code": null, "e": 3877, "s": 3776, "text": "Reference: https://docs.oracle.com/javase/10/docs/api/java/lang/StringBuilder.html#delete(int, int) " }, { "code": null, "e": 3894, "s": 3877, "text": "surinderdawra388" }, { "code": null, "e": 3906, "s": 3894, "text": "java-basics" }, { "code": null, "e": 3921, "s": 3906, "text": "Java-Functions" }, { "code": null, "e": 3940, "s": 3921, "text": "Java-StringBuilder" }, { "code": null, "e": 3945, "s": 3940, "text": "Java" }, { "code": null, "e": 3950, "s": 3945, "text": "Java" }, { "code": null, "e": 4048, "s": 3950, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 4099, "s": 4048, "text": "Object Oriented Programming (OOPs) Concept in Java" }, { "code": null, "e": 4130, "s": 4099, "text": "How to iterate any Map in Java" }, { "code": null, "e": 4149, "s": 4130, "text": "Interfaces in Java" }, { "code": null, "e": 4179, "s": 4149, "text": "HashMap in Java with Examples" }, { "code": null, "e": 4197, "s": 4179, "text": "ArrayList in Java" }, { "code": null, "e": 4212, "s": 4197, "text": "Stream In Java" }, { "code": null, "e": 4232, "s": 4212, "text": "Collections in Java" }, { "code": null, "e": 4256, "s": 4232, "text": "Singleton Class in Java" }, { "code": null, "e": 4288, "s": 4256, "text": "Multidimensional Arrays in Java" } ]
Count Triplets such that one of the numbers can be written as sum of the other two
30 Jun, 2021 Given an array A[] of N integers. The task is to find the number of triples (i, j, k) , where i, j, k are indices and (1 <= i < j < k <= N), such that in the set { , , } at least one of the numbers can be written as the sum of the other two.Examples: Input : A[] = {1, 2, 3, 4, 5} Output : 4 The valid triplets are: (1, 2, 3), (1, 3, 4), (1, 4, 5), (2, 3, 5) Input : A[] = {1, 1, 1, 2, 2} Output : 6 This is a counting problem. Let’s say f(x) represents the frequency of number in our array.There exist four cases: All three numbers are equal to 0. The number of ways = f(0)C3 (where pCq is the number of ways of choosing q numbers from p numbers).One number is equal to 0, the other two are equal to some x > 0: f(0) * f(x)C2.Two numbers are equal to some x>0, the third is 2*x: f(x)C2 * f(2 * x).The three numbers are x, y and x + y, 0 < x, y: f(x) * f(y) * f(x + y). All three numbers are equal to 0. The number of ways = f(0)C3 (where pCq is the number of ways of choosing q numbers from p numbers). One number is equal to 0, the other two are equal to some x > 0: f(0) * f(x)C2. Two numbers are equal to some x>0, the third is 2*x: f(x)C2 * f(2 * x). The three numbers are x, y and x + y, 0 < x, y: f(x) * f(y) * f(x + y). Below is the implementation of the above approach: C++ Java Python3 C# PHP Javascript // C++ program to count Triplets such that at// least one of the numbers can be written// as sum of the other two#include<bits/stdc++.h>using namespace std; // Function to count the number of ways // to choose the triples int countWays(int arr[], int n) { // compute the max value in the array // and create frequency array of size // max_val + 1. // We can also use HashMap to store // frequencies. We have used an array // to keep remaining code simple. int max_val = 0; for (int i = 0; i < n; i++) max_val = max(max_val, arr[i]); int freq[max_val + 1]={0}; for (int i = 0; i < n; i++) freq[arr[i]]++; int ans = 0; // stores the number of ways // Case 1: 0, 0, 0 ans += freq[0] * (freq[0] - 1) * (freq[0] - 2) / 6; // Case 2: 0, x, x for (int i = 1; i <= max_val; i++) ans += freq[0] * freq[i] * (freq[i] - 1) / 2; // Case 3: x, x, 2*x for (int i = 1; 2 * i <= max_val; i++) ans += freq[i] * (freq[i] - 1) / 2 * freq[2 * i]; // Case 4: x, y, x + y // iterate through all pairs (x, y) for (int i = 1; i <= max_val; i++) { for (int j = i + 1; i + j <= max_val; j++) ans += freq[i] * freq[j] * freq[i + j]; } return ans; } // Driver code int main() { int arr[]={ 1, 2, 3, 4, 5 }; int n = sizeof(arr)/sizeof(int); cout<<(countWays(arr, n)); return 0; } //contributed by Arnab Kundu // Java program to count Triplets such that at// least one of the numbers can be written// as a sum of the other two class GFG { // Function to count the number of ways // to choose the triples static int countWays(int[] arr, int n) { // compute the max value in the array // and create frequency array of size // max_val + 1. // We can also use HashMap to store // frequencies. We have used an array // to keep remaining code simple. int max_val = 0; for (int i = 0; i < n; i++) max_val = Math.max(max_val, arr[i]); int[] freq = new int[max_val + 1]; for (int i = 0; i < n; i++) freq[arr[i]]++; int ans = 0; // stores the number of ways // Case 1: 0, 0, 0 ans += freq[0] * (freq[0] - 1) * (freq[0] - 2) / 6; // Case 2: 0, x, x for (int i = 1; i <= max_val; i++) ans += freq[0] * freq[i] * (freq[i] - 1) / 2; // Case 3: x, x, 2*x for (int i = 1; 2 * i <= max_val; i++) ans += freq[i] * (freq[i] - 1) / 2 * freq[2 * i]; // Case 4: x, y, x + y // iterate through all pairs (x, y) for (int i = 1; i <= max_val; i++) { for (int j = i + 1; i + j <= max_val; j++) ans += freq[i] * freq[j] * freq[i + j]; } return ans; } // Driver code public static void main(String[] args) { int[] arr = new int[] { 1, 2, 3, 4, 5 }; int n = arr.length; System.out.println(countWays(arr, n)); }} # Python3 program to count Triplets such# that at least one of the numbers can be# written as sum of the other twoimport math as mt # Function to count the number of ways# to choose the triplesdef countWays(arr, n): # compute the max value in the array # and create frequency array of size # max_val + 1. # We can also use HashMap to store # frequencies. We have used an array # to keep remaining code simple. max_val = 0 for i in range(n): max_val = max(max_val, arr[i]) freq = [0 for i in range(max_val + 1)] for i in range(n): freq[arr[i]] += 1 ans = 0 # stores the number of ways # Case 1: 0, 0, 0 ans += (freq[0] * (freq[0] - 1) * (freq[0] - 2) // 6) # Case 2: 0, x, x for i in range(1, max_val + 1): ans += (freq[0] * freq[i] * (freq[i] - 1) // 2) # Case 3: x, x, 2*x for i in range(1, (max_val + 1) // 2): ans += (freq[i] * (freq[i] - 1) // 2 * freq[2 * i]) # Case 4: x, y, x + y # iterate through all pairs (x, y) for i in range(1, max_val + 1): for j in range(i + 1, max_val - i + 1): ans += freq[i] * freq[j] * freq[i + j] return ans # Driver codearr = [ 1, 2, 3, 4, 5]n = len(arr)print(countWays(arr, n)) # This code is contributed by# mohit kumar 29 // C# program to count Triplets// such that at least one of the// numbers can be written as sum// of the other twousing System; class GFG{ // Function to count the number// of ways to choose the triplesstatic int countWays(int[] arr, int n){ // compute the max value in the array // and create frequency array of size // max_val + 1. // We can also use HashMap to store // frequencies. We have used an array // to keep remaining code simple. int max_val = 0; for (int i = 0; i < n; i++) max_val = Math.Max(max_val, arr[i]); int[] freq = new int[max_val + 1]; for (int i = 0; i < n; i++) freq[arr[i]]++; int ans = 0; // stores the number of ways // Case 1: 0, 0, 0 ans += freq[0] * (freq[0] - 1) * (freq[0] - 2) / 6; // Case 2: 0, x, x for (int i = 1; i <= max_val; i++) ans += freq[0] * freq[i] * (freq[i] - 1) / 2; // Case 3: x, x, 2*x for (int i = 1; 2 * i <= max_val; i++) ans += freq[i] * (freq[i] - 1) / 2 * freq[2 * i]; // Case 4: x, y, x + y // iterate through all pairs (x, y) for (int i = 1; i <= max_val; i++) { for (int j = i + 1; i + j <= max_val; j++) ans += freq[i] * freq[j] * freq[i + j]; } return ans;} // Driver codepublic static void Main(){ int[] arr = { 1, 2, 3, 4, 5 }; int n = arr.Length; Console.WriteLine(countWays(arr, n));}} // This code is contributed by shs.. <?php// PHP program to count Triplets such that at// least one of the numbers can be written// as sum of the other two // Function to count the number of ways// to choose the triplesfunction countWays($arr, $n){ // compute the max value in the array // and create frequency array of size // max_val + 1. // We can also use HashMap to store // frequencies. We have used an array // to keep remaining code simple. $max_val = 0; for ($i = 0; $i < $n; $i++) $max_val = max($max_val, $arr[$i]); $freq = array_fill(0, $max_val + 1, 0); for ($i = 0; $i < $n; $i++) $freq[$arr[$i]]++; $ans = 0; // stores the number of ways // Case 1: 0, 0, 0 $ans += (int)($freq[0] * ($freq[0] - 1) * ($freq[0] - 2) / 6); // Case 2: 0, x, x for ($i = 1; $i <= $max_val; $i++) $ans += (int)($freq[0] * $freq[$i] * ($freq[$i] - 1) / 2); // Case 3: x, x, 2*x for ($i = 1; 2 * $i <= $max_val; $i++) $ans += (int)($freq[$i] * ($freq[$i] - 1) / 2 * $freq[2 * $i]); // Case 4: x, y, x + y // iterate through all pairs (x, y) for ($i = 1; $i <= $max_val; $i++) { for ($j = $i + 1; $i + $j <= $max_val; $j++) $ans += $freq[$i] * $freq[$j] * $freq[$i + $j]; } return $ans;} // Driver code$arr = array( 1, 2, 3, 4, 5 );$n = count($arr);echo countWays($arr, $n); // This code is contributed by mits?> <script> // JavaScript program to count Triplets such that at// least one of the numbers can be written// as a sum of the other two // Function to count the number of ways // to choose the triples function countWays(arr,n) { // compute the max value in the array // and create frequency array of size // max_val + 1. // We can also use HashMap to store // frequencies. We have used an array // to keep remaining code simple. let max_val = 0; for (let i = 0; i < n; i++) max_val = Math.max(max_val, arr[i]); let freq = new Array(max_val + 1); for(let i=0;i<freq.length;i++) { freq[i]=0; } for (let i = 0; i < n; i++) freq[arr[i]]++; let ans = 0; // stores the number of ways // Case 1: 0, 0, 0 ans += freq[0] * (freq[0] - 1) * (freq[0] - 2) / 6; // Case 2: 0, x, x for (let i = 1; i <= max_val; i++) ans += freq[0] * freq[i] * (freq[i] - 1) / 2; // Case 3: x, x, 2*x for (let i = 1; 2 * i <= max_val; i++) ans += freq[i] * (freq[i] - 1) / 2 * freq[2 * i]; // Case 4: x, y, x + y // iterate through all pairs (x, y) for (let i = 1; i <= max_val; i++) { for (let j = i + 1; i + j <= max_val; j++) ans += freq[i] * freq[j] * freq[i + j]; } return ans; } // Driver code let arr=[1, 2, 3, 4, 5]; let n = arr.length; document.write(countWays(arr, n)); // This code is contributed by patel2127 </script> 4 Shashank12 ronak319 andrew1234 mohit kumar 29 Mithun Kumar Kartik Nigam patel2127 adnanirshad158 frequency-counting Arrays Searching Arrays Searching Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 52, "s": 24, "text": "\n30 Jun, 2021" }, { "code": null, "e": 305, "s": 52, "text": "Given an array A[] of N integers. The task is to find the number of triples (i, j, k) , where i, j, k are indices and (1 <= i < j < k <= N), such that in the set { , , } at least one of the numbers can be written as the sum of the other two.Examples: " }, { "code": null, "e": 455, "s": 305, "text": "Input : A[] = {1, 2, 3, 4, 5}\nOutput : 4\nThe valid triplets are:\n(1, 2, 3), (1, 3, 4), (1, 4, 5), (2, 3, 5)\n\nInput : A[] = {1, 1, 1, 2, 2}\nOutput : 6" }, { "code": null, "e": 574, "s": 457, "text": "This is a counting problem. Let’s say f(x) represents the frequency of number in our array.There exist four cases: " }, { "code": null, "e": 929, "s": 574, "text": "All three numbers are equal to 0. The number of ways = f(0)C3 (where pCq is the number of ways of choosing q numbers from p numbers).One number is equal to 0, the other two are equal to some x > 0: f(0) * f(x)C2.Two numbers are equal to some x>0, the third is 2*x: f(x)C2 * f(2 * x).The three numbers are x, y and x + y, 0 < x, y: f(x) * f(y) * f(x + y)." }, { "code": null, "e": 1063, "s": 929, "text": "All three numbers are equal to 0. The number of ways = f(0)C3 (where pCq is the number of ways of choosing q numbers from p numbers)." }, { "code": null, "e": 1143, "s": 1063, "text": "One number is equal to 0, the other two are equal to some x > 0: f(0) * f(x)C2." }, { "code": null, "e": 1215, "s": 1143, "text": "Two numbers are equal to some x>0, the third is 2*x: f(x)C2 * f(2 * x)." }, { "code": null, "e": 1287, "s": 1215, "text": "The three numbers are x, y and x + y, 0 < x, y: f(x) * f(y) * f(x + y)." }, { "code": null, "e": 1340, "s": 1287, "text": "Below is the implementation of the above approach: " }, { "code": null, "e": 1344, "s": 1340, "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++ program to count Triplets such that at// least one of the numbers can be written// as sum of the other two#include<bits/stdc++.h>using namespace std; // Function to count the number of ways // to choose the triples int countWays(int arr[], int n) { // compute the max value in the array // and create frequency array of size // max_val + 1. // We can also use HashMap to store // frequencies. We have used an array // to keep remaining code simple. int max_val = 0; for (int i = 0; i < n; i++) max_val = max(max_val, arr[i]); int freq[max_val + 1]={0}; for (int i = 0; i < n; i++) freq[arr[i]]++; int ans = 0; // stores the number of ways // Case 1: 0, 0, 0 ans += freq[0] * (freq[0] - 1) * (freq[0] - 2) / 6; // Case 2: 0, x, x for (int i = 1; i <= max_val; i++) ans += freq[0] * freq[i] * (freq[i] - 1) / 2; // Case 3: x, x, 2*x for (int i = 1; 2 * i <= max_val; i++) ans += freq[i] * (freq[i] - 1) / 2 * freq[2 * i]; // Case 4: x, y, x + y // iterate through all pairs (x, y) for (int i = 1; i <= max_val; i++) { for (int j = i + 1; i + j <= max_val; j++) ans += freq[i] * freq[j] * freq[i + j]; } return ans; } // Driver code int main() { int arr[]={ 1, 2, 3, 4, 5 }; int n = sizeof(arr)/sizeof(int); cout<<(countWays(arr, n)); return 0; } //contributed by Arnab Kundu", "e": 2942, "s": 1375, "text": null }, { "code": "// Java program to count Triplets such that at// least one of the numbers can be written// as a sum of the other two class GFG { // Function to count the number of ways // to choose the triples static int countWays(int[] arr, int n) { // compute the max value in the array // and create frequency array of size // max_val + 1. // We can also use HashMap to store // frequencies. We have used an array // to keep remaining code simple. int max_val = 0; for (int i = 0; i < n; i++) max_val = Math.max(max_val, arr[i]); int[] freq = new int[max_val + 1]; for (int i = 0; i < n; i++) freq[arr[i]]++; int ans = 0; // stores the number of ways // Case 1: 0, 0, 0 ans += freq[0] * (freq[0] - 1) * (freq[0] - 2) / 6; // Case 2: 0, x, x for (int i = 1; i <= max_val; i++) ans += freq[0] * freq[i] * (freq[i] - 1) / 2; // Case 3: x, x, 2*x for (int i = 1; 2 * i <= max_val; i++) ans += freq[i] * (freq[i] - 1) / 2 * freq[2 * i]; // Case 4: x, y, x + y // iterate through all pairs (x, y) for (int i = 1; i <= max_val; i++) { for (int j = i + 1; i + j <= max_val; j++) ans += freq[i] * freq[j] * freq[i + j]; } return ans; } // Driver code public static void main(String[] args) { int[] arr = new int[] { 1, 2, 3, 4, 5 }; int n = arr.length; System.out.println(countWays(arr, n)); }}", "e": 4495, "s": 2942, "text": null }, { "code": "# Python3 program to count Triplets such# that at least one of the numbers can be# written as sum of the other twoimport math as mt # Function to count the number of ways# to choose the triplesdef countWays(arr, n): # compute the max value in the array # and create frequency array of size # max_val + 1. # We can also use HashMap to store # frequencies. We have used an array # to keep remaining code simple. max_val = 0 for i in range(n): max_val = max(max_val, arr[i]) freq = [0 for i in range(max_val + 1)] for i in range(n): freq[arr[i]] += 1 ans = 0 # stores the number of ways # Case 1: 0, 0, 0 ans += (freq[0] * (freq[0] - 1) * (freq[0] - 2) // 6) # Case 2: 0, x, x for i in range(1, max_val + 1): ans += (freq[0] * freq[i] * (freq[i] - 1) // 2) # Case 3: x, x, 2*x for i in range(1, (max_val + 1) // 2): ans += (freq[i] * (freq[i] - 1) // 2 * freq[2 * i]) # Case 4: x, y, x + y # iterate through all pairs (x, y) for i in range(1, max_val + 1): for j in range(i + 1, max_val - i + 1): ans += freq[i] * freq[j] * freq[i + j] return ans # Driver codearr = [ 1, 2, 3, 4, 5]n = len(arr)print(countWays(arr, n)) # This code is contributed by# mohit kumar 29", "e": 5813, "s": 4495, "text": null }, { "code": "// C# program to count Triplets// such that at least one of the// numbers can be written as sum// of the other twousing System; class GFG{ // Function to count the number// of ways to choose the triplesstatic int countWays(int[] arr, int n){ // compute the max value in the array // and create frequency array of size // max_val + 1. // We can also use HashMap to store // frequencies. We have used an array // to keep remaining code simple. int max_val = 0; for (int i = 0; i < n; i++) max_val = Math.Max(max_val, arr[i]); int[] freq = new int[max_val + 1]; for (int i = 0; i < n; i++) freq[arr[i]]++; int ans = 0; // stores the number of ways // Case 1: 0, 0, 0 ans += freq[0] * (freq[0] - 1) * (freq[0] - 2) / 6; // Case 2: 0, x, x for (int i = 1; i <= max_val; i++) ans += freq[0] * freq[i] * (freq[i] - 1) / 2; // Case 3: x, x, 2*x for (int i = 1; 2 * i <= max_val; i++) ans += freq[i] * (freq[i] - 1) / 2 * freq[2 * i]; // Case 4: x, y, x + y // iterate through all pairs (x, y) for (int i = 1; i <= max_val; i++) { for (int j = i + 1; i + j <= max_val; j++) ans += freq[i] * freq[j] * freq[i + j]; } return ans;} // Driver codepublic static void Main(){ int[] arr = { 1, 2, 3, 4, 5 }; int n = arr.Length; Console.WriteLine(countWays(arr, n));}} // This code is contributed by shs..", "e": 7361, "s": 5813, "text": null }, { "code": "<?php// PHP program to count Triplets such that at// least one of the numbers can be written// as sum of the other two // Function to count the number of ways// to choose the triplesfunction countWays($arr, $n){ // compute the max value in the array // and create frequency array of size // max_val + 1. // We can also use HashMap to store // frequencies. We have used an array // to keep remaining code simple. $max_val = 0; for ($i = 0; $i < $n; $i++) $max_val = max($max_val, $arr[$i]); $freq = array_fill(0, $max_val + 1, 0); for ($i = 0; $i < $n; $i++) $freq[$arr[$i]]++; $ans = 0; // stores the number of ways // Case 1: 0, 0, 0 $ans += (int)($freq[0] * ($freq[0] - 1) * ($freq[0] - 2) / 6); // Case 2: 0, x, x for ($i = 1; $i <= $max_val; $i++) $ans += (int)($freq[0] * $freq[$i] * ($freq[$i] - 1) / 2); // Case 3: x, x, 2*x for ($i = 1; 2 * $i <= $max_val; $i++) $ans += (int)($freq[$i] * ($freq[$i] - 1) / 2 * $freq[2 * $i]); // Case 4: x, y, x + y // iterate through all pairs (x, y) for ($i = 1; $i <= $max_val; $i++) { for ($j = $i + 1; $i + $j <= $max_val; $j++) $ans += $freq[$i] * $freq[$j] * $freq[$i + $j]; } return $ans;} // Driver code$arr = array( 1, 2, 3, 4, 5 );$n = count($arr);echo countWays($arr, $n); // This code is contributed by mits?>", "e": 8860, "s": 7361, "text": null }, { "code": "<script> // JavaScript program to count Triplets such that at// least one of the numbers can be written// as a sum of the other two // Function to count the number of ways // to choose the triples function countWays(arr,n) { // compute the max value in the array // and create frequency array of size // max_val + 1. // We can also use HashMap to store // frequencies. We have used an array // to keep remaining code simple. let max_val = 0; for (let i = 0; i < n; i++) max_val = Math.max(max_val, arr[i]); let freq = new Array(max_val + 1); for(let i=0;i<freq.length;i++) { freq[i]=0; } for (let i = 0; i < n; i++) freq[arr[i]]++; let ans = 0; // stores the number of ways // Case 1: 0, 0, 0 ans += freq[0] * (freq[0] - 1) * (freq[0] - 2) / 6; // Case 2: 0, x, x for (let i = 1; i <= max_val; i++) ans += freq[0] * freq[i] * (freq[i] - 1) / 2; // Case 3: x, x, 2*x for (let i = 1; 2 * i <= max_val; i++) ans += freq[i] * (freq[i] - 1) / 2 * freq[2 * i]; // Case 4: x, y, x + y // iterate through all pairs (x, y) for (let i = 1; i <= max_val; i++) { for (let j = i + 1; i + j <= max_val; j++) ans += freq[i] * freq[j] * freq[i + j]; } return ans; } // Driver code let arr=[1, 2, 3, 4, 5]; let n = arr.length; document.write(countWays(arr, n)); // This code is contributed by patel2127 </script>", "e": 10476, "s": 8860, "text": null }, { "code": null, "e": 10478, "s": 10476, "text": "4" }, { "code": null, "e": 10491, "s": 10480, "text": "Shashank12" }, { "code": null, "e": 10500, "s": 10491, "text": "ronak319" }, { "code": null, "e": 10511, "s": 10500, "text": "andrew1234" }, { "code": null, "e": 10526, "s": 10511, "text": "mohit kumar 29" }, { "code": null, "e": 10539, "s": 10526, "text": "Mithun Kumar" }, { "code": null, "e": 10552, "s": 10539, "text": "Kartik Nigam" }, { "code": null, "e": 10562, "s": 10552, "text": "patel2127" }, { "code": null, "e": 10577, "s": 10562, "text": "adnanirshad158" }, { "code": null, "e": 10596, "s": 10577, "text": "frequency-counting" }, { "code": null, "e": 10603, "s": 10596, "text": "Arrays" }, { "code": null, "e": 10613, "s": 10603, "text": "Searching" }, { "code": null, "e": 10620, "s": 10613, "text": "Arrays" }, { "code": null, "e": 10630, "s": 10620, "text": "Searching" } ]
Software Engineering | Project Planning
06 May, 2019 Once a project is found to be possible, computer code project managers undertake project designing. Project designing is undertaken and completed even before any development activity starts. Project designing consists of subsequent essential activities: Estimating the subsequent attributes of the project: Project size:What’s going to be downside quality in terms of the trouble and time needed to develop the product? Cost:What proportion is it reaching to value to develop the project? Duration:However long is it reaching to want complete development? Effort:What proportion effort would be required? The effectiveness of the following designing activities relies on the accuracy of those estimations. planning force and alternative resources workers organization and staffing plans Risk identification, analysis, and abatement designing Miscellaneous arranges like quality assurance plan, configuration, management arrange, etc. Precedence ordering among project planning activities:The different project connected estimates done by a project manager have already been mentioned. The below diagram shows the order during which vital project coming up with activities is also undertaken. It may be simply discovered that size estimation is that the 1st activity. It’s conjointly the foremost basic parameter supported that all alternative coming up with activities square measure dispensed, alternative estimations like the estimation of effort, cost, resource, and project length also are vital elements of the project coming up with. Sliding Window Planning:Project designing needs utmost care and a spotlight since commitment to unrealistic time and resource estimates end in schedule slippage. Schedule delays will cause client discontent and adversely have an effect on team morale. It will even cause project failure. However, project designing could be a terribly difficult activity. particularly for giant comes, it’s pretty much troublesome to create correct plans. A region of this issue is thanks to the actual fact that the correct parameters, the scope of the project, project workers, etc. might amendment throughout the span of the project. So as to beat this drawback, generally project managers undertake project designing little by little. Designing a project over a variety of stages protects managers from creating huge commitments too early. This method of staggered designing is thought of as window designing. Within the window technique, beginning with associate initial set up, the project is planned additional accurately in sequential development stages. At the beginning of a project, project managers have incomplete information concerning the main points of the project. Their info base step by step improves because the project progresses through completely different phases. When the completion of each section, the project managers will set up every ulterior section additional accurately and with increasing levels of confidence. Software Engineering Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Functional vs Non Functional Requirements Differences between Verification and Validation Unit Testing | Software Testing Software Engineering | Classical Waterfall Model Software Requirement Specification (SRS) Format Difference between Spring and Spring Boot Software Engineering | Requirements Engineering Process Software Testing Life Cycle (STLC) Difference between IAAS, PAAS and SAAS Equivalence Partitioning Method
[ { "code": null, "e": 28, "s": 0, "text": "\n06 May, 2019" }, { "code": null, "e": 282, "s": 28, "text": "Once a project is found to be possible, computer code project managers undertake project designing. Project designing is undertaken and completed even before any development activity starts. Project designing consists of subsequent essential activities:" }, { "code": null, "e": 335, "s": 282, "text": "Estimating the subsequent attributes of the project:" }, { "code": null, "e": 448, "s": 335, "text": "Project size:What’s going to be downside quality in terms of the trouble and time needed to develop the product?" }, { "code": null, "e": 517, "s": 448, "text": "Cost:What proportion is it reaching to value to develop the project?" }, { "code": null, "e": 584, "s": 517, "text": "Duration:However long is it reaching to want complete development?" }, { "code": null, "e": 633, "s": 584, "text": "Effort:What proportion effort would be required?" }, { "code": null, "e": 734, "s": 633, "text": "The effectiveness of the following designing activities relies on the accuracy of those estimations." }, { "code": null, "e": 775, "s": 734, "text": "planning force and alternative resources" }, { "code": null, "e": 815, "s": 775, "text": "workers organization and staffing plans" }, { "code": null, "e": 870, "s": 815, "text": "Risk identification, analysis, and abatement designing" }, { "code": null, "e": 962, "s": 870, "text": "Miscellaneous arranges like quality assurance plan, configuration, management arrange, etc." }, { "code": null, "e": 1568, "s": 962, "text": "Precedence ordering among project planning activities:The different project connected estimates done by a project manager have already been mentioned. The below diagram shows the order during which vital project coming up with activities is also undertaken. It may be simply discovered that size estimation is that the 1st activity. It’s conjointly the foremost basic parameter supported that all alternative coming up with activities square measure dispensed, alternative estimations like the estimation of effort, cost, resource, and project length also are vital elements of the project coming up with." }, { "code": null, "e": 1856, "s": 1568, "text": "Sliding Window Planning:Project designing needs utmost care and a spotlight since commitment to unrealistic time and resource estimates end in schedule slippage. Schedule delays will cause client discontent and adversely have an effect on team morale. It will even cause project failure." }, { "code": null, "e": 2614, "s": 1856, "text": "However, project designing could be a terribly difficult activity. particularly for giant comes, it’s pretty much troublesome to create correct plans. A region of this issue is thanks to the actual fact that the correct parameters, the scope of the project, project workers, etc. might amendment throughout the span of the project. So as to beat this drawback, generally project managers undertake project designing little by little. Designing a project over a variety of stages protects managers from creating huge commitments too early. This method of staggered designing is thought of as window designing. Within the window technique, beginning with associate initial set up, the project is planned additional accurately in sequential development stages." }, { "code": null, "e": 2996, "s": 2614, "text": "At the beginning of a project, project managers have incomplete information concerning the main points of the project. Their info base step by step improves because the project progresses through completely different phases. When the completion of each section, the project managers will set up every ulterior section additional accurately and with increasing levels of confidence." }, { "code": null, "e": 3017, "s": 2996, "text": "Software Engineering" }, { "code": null, "e": 3115, "s": 3017, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 3157, "s": 3115, "text": "Functional vs Non Functional Requirements" }, { "code": null, "e": 3205, "s": 3157, "text": "Differences between Verification and Validation" }, { "code": null, "e": 3237, "s": 3205, "text": "Unit Testing | Software Testing" }, { "code": null, "e": 3286, "s": 3237, "text": "Software Engineering | Classical Waterfall Model" }, { "code": null, "e": 3334, "s": 3286, "text": "Software Requirement Specification (SRS) Format" }, { "code": null, "e": 3376, "s": 3334, "text": "Difference between Spring and Spring Boot" }, { "code": null, "e": 3432, "s": 3376, "text": "Software Engineering | Requirements Engineering Process" }, { "code": null, "e": 3467, "s": 3432, "text": "Software Testing Life Cycle (STLC)" }, { "code": null, "e": 3506, "s": 3467, "text": "Difference between IAAS, PAAS and SAAS" } ]
Sorted insert in a doubly linked list with head and tail pointers
11 Jun, 2022 A Doubly linked list is a linked list that consists of a set of sequentially linked records called nodes. Each node contains two fields that are references to the previous and to the next node in the sequence of nodes.The task is to create a doubly linked list by inserting nodes such that list remains in ascending order on printing from left to right. Also, we need to maintain two pointers, head (points to first node) and tail (points to last node).Examples: Input : 40 50 10 45 90 100 95 Output :10 40 45 50 90 95 100 Input : 30 10 50 43 56 12 Output :10 12 30 43 50 56 Algorithm: The task can be accomplished as: If Linked list is empty then make both the left and right pointers point to the node to be inserted and make its previous and next field point to NULL.If node to be inserted has value less than the value of first node of linked list then connect that node from previous field of first node.If node to be inserted has value more than the value of last node of linked list then connect that node from next field of last node.If node to be inserted has value in between the value of first and last node, then check for appropriate position and make connections. If Linked list is empty then make both the left and right pointers point to the node to be inserted and make its previous and next field point to NULL. If node to be inserted has value less than the value of first node of linked list then connect that node from previous field of first node. If node to be inserted has value more than the value of last node of linked list then connect that node from next field of last node. If node to be inserted has value in between the value of first and last node, then check for appropriate position and make connections. C++ C Java Python C# Javascript /* C++ program to insetail nodes in doublylinked list such that list remains inascending order on printing from leftto right */#include <bits/stdc++.h>using namespace std; // A linked list nodeclass Node{ public: Node *prev; int info; Node *next;}; // Function to insetail new nodevoid nodeInsetail(Node **head, Node **tail, int key){ Node *p = new Node(); p->info = key; p->next = NULL; // If first node to be insetailed in doubly // linked list if ((*head) == NULL) { (*head) = p; (*tail) = p; (*head)->prev = NULL; return; } // If node to be insetailed has value less // than first node if ((p->info) < ((*head)->info)) { p->prev = NULL; (*head)->prev = p; p->next = (*head); (*head) = p; return; } // If node to be insetailed has value more // than last node if ((p->info) > ((*tail)->info)) { p->prev = (*tail); (*tail)->next = p; (*tail) = p; return; } // Find the node before which we need to // insert p. Node *temp = (*head)->next; while ((temp->info) < (p->info)) temp = temp->next; // Insert new node before temp (temp->prev)->next = p; p->prev = temp->prev; temp->prev = p; p->next = temp;} // Function to print nodes in from left to rightvoid printList(Node *temp){ while (temp != NULL) { cout << temp->info << " "; temp = temp->next; }} // Driver program to test above functionsint main(){ Node *left = NULL, *right = NULL; nodeInsetail(&left, &right, 30); nodeInsetail(&left, &right, 50); nodeInsetail(&left, &right, 90); nodeInsetail(&left, &right, 10); nodeInsetail(&left, &right, 40); nodeInsetail(&left, &right, 110); nodeInsetail(&left, &right, 60); nodeInsetail(&left, &right, 95); nodeInsetail(&left, &right, 23); cout<<"Doubly linked list on printing" " from left to right\n"; printList(left); return 0;} // This is code is contributed by rathbhupendra /* C program to insetail nodes in doublylinked list such that list remains inascending order on printing from leftto right */#include<stdio.h>#include<stdlib.h> // A linked list nodestruct Node{ struct Node *prev; int info; struct Node *next;}; // Function to insetail new nodevoid nodeInsetail(struct Node **head, struct Node **tail, int key){ struct Node *p = new Node; p->info = key; p->next = NULL; // If first node to be insetailed in doubly // linked list if ((*head) == NULL) { (*head) = p; (*tail) = p; (*head)->prev = NULL; return; } // If node to be insetailed has value less // than first node if ((p->info) < ((*head)->info)) { p->prev = NULL; (*head)->prev = p; p->next = (*head); (*head) = p; return; } // If node to be insetailed has value more // than last node if ((p->info) > ((*tail)->info)) { p->prev = (*tail); (*tail)->next = p; (*tail) = p; return; } // Find the node before which we need to // insert p. temp = (*head)->next; while ((temp->info) < (p->info)) temp = temp->next; // Insert new node before temp (temp->prev)->next = p; p->prev = temp->prev; temp->prev = p; p->next = temp;} // Function to print nodes in from left to rightvoid printList(struct Node *temp){ while (temp != NULL) { printf("%d ", temp->info); temp = temp->next; }} // Driver program to test above functionsint main(){ struct Node *left = NULL, *right = NULL; nodeInsetail(&left, &right, 30); nodeInsetail(&left, &right, 50); nodeInsetail(&left, &right, 90); nodeInsetail(&left, &right, 10); nodeInsetail(&left, &right, 40); nodeInsetail(&left, &right, 110); nodeInsetail(&left, &right, 60); nodeInsetail(&left, &right, 95); nodeInsetail(&left, &right, 23); printf("\nDoubly linked list on printing" " from left to right\n"); printList(left); return 0;} /* Java program to insetail nodes in doublylinked list such that list remains inascending order on printing from leftto right */ import java.io.*;import java.util.*; // A linked list nodeclass Node{ int info; Node prev, next;} class GFG{ static Node head, tail; // Function to insetail new node static void nodeInsetail(int key) { Node p = new Node(); p.info = key; p.next = null; // If first node to be insetailed in doubly // linked list if (head == null) { head = p; tail = p; head.prev = null; return; } // If node to be insetailed has value less // than first node if (p.info < head.info) { p.prev = null; head.prev = p; p.next = head; head = p; return; } // If node to be insetailed has value more // than last node if (p.info > tail.info) { p.prev = tail; tail.next = p; tail = p; return; } // Find the node before which we need to // insert p. Node temp = head.next; while (temp.info < p.info) temp = temp.next; // Insert new node before temp (temp.prev).next = p; p.prev = temp.prev; temp.prev = p; p.next = temp; } // Function to print nodes in from left to right static void printList(Node temp) { while (temp != null) { System.out.print(temp.info + " "); temp = temp.next; } } // Driver code public static void main(String args[]) { head = tail = null; nodeInsetail(30); nodeInsetail(50); nodeInsetail(90); nodeInsetail(10); nodeInsetail(40); nodeInsetail(110); nodeInsetail(60); nodeInsetail(95); nodeInsetail(23); System.out.println("Doubly linked list on printing from left to right"); printList(head); }} // This code is contributed by rachana soma # Python program to insetail nodes in doubly# linked list such that list remains in# ascending order on printing from left# to right # Linked List nodeclass Node: def __init__(self, data): self.info = data self.next = None self.prev = None head = Nonetail = None # Function to insetail new nodedef nodeInsetail( key) : global head global tail p = Node(0) p.info = key p.next = None # If first node to be insetailed in doubly # linked list if ((head) == None) : (head) = p (tail) = p (head).prev = None return # If node to be insetailed has value less # than first node if ((p.info) < ((head).info)) : p.prev = None (head).prev = p p.next = (head) (head) = p return # If node to be insetailed has value more # than last node if ((p.info) > ((tail).info)) : p.prev = (tail) (tail).next = p (tail) = p return # Find the node before which we need to # insert p. temp = (head).next while ((temp.info) < (p.info)) : temp = temp.next # Insert new node before temp (temp.prev).next = p p.prev = temp.prev temp.prev = p p.next = temp # Function to print nodes in from left to rightdef printList(temp) : while (temp != None) : print( temp.info, end = " ") temp = temp.next # Driver program to test above functionsnodeInsetail( 30)nodeInsetail( 50)nodeInsetail( 90)nodeInsetail( 10)nodeInsetail( 40)nodeInsetail( 110)nodeInsetail( 60)nodeInsetail( 95)nodeInsetail( 23) print("Doubly linked list on printing from left to right\n" ) printList(head) # This code is contributed by Arnab Kundu /* C# program to insetail nodes in doublylinked list such that list remains inascending order on printing from leftto right */using System; // A linked list nodepublic class Node{ public int info; public Node prev, next;} class GFG{ static Node head, tail; // Function to insetail new node static void nodeInsetail(int key) { Node p = new Node(); p.info = key; p.next = null; // If first node to be insetailed in doubly // linked list if (head == null) { head = p; tail = p; head.prev = null; return; } // If node to be insetailed has value less // than first node if (p.info < head.info) { p.prev = null; head.prev = p; p.next = head; head = p; return; } // If node to be insetailed has value more // than last node if (p.info > tail.info) { p.prev = tail; tail.next = p; tail = p; return; } // Find the node before which we need to // insert p. Node temp = head.next; while (temp.info < p.info) temp = temp.next; // Insert new node before temp (temp.prev).next = p; p.prev = temp.prev; temp.prev = p; p.next = temp; } // Function to print nodes in from left to right static void printList(Node temp) { while (temp != null) { Console.Write(temp.info + " "); temp = temp.next; } } // Driver code public static void Main(String []args) { head = tail = null; nodeInsetail(30); nodeInsetail(50); nodeInsetail(90); nodeInsetail(10); nodeInsetail(40); nodeInsetail(110); nodeInsetail(60); nodeInsetail(95); nodeInsetail(23); Console.WriteLine("Doubly linked list on printing from left to right"); printList(head); }} // This code is contributed by Arnab Kundu <script>/* javascript program to insetail nodes in doublylinked list such that list remains inascending order on printing from leftto right */ // A linked list node class Node { constructor() { this.info = 0; this.prev = null; this.next = null; } }var head, tail; // Function to insetail new node function nodeInsetail(key) { p = new Node(); p.info = key; p.next = null; // If first node to be insetailed in doubly // linked list if (head == null) { head = p; tail = p; head.prev = null; return; } // If node to be insetailed has value less // than first node if (p.info < head.info) { p.prev = null; head.prev = p; p.next = head; head = p; return; } // If node to be insetailed has value more // than last node if (p.info > tail.info) { p.prev = tail; tail.next = p; tail = p; return; } // Find the node before which we need to // insert p. temp = head.next; while (temp.info < p.info) temp = temp.next; // Insert new node before temp (temp.prev).next = p; p.prev = temp.prev; temp.prev = p; p.next = temp; } // Function to print nodes in from left to right function printList( temp) { while (temp != null) { document.write(temp.info + " "); temp = temp.next; } } // Driver code head = tail = null; nodeInsetail(30); nodeInsetail(50); nodeInsetail(90); nodeInsetail(10); nodeInsetail(40); nodeInsetail(110); nodeInsetail(60); nodeInsetail(95); nodeInsetail(23); document.write("Doubly linked list on printing from left to right<br/>"); printList(head); // This code is contributed by aashish1995</script> Doubly linked list on printing from left to right 10 23 30 40 50 60 90 95 110 Time complexity: O(n) since using a single loop to traverse doubly linked list Auxiliary Space: O(1) rathbhupendra rachana soma andrew1234 aashish1995 khushboogoyal499 polymatir3j doubly linked list Linked List Linked List Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 52, "s": 24, "text": "\n11 Jun, 2022" }, { "code": null, "e": 517, "s": 52, "text": "A Doubly linked list is a linked list that consists of a set of sequentially linked records called nodes. Each node contains two fields that are references to the previous and to the next node in the sequence of nodes.The task is to create a doubly linked list by inserting nodes such that list remains in ascending order on printing from left to right. Also, we need to maintain two pointers, head (points to first node) and tail (points to last node).Examples: " }, { "code": null, "e": 630, "s": 517, "text": "Input : 40 50 10 45 90 100 95\nOutput :10 40 45 50 90 95 100\n\nInput : 30 10 50 43 56 12\nOutput :10 12 30 43 50 56" }, { "code": null, "e": 678, "s": 632, "text": "Algorithm: The task can be accomplished as: " }, { "code": null, "e": 1237, "s": 678, "text": "If Linked list is empty then make both the left and right pointers point to the node to be inserted and make its previous and next field point to NULL.If node to be inserted has value less than the value of first node of linked list then connect that node from previous field of first node.If node to be inserted has value more than the value of last node of linked list then connect that node from next field of last node.If node to be inserted has value in between the value of first and last node, then check for appropriate position and make connections." }, { "code": null, "e": 1389, "s": 1237, "text": "If Linked list is empty then make both the left and right pointers point to the node to be inserted and make its previous and next field point to NULL." }, { "code": null, "e": 1529, "s": 1389, "text": "If node to be inserted has value less than the value of first node of linked list then connect that node from previous field of first node." }, { "code": null, "e": 1663, "s": 1529, "text": "If node to be inserted has value more than the value of last node of linked list then connect that node from next field of last node." }, { "code": null, "e": 1799, "s": 1663, "text": "If node to be inserted has value in between the value of first and last node, then check for appropriate position and make connections." }, { "code": null, "e": 1805, "s": 1801, "text": "C++" }, { "code": null, "e": 1807, "s": 1805, "text": "C" }, { "code": null, "e": 1812, "s": 1807, "text": "Java" }, { "code": null, "e": 1819, "s": 1812, "text": "Python" }, { "code": null, "e": 1822, "s": 1819, "text": "C#" }, { "code": null, "e": 1833, "s": 1822, "text": "Javascript" }, { "code": "/* C++ program to insetail nodes in doublylinked list such that list remains inascending order on printing from leftto right */#include <bits/stdc++.h>using namespace std; // A linked list nodeclass Node{ public: Node *prev; int info; Node *next;}; // Function to insetail new nodevoid nodeInsetail(Node **head, Node **tail, int key){ Node *p = new Node(); p->info = key; p->next = NULL; // If first node to be insetailed in doubly // linked list if ((*head) == NULL) { (*head) = p; (*tail) = p; (*head)->prev = NULL; return; } // If node to be insetailed has value less // than first node if ((p->info) < ((*head)->info)) { p->prev = NULL; (*head)->prev = p; p->next = (*head); (*head) = p; return; } // If node to be insetailed has value more // than last node if ((p->info) > ((*tail)->info)) { p->prev = (*tail); (*tail)->next = p; (*tail) = p; return; } // Find the node before which we need to // insert p. Node *temp = (*head)->next; while ((temp->info) < (p->info)) temp = temp->next; // Insert new node before temp (temp->prev)->next = p; p->prev = temp->prev; temp->prev = p; p->next = temp;} // Function to print nodes in from left to rightvoid printList(Node *temp){ while (temp != NULL) { cout << temp->info << \" \"; temp = temp->next; }} // Driver program to test above functionsint main(){ Node *left = NULL, *right = NULL; nodeInsetail(&left, &right, 30); nodeInsetail(&left, &right, 50); nodeInsetail(&left, &right, 90); nodeInsetail(&left, &right, 10); nodeInsetail(&left, &right, 40); nodeInsetail(&left, &right, 110); nodeInsetail(&left, &right, 60); nodeInsetail(&left, &right, 95); nodeInsetail(&left, &right, 23); cout<<\"Doubly linked list on printing\" \" from left to right\\n\"; printList(left); return 0;} // This is code is contributed by rathbhupendra", "e": 3907, "s": 1833, "text": null }, { "code": "/* C program to insetail nodes in doublylinked list such that list remains inascending order on printing from leftto right */#include<stdio.h>#include<stdlib.h> // A linked list nodestruct Node{ struct Node *prev; int info; struct Node *next;}; // Function to insetail new nodevoid nodeInsetail(struct Node **head, struct Node **tail, int key){ struct Node *p = new Node; p->info = key; p->next = NULL; // If first node to be insetailed in doubly // linked list if ((*head) == NULL) { (*head) = p; (*tail) = p; (*head)->prev = NULL; return; } // If node to be insetailed has value less // than first node if ((p->info) < ((*head)->info)) { p->prev = NULL; (*head)->prev = p; p->next = (*head); (*head) = p; return; } // If node to be insetailed has value more // than last node if ((p->info) > ((*tail)->info)) { p->prev = (*tail); (*tail)->next = p; (*tail) = p; return; } // Find the node before which we need to // insert p. temp = (*head)->next; while ((temp->info) < (p->info)) temp = temp->next; // Insert new node before temp (temp->prev)->next = p; p->prev = temp->prev; temp->prev = p; p->next = temp;} // Function to print nodes in from left to rightvoid printList(struct Node *temp){ while (temp != NULL) { printf(\"%d \", temp->info); temp = temp->next; }} // Driver program to test above functionsint main(){ struct Node *left = NULL, *right = NULL; nodeInsetail(&left, &right, 30); nodeInsetail(&left, &right, 50); nodeInsetail(&left, &right, 90); nodeInsetail(&left, &right, 10); nodeInsetail(&left, &right, 40); nodeInsetail(&left, &right, 110); nodeInsetail(&left, &right, 60); nodeInsetail(&left, &right, 95); nodeInsetail(&left, &right, 23); printf(\"\\nDoubly linked list on printing\" \" from left to right\\n\"); printList(left); return 0;}", "e": 5964, "s": 3907, "text": null }, { "code": "/* Java program to insetail nodes in doublylinked list such that list remains inascending order on printing from leftto right */ import java.io.*;import java.util.*; // A linked list nodeclass Node{ int info; Node prev, next;} class GFG{ static Node head, tail; // Function to insetail new node static void nodeInsetail(int key) { Node p = new Node(); p.info = key; p.next = null; // If first node to be insetailed in doubly // linked list if (head == null) { head = p; tail = p; head.prev = null; return; } // If node to be insetailed has value less // than first node if (p.info < head.info) { p.prev = null; head.prev = p; p.next = head; head = p; return; } // If node to be insetailed has value more // than last node if (p.info > tail.info) { p.prev = tail; tail.next = p; tail = p; return; } // Find the node before which we need to // insert p. Node temp = head.next; while (temp.info < p.info) temp = temp.next; // Insert new node before temp (temp.prev).next = p; p.prev = temp.prev; temp.prev = p; p.next = temp; } // Function to print nodes in from left to right static void printList(Node temp) { while (temp != null) { System.out.print(temp.info + \" \"); temp = temp.next; } } // Driver code public static void main(String args[]) { head = tail = null; nodeInsetail(30); nodeInsetail(50); nodeInsetail(90); nodeInsetail(10); nodeInsetail(40); nodeInsetail(110); nodeInsetail(60); nodeInsetail(95); nodeInsetail(23); System.out.println(\"Doubly linked list on printing from left to right\"); printList(head); }} // This code is contributed by rachana soma", "e": 8094, "s": 5964, "text": null }, { "code": "# Python program to insetail nodes in doubly# linked list such that list remains in# ascending order on printing from left# to right # Linked List nodeclass Node: def __init__(self, data): self.info = data self.next = None self.prev = None head = Nonetail = None # Function to insetail new nodedef nodeInsetail( key) : global head global tail p = Node(0) p.info = key p.next = None # If first node to be insetailed in doubly # linked list if ((head) == None) : (head) = p (tail) = p (head).prev = None return # If node to be insetailed has value less # than first node if ((p.info) < ((head).info)) : p.prev = None (head).prev = p p.next = (head) (head) = p return # If node to be insetailed has value more # than last node if ((p.info) > ((tail).info)) : p.prev = (tail) (tail).next = p (tail) = p return # Find the node before which we need to # insert p. temp = (head).next while ((temp.info) < (p.info)) : temp = temp.next # Insert new node before temp (temp.prev).next = p p.prev = temp.prev temp.prev = p p.next = temp # Function to print nodes in from left to rightdef printList(temp) : while (temp != None) : print( temp.info, end = \" \") temp = temp.next # Driver program to test above functionsnodeInsetail( 30)nodeInsetail( 50)nodeInsetail( 90)nodeInsetail( 10)nodeInsetail( 40)nodeInsetail( 110)nodeInsetail( 60)nodeInsetail( 95)nodeInsetail( 23) print(\"Doubly linked list on printing from left to right\\n\" ) printList(head) # This code is contributed by Arnab Kundu", "e": 9830, "s": 8094, "text": null }, { "code": "/* C# program to insetail nodes in doublylinked list such that list remains inascending order on printing from leftto right */using System; // A linked list nodepublic class Node{ public int info; public Node prev, next;} class GFG{ static Node head, tail; // Function to insetail new node static void nodeInsetail(int key) { Node p = new Node(); p.info = key; p.next = null; // If first node to be insetailed in doubly // linked list if (head == null) { head = p; tail = p; head.prev = null; return; } // If node to be insetailed has value less // than first node if (p.info < head.info) { p.prev = null; head.prev = p; p.next = head; head = p; return; } // If node to be insetailed has value more // than last node if (p.info > tail.info) { p.prev = tail; tail.next = p; tail = p; return; } // Find the node before which we need to // insert p. Node temp = head.next; while (temp.info < p.info) temp = temp.next; // Insert new node before temp (temp.prev).next = p; p.prev = temp.prev; temp.prev = p; p.next = temp; } // Function to print nodes in from left to right static void printList(Node temp) { while (temp != null) { Console.Write(temp.info + \" \"); temp = temp.next; } } // Driver code public static void Main(String []args) { head = tail = null; nodeInsetail(30); nodeInsetail(50); nodeInsetail(90); nodeInsetail(10); nodeInsetail(40); nodeInsetail(110); nodeInsetail(60); nodeInsetail(95); nodeInsetail(23); Console.WriteLine(\"Doubly linked list on printing from left to right\"); printList(head); }} // This code is contributed by Arnab Kundu", "e": 11938, "s": 9830, "text": null }, { "code": "<script>/* javascript program to insetail nodes in doublylinked list such that list remains inascending order on printing from leftto right */ // A linked list node class Node { constructor() { this.info = 0; this.prev = null; this.next = null; } }var head, tail; // Function to insetail new node function nodeInsetail(key) { p = new Node(); p.info = key; p.next = null; // If first node to be insetailed in doubly // linked list if (head == null) { head = p; tail = p; head.prev = null; return; } // If node to be insetailed has value less // than first node if (p.info < head.info) { p.prev = null; head.prev = p; p.next = head; head = p; return; } // If node to be insetailed has value more // than last node if (p.info > tail.info) { p.prev = tail; tail.next = p; tail = p; return; } // Find the node before which we need to // insert p. temp = head.next; while (temp.info < p.info) temp = temp.next; // Insert new node before temp (temp.prev).next = p; p.prev = temp.prev; temp.prev = p; p.next = temp; } // Function to print nodes in from left to right function printList( temp) { while (temp != null) { document.write(temp.info + \" \"); temp = temp.next; } } // Driver code head = tail = null; nodeInsetail(30); nodeInsetail(50); nodeInsetail(90); nodeInsetail(10); nodeInsetail(40); nodeInsetail(110); nodeInsetail(60); nodeInsetail(95); nodeInsetail(23); document.write(\"Doubly linked list on printing from left to right<br/>\"); printList(head); // This code is contributed by aashish1995</script>", "e": 13973, "s": 11938, "text": null }, { "code": null, "e": 14051, "s": 13973, "text": "Doubly linked list on printing from left to right\n10 23 30 40 50 60 90 95 110" }, { "code": null, "e": 14132, "s": 14053, "text": "Time complexity: O(n) since using a single loop to traverse doubly linked list" }, { "code": null, "e": 14154, "s": 14132, "text": "Auxiliary Space: O(1)" }, { "code": null, "e": 14168, "s": 14154, "text": "rathbhupendra" }, { "code": null, "e": 14181, "s": 14168, "text": "rachana soma" }, { "code": null, "e": 14192, "s": 14181, "text": "andrew1234" }, { "code": null, "e": 14204, "s": 14192, "text": "aashish1995" }, { "code": null, "e": 14221, "s": 14204, "text": "khushboogoyal499" }, { "code": null, "e": 14233, "s": 14221, "text": "polymatir3j" }, { "code": null, "e": 14252, "s": 14233, "text": "doubly linked list" }, { "code": null, "e": 14264, "s": 14252, "text": "Linked List" }, { "code": null, "e": 14276, "s": 14264, "text": "Linked List" } ]
How to get Slice of a Stream in Java
11 Dec, 2018 A stream is a sequence of objects that supports various methods which can be pipelined to produce the desired result. Slice of a Stream means a stream of elements that exists in a specified limit, from the original stream. Examples: Input: [11, 12, 13, 14, 15, 16, 17, 18, 19, 20]Output: [15, 16, 17, 18, 19]Explanation: The output contains a slice of the stream from index 4 to 8. Input: [1, 2, 3, 4, 5, 6, 7, 8, 9]Output: [2, 3, 4]Explanation: The output contains a slice of the stream from index 1 to 3. Below are the methods to remove nulls from a List in Java: Using skip() and limit(): Stream API in Java provides skip() method which is used to discard the other non-required elements from the stream. It also provides limit() function which is applied to fetch the new stream with the specified index as limit, in the encountered order.Algorithm:Get the Stream to be sliced.Get the From and To index to be sliced from Stream as StartIndex and EndIndexCall skip() method to specify the number of elements to be skipped before the starting index as skip(startIndex)Call limit() method to specify the number of elements, from the stream, that should be limited as limit(endIndex – startIndex + 1)Return the Sliced Stream// Java program to get slice of a stream using// Stream skip() and limit()import java.util.*;import java.util.stream.Stream; class GFG { // Generic function to get Slice of a // Stream from startIndex to endIndex public static <T> Stream<T> getSliceOfStream(Stream<T> stream, int startIndex, int endIndex) { return stream // specify the number of elements to skip .skip(startIndex) // specify the no. of elements the stream // that should be limited .limit(endIndex - startIndex + 1); } public static void main(String[] args) { // Create a new List with values 11 - 20 List<Integer> list = new ArrayList<>(); for (int i = 11; i <= 20; i++) list.add(i); // Create stream from list Stream<Integer> intStream = list.stream(); // Print the stream System.out.println("List: " + list); // Get Slice of Stream // containing of elements from the 4th index to 8th Stream<Integer> sliceOfIntStream = getSliceOfStream(intStream, 4, 8); // Print the slice System.out.println("\nSlice of Stream:"); sliceOfIntStream.forEach(System.out::println); }}Output:List: [11, 12, 13, 14, 15, 16, 17, 18, 19, 20] Slice of Stream: 15 16 17 18 19 Using Collectors along with skip() and limit(): In this method, the Stream is converted to List and then a function of a collector to get sub-list of desired elements is used and the sub-list id converted back to a stream using stream.collect(Collectors.collectingAndThen()).Algorithm:Get the Stream to be sliced.Get the From and To index to be sliced from Stream as StartIndex and EndIndexUsing Collectors.collectingAndThen,Convert the Stream to List using Collectors.toList()Obtain the Stream from the List as list.stream()Call skip() method to specify the number of elements to be skipped before the starting index as skip(startIndex)Call limit() method to specify the number of elements, from the stream, that should be limited as limit(endIndex – startIndex + 1)Collect the sliced list stream using stream.collect()Return the Sliced Stream// Java program to get slice of a stream using// Collection skip() and limit()import java.util.*;import java.util.stream.*; class GFG { // Generic function to get Slice of a // Stream from startIndex to endIndex public static <T> Stream<T> getSliceOfStream(Stream<T> stream, int startIndex, int endIndex) { return stream.collect(Collectors.collectingAndThen( // 1st argument // Convert the stream to list Collectors.toList(), // 2nd argument list -> list.stream() // specify the number of elements to skip .skip(startIndex) // specify the no. of elements the stream // that should be limited .limit(endIndex - startIndex + 1))); } public static void main(String[] args) { // Create a new List with values 11 - 20 List<Integer> list = new ArrayList<>(); for (int i = 11; i <= 20; i++) list.add(i); // Create stream from list Stream<Integer> intStream = list.stream(); // Print the stream System.out.println("List: " + list); // Get Slice of Stream // containing of elements from the 4th index to 8th Stream<Integer> sliceOfIntStream = getSliceOfStream(intStream, 4, 8); // Print the slice System.out.println("\nSlice of Stream:"); sliceOfIntStream.forEach(System.out::println); }}Output:List: [11, 12, 13, 14, 15, 16, 17, 18, 19, 20] Slice of Stream: 15 16 17 18 19 Fetching a SubList: This method involves converting a Stream into a List. Now this list is used to fetch a required subList from it between the specified index. And finally, this subList is converted back to Stream.Algorithm:Get the Stream to be sliced.Get the From and To index to be sliced from Stream as StartIndex and EndIndexConvert the Stream to List using Collectors.toList() and then collect it using stream.collect()Fetch the subList from the collected List with the startIndex and endIndex+1 as the limit using subList(startIndex, endIndex + 1)Convert the subList back to stream using stream()Return the Sliced Stream// Java program to get slice of a stream by// fetching a sublistimport java.util.*;import java.util.stream.*; class GFG { // Generic function to get Slice of a // Stream from startIndex to endIndex public static <T> Stream<T> getSliceOfStream(Stream<T> stream, int startIndex, int endIndex) { return stream // Convert the stream to list .collect(Collectors.toList()) // Fetch the subList between the specified index .subList(startIndex, endIndex + 1) // Convert the subList to stream .stream(); } public static void main(String[] args) { // Create a new List with values 11 - 20 List<Integer> list = new ArrayList<>(); for (int i = 11; i <= 20; i++) list.add(i); // Create stream from list Stream<Integer> intStream = list.stream(); // Print the stream System.out.println("List: " + list); // Get Slice of Stream // containing of elements from the 4th index to 8th Stream<Integer> sliceOfIntStream = getSliceOfStream(intStream, 4, 8); // Print the slice System.out.println("\nSlice of Stream:"); sliceOfIntStream.forEach(System.out::println); }}Output:List: [11, 12, 13, 14, 15, 16, 17, 18, 19, 20] Slice of Stream: 15 16 17 18 19 Using skip() and limit(): Stream API in Java provides skip() method which is used to discard the other non-required elements from the stream. It also provides limit() function which is applied to fetch the new stream with the specified index as limit, in the encountered order.Algorithm:Get the Stream to be sliced.Get the From and To index to be sliced from Stream as StartIndex and EndIndexCall skip() method to specify the number of elements to be skipped before the starting index as skip(startIndex)Call limit() method to specify the number of elements, from the stream, that should be limited as limit(endIndex – startIndex + 1)Return the Sliced Stream// Java program to get slice of a stream using// Stream skip() and limit()import java.util.*;import java.util.stream.Stream; class GFG { // Generic function to get Slice of a // Stream from startIndex to endIndex public static <T> Stream<T> getSliceOfStream(Stream<T> stream, int startIndex, int endIndex) { return stream // specify the number of elements to skip .skip(startIndex) // specify the no. of elements the stream // that should be limited .limit(endIndex - startIndex + 1); } public static void main(String[] args) { // Create a new List with values 11 - 20 List<Integer> list = new ArrayList<>(); for (int i = 11; i <= 20; i++) list.add(i); // Create stream from list Stream<Integer> intStream = list.stream(); // Print the stream System.out.println("List: " + list); // Get Slice of Stream // containing of elements from the 4th index to 8th Stream<Integer> sliceOfIntStream = getSliceOfStream(intStream, 4, 8); // Print the slice System.out.println("\nSlice of Stream:"); sliceOfIntStream.forEach(System.out::println); }}Output:List: [11, 12, 13, 14, 15, 16, 17, 18, 19, 20] Slice of Stream: 15 16 17 18 19 Algorithm: Get the Stream to be sliced.Get the From and To index to be sliced from Stream as StartIndex and EndIndexCall skip() method to specify the number of elements to be skipped before the starting index as skip(startIndex)Call limit() method to specify the number of elements, from the stream, that should be limited as limit(endIndex – startIndex + 1)Return the Sliced Stream Get the Stream to be sliced. Get the From and To index to be sliced from Stream as StartIndex and EndIndex Call skip() method to specify the number of elements to be skipped before the starting index as skip(startIndex) Call limit() method to specify the number of elements, from the stream, that should be limited as limit(endIndex – startIndex + 1) Return the Sliced Stream // Java program to get slice of a stream using// Stream skip() and limit()import java.util.*;import java.util.stream.Stream; class GFG { // Generic function to get Slice of a // Stream from startIndex to endIndex public static <T> Stream<T> getSliceOfStream(Stream<T> stream, int startIndex, int endIndex) { return stream // specify the number of elements to skip .skip(startIndex) // specify the no. of elements the stream // that should be limited .limit(endIndex - startIndex + 1); } public static void main(String[] args) { // Create a new List with values 11 - 20 List<Integer> list = new ArrayList<>(); for (int i = 11; i <= 20; i++) list.add(i); // Create stream from list Stream<Integer> intStream = list.stream(); // Print the stream System.out.println("List: " + list); // Get Slice of Stream // containing of elements from the 4th index to 8th Stream<Integer> sliceOfIntStream = getSliceOfStream(intStream, 4, 8); // Print the slice System.out.println("\nSlice of Stream:"); sliceOfIntStream.forEach(System.out::println); }} List: [11, 12, 13, 14, 15, 16, 17, 18, 19, 20] Slice of Stream: 15 16 17 18 19 Using Collectors along with skip() and limit(): In this method, the Stream is converted to List and then a function of a collector to get sub-list of desired elements is used and the sub-list id converted back to a stream using stream.collect(Collectors.collectingAndThen()).Algorithm:Get the Stream to be sliced.Get the From and To index to be sliced from Stream as StartIndex and EndIndexUsing Collectors.collectingAndThen,Convert the Stream to List using Collectors.toList()Obtain the Stream from the List as list.stream()Call skip() method to specify the number of elements to be skipped before the starting index as skip(startIndex)Call limit() method to specify the number of elements, from the stream, that should be limited as limit(endIndex – startIndex + 1)Collect the sliced list stream using stream.collect()Return the Sliced Stream// Java program to get slice of a stream using// Collection skip() and limit()import java.util.*;import java.util.stream.*; class GFG { // Generic function to get Slice of a // Stream from startIndex to endIndex public static <T> Stream<T> getSliceOfStream(Stream<T> stream, int startIndex, int endIndex) { return stream.collect(Collectors.collectingAndThen( // 1st argument // Convert the stream to list Collectors.toList(), // 2nd argument list -> list.stream() // specify the number of elements to skip .skip(startIndex) // specify the no. of elements the stream // that should be limited .limit(endIndex - startIndex + 1))); } public static void main(String[] args) { // Create a new List with values 11 - 20 List<Integer> list = new ArrayList<>(); for (int i = 11; i <= 20; i++) list.add(i); // Create stream from list Stream<Integer> intStream = list.stream(); // Print the stream System.out.println("List: " + list); // Get Slice of Stream // containing of elements from the 4th index to 8th Stream<Integer> sliceOfIntStream = getSliceOfStream(intStream, 4, 8); // Print the slice System.out.println("\nSlice of Stream:"); sliceOfIntStream.forEach(System.out::println); }}Output:List: [11, 12, 13, 14, 15, 16, 17, 18, 19, 20] Slice of Stream: 15 16 17 18 19 Algorithm: Get the Stream to be sliced.Get the From and To index to be sliced from Stream as StartIndex and EndIndexUsing Collectors.collectingAndThen,Convert the Stream to List using Collectors.toList()Obtain the Stream from the List as list.stream()Call skip() method to specify the number of elements to be skipped before the starting index as skip(startIndex)Call limit() method to specify the number of elements, from the stream, that should be limited as limit(endIndex – startIndex + 1)Collect the sliced list stream using stream.collect()Return the Sliced Stream Get the Stream to be sliced. Get the From and To index to be sliced from Stream as StartIndex and EndIndex Using Collectors.collectingAndThen, Convert the Stream to List using Collectors.toList() Obtain the Stream from the List as list.stream() Call skip() method to specify the number of elements to be skipped before the starting index as skip(startIndex) Call limit() method to specify the number of elements, from the stream, that should be limited as limit(endIndex – startIndex + 1) Collect the sliced list stream using stream.collect() Return the Sliced Stream // Java program to get slice of a stream using// Collection skip() and limit()import java.util.*;import java.util.stream.*; class GFG { // Generic function to get Slice of a // Stream from startIndex to endIndex public static <T> Stream<T> getSliceOfStream(Stream<T> stream, int startIndex, int endIndex) { return stream.collect(Collectors.collectingAndThen( // 1st argument // Convert the stream to list Collectors.toList(), // 2nd argument list -> list.stream() // specify the number of elements to skip .skip(startIndex) // specify the no. of elements the stream // that should be limited .limit(endIndex - startIndex + 1))); } public static void main(String[] args) { // Create a new List with values 11 - 20 List<Integer> list = new ArrayList<>(); for (int i = 11; i <= 20; i++) list.add(i); // Create stream from list Stream<Integer> intStream = list.stream(); // Print the stream System.out.println("List: " + list); // Get Slice of Stream // containing of elements from the 4th index to 8th Stream<Integer> sliceOfIntStream = getSliceOfStream(intStream, 4, 8); // Print the slice System.out.println("\nSlice of Stream:"); sliceOfIntStream.forEach(System.out::println); }} List: [11, 12, 13, 14, 15, 16, 17, 18, 19, 20] Slice of Stream: 15 16 17 18 19 Fetching a SubList: This method involves converting a Stream into a List. Now this list is used to fetch a required subList from it between the specified index. And finally, this subList is converted back to Stream.Algorithm:Get the Stream to be sliced.Get the From and To index to be sliced from Stream as StartIndex and EndIndexConvert the Stream to List using Collectors.toList() and then collect it using stream.collect()Fetch the subList from the collected List with the startIndex and endIndex+1 as the limit using subList(startIndex, endIndex + 1)Convert the subList back to stream using stream()Return the Sliced Stream// Java program to get slice of a stream by// fetching a sublistimport java.util.*;import java.util.stream.*; class GFG { // Generic function to get Slice of a // Stream from startIndex to endIndex public static <T> Stream<T> getSliceOfStream(Stream<T> stream, int startIndex, int endIndex) { return stream // Convert the stream to list .collect(Collectors.toList()) // Fetch the subList between the specified index .subList(startIndex, endIndex + 1) // Convert the subList to stream .stream(); } public static void main(String[] args) { // Create a new List with values 11 - 20 List<Integer> list = new ArrayList<>(); for (int i = 11; i <= 20; i++) list.add(i); // Create stream from list Stream<Integer> intStream = list.stream(); // Print the stream System.out.println("List: " + list); // Get Slice of Stream // containing of elements from the 4th index to 8th Stream<Integer> sliceOfIntStream = getSliceOfStream(intStream, 4, 8); // Print the slice System.out.println("\nSlice of Stream:"); sliceOfIntStream.forEach(System.out::println); }}Output:List: [11, 12, 13, 14, 15, 16, 17, 18, 19, 20] Slice of Stream: 15 16 17 18 19 Algorithm: Get the Stream to be sliced.Get the From and To index to be sliced from Stream as StartIndex and EndIndexConvert the Stream to List using Collectors.toList() and then collect it using stream.collect()Fetch the subList from the collected List with the startIndex and endIndex+1 as the limit using subList(startIndex, endIndex + 1)Convert the subList back to stream using stream()Return the Sliced Stream Get the Stream to be sliced. Get the From and To index to be sliced from Stream as StartIndex and EndIndex Convert the Stream to List using Collectors.toList() and then collect it using stream.collect() Fetch the subList from the collected List with the startIndex and endIndex+1 as the limit using subList(startIndex, endIndex + 1) Convert the subList back to stream using stream() Return the Sliced Stream // Java program to get slice of a stream by// fetching a sublistimport java.util.*;import java.util.stream.*; class GFG { // Generic function to get Slice of a // Stream from startIndex to endIndex public static <T> Stream<T> getSliceOfStream(Stream<T> stream, int startIndex, int endIndex) { return stream // Convert the stream to list .collect(Collectors.toList()) // Fetch the subList between the specified index .subList(startIndex, endIndex + 1) // Convert the subList to stream .stream(); } public static void main(String[] args) { // Create a new List with values 11 - 20 List<Integer> list = new ArrayList<>(); for (int i = 11; i <= 20; i++) list.add(i); // Create stream from list Stream<Integer> intStream = list.stream(); // Print the stream System.out.println("List: " + list); // Get Slice of Stream // containing of elements from the 4th index to 8th Stream<Integer> sliceOfIntStream = getSliceOfStream(intStream, 4, 8); // Print the slice System.out.println("\nSlice of Stream:"); sliceOfIntStream.forEach(System.out::println); }} List: [11, 12, 13, 14, 15, 16, 17, 18, 19, 20] Slice of Stream: 15 16 17 18 19 Java-Collections java-stream Java-Stream-programs Java Java Programs Java Java-Collections Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Object Oriented Programming (OOPs) Concept in Java How to iterate any Map in Java Interfaces in Java HashMap in Java with Examples ArrayList in Java Initializing a List in Java Java Programming Examples Convert a String to Character Array in Java Convert Double to Integer in Java Implementing a Linked List in Java using Class
[ { "code": null, "e": 28, "s": 0, "text": "\n11 Dec, 2018" }, { "code": null, "e": 251, "s": 28, "text": "A stream is a sequence of objects that supports various methods which can be pipelined to produce the desired result. Slice of a Stream means a stream of elements that exists in a specified limit, from the original stream." }, { "code": null, "e": 261, "s": 251, "text": "Examples:" }, { "code": null, "e": 410, "s": 261, "text": "Input: [11, 12, 13, 14, 15, 16, 17, 18, 19, 20]Output: [15, 16, 17, 18, 19]Explanation: The output contains a slice of the stream from index 4 to 8." }, { "code": null, "e": 535, "s": 410, "text": "Input: [1, 2, 3, 4, 5, 6, 7, 8, 9]Output: [2, 3, 4]Explanation: The output contains a slice of the stream from index 1 to 3." }, { "code": null, "e": 594, "s": 535, "text": "Below are the methods to remove nulls from a List in Java:" }, { "code": null, "e": 7071, "s": 594, "text": "Using skip() and limit(): Stream API in Java provides skip() method which is used to discard the other non-required elements from the stream. It also provides limit() function which is applied to fetch the new stream with the specified index as limit, in the encountered order.Algorithm:Get the Stream to be sliced.Get the From and To index to be sliced from Stream as StartIndex and EndIndexCall skip() method to specify the number of elements to be skipped before the starting index as skip(startIndex)Call limit() method to specify the number of elements, from the stream, that should be limited as limit(endIndex – startIndex + 1)Return the Sliced Stream// Java program to get slice of a stream using// Stream skip() and limit()import java.util.*;import java.util.stream.Stream; class GFG { // Generic function to get Slice of a // Stream from startIndex to endIndex public static <T> Stream<T> getSliceOfStream(Stream<T> stream, int startIndex, int endIndex) { return stream // specify the number of elements to skip .skip(startIndex) // specify the no. of elements the stream // that should be limited .limit(endIndex - startIndex + 1); } public static void main(String[] args) { // Create a new List with values 11 - 20 List<Integer> list = new ArrayList<>(); for (int i = 11; i <= 20; i++) list.add(i); // Create stream from list Stream<Integer> intStream = list.stream(); // Print the stream System.out.println(\"List: \" + list); // Get Slice of Stream // containing of elements from the 4th index to 8th Stream<Integer> sliceOfIntStream = getSliceOfStream(intStream, 4, 8); // Print the slice System.out.println(\"\\nSlice of Stream:\"); sliceOfIntStream.forEach(System.out::println); }}Output:List: [11, 12, 13, 14, 15, 16, 17, 18, 19, 20]\n\nSlice of Stream:\n15\n16\n17\n18\n19\nUsing Collectors along with skip() and limit(): In this method, the Stream is converted to List and then a function of a collector to get sub-list of desired elements is used and the sub-list id converted back to a stream using stream.collect(Collectors.collectingAndThen()).Algorithm:Get the Stream to be sliced.Get the From and To index to be sliced from Stream as StartIndex and EndIndexUsing Collectors.collectingAndThen,Convert the Stream to List using Collectors.toList()Obtain the Stream from the List as list.stream()Call skip() method to specify the number of elements to be skipped before the starting index as skip(startIndex)Call limit() method to specify the number of elements, from the stream, that should be limited as limit(endIndex – startIndex + 1)Collect the sliced list stream using stream.collect()Return the Sliced Stream// Java program to get slice of a stream using// Collection skip() and limit()import java.util.*;import java.util.stream.*; class GFG { // Generic function to get Slice of a // Stream from startIndex to endIndex public static <T> Stream<T> getSliceOfStream(Stream<T> stream, int startIndex, int endIndex) { return stream.collect(Collectors.collectingAndThen( // 1st argument // Convert the stream to list Collectors.toList(), // 2nd argument list -> list.stream() // specify the number of elements to skip .skip(startIndex) // specify the no. of elements the stream // that should be limited .limit(endIndex - startIndex + 1))); } public static void main(String[] args) { // Create a new List with values 11 - 20 List<Integer> list = new ArrayList<>(); for (int i = 11; i <= 20; i++) list.add(i); // Create stream from list Stream<Integer> intStream = list.stream(); // Print the stream System.out.println(\"List: \" + list); // Get Slice of Stream // containing of elements from the 4th index to 8th Stream<Integer> sliceOfIntStream = getSliceOfStream(intStream, 4, 8); // Print the slice System.out.println(\"\\nSlice of Stream:\"); sliceOfIntStream.forEach(System.out::println); }}Output:List: [11, 12, 13, 14, 15, 16, 17, 18, 19, 20]\n\nSlice of Stream:\n15\n16\n17\n18\n19\nFetching a SubList: This method involves converting a Stream into a List. Now this list is used to fetch a required subList from it between the specified index. And finally, this subList is converted back to Stream.Algorithm:Get the Stream to be sliced.Get the From and To index to be sliced from Stream as StartIndex and EndIndexConvert the Stream to List using Collectors.toList() and then collect it using stream.collect()Fetch the subList from the collected List with the startIndex and endIndex+1 as the limit using subList(startIndex, endIndex + 1)Convert the subList back to stream using stream()Return the Sliced Stream// Java program to get slice of a stream by// fetching a sublistimport java.util.*;import java.util.stream.*; class GFG { // Generic function to get Slice of a // Stream from startIndex to endIndex public static <T> Stream<T> getSliceOfStream(Stream<T> stream, int startIndex, int endIndex) { return stream // Convert the stream to list .collect(Collectors.toList()) // Fetch the subList between the specified index .subList(startIndex, endIndex + 1) // Convert the subList to stream .stream(); } public static void main(String[] args) { // Create a new List with values 11 - 20 List<Integer> list = new ArrayList<>(); for (int i = 11; i <= 20; i++) list.add(i); // Create stream from list Stream<Integer> intStream = list.stream(); // Print the stream System.out.println(\"List: \" + list); // Get Slice of Stream // containing of elements from the 4th index to 8th Stream<Integer> sliceOfIntStream = getSliceOfStream(intStream, 4, 8); // Print the slice System.out.println(\"\\nSlice of Stream:\"); sliceOfIntStream.forEach(System.out::println); }}Output:List: [11, 12, 13, 14, 15, 16, 17, 18, 19, 20]\n\nSlice of Stream:\n15\n16\n17\n18\n19\n" }, { "code": null, "e": 9111, "s": 7071, "text": "Using skip() and limit(): Stream API in Java provides skip() method which is used to discard the other non-required elements from the stream. It also provides limit() function which is applied to fetch the new stream with the specified index as limit, in the encountered order.Algorithm:Get the Stream to be sliced.Get the From and To index to be sliced from Stream as StartIndex and EndIndexCall skip() method to specify the number of elements to be skipped before the starting index as skip(startIndex)Call limit() method to specify the number of elements, from the stream, that should be limited as limit(endIndex – startIndex + 1)Return the Sliced Stream// Java program to get slice of a stream using// Stream skip() and limit()import java.util.*;import java.util.stream.Stream; class GFG { // Generic function to get Slice of a // Stream from startIndex to endIndex public static <T> Stream<T> getSliceOfStream(Stream<T> stream, int startIndex, int endIndex) { return stream // specify the number of elements to skip .skip(startIndex) // specify the no. of elements the stream // that should be limited .limit(endIndex - startIndex + 1); } public static void main(String[] args) { // Create a new List with values 11 - 20 List<Integer> list = new ArrayList<>(); for (int i = 11; i <= 20; i++) list.add(i); // Create stream from list Stream<Integer> intStream = list.stream(); // Print the stream System.out.println(\"List: \" + list); // Get Slice of Stream // containing of elements from the 4th index to 8th Stream<Integer> sliceOfIntStream = getSliceOfStream(intStream, 4, 8); // Print the slice System.out.println(\"\\nSlice of Stream:\"); sliceOfIntStream.forEach(System.out::println); }}Output:List: [11, 12, 13, 14, 15, 16, 17, 18, 19, 20]\n\nSlice of Stream:\n15\n16\n17\n18\n19\n" }, { "code": null, "e": 9122, "s": 9111, "text": "Algorithm:" }, { "code": null, "e": 9494, "s": 9122, "text": "Get the Stream to be sliced.Get the From and To index to be sliced from Stream as StartIndex and EndIndexCall skip() method to specify the number of elements to be skipped before the starting index as skip(startIndex)Call limit() method to specify the number of elements, from the stream, that should be limited as limit(endIndex – startIndex + 1)Return the Sliced Stream" }, { "code": null, "e": 9523, "s": 9494, "text": "Get the Stream to be sliced." }, { "code": null, "e": 9601, "s": 9523, "text": "Get the From and To index to be sliced from Stream as StartIndex and EndIndex" }, { "code": null, "e": 9714, "s": 9601, "text": "Call skip() method to specify the number of elements to be skipped before the starting index as skip(startIndex)" }, { "code": null, "e": 9845, "s": 9714, "text": "Call limit() method to specify the number of elements, from the stream, that should be limited as limit(endIndex – startIndex + 1)" }, { "code": null, "e": 9870, "s": 9845, "text": "Return the Sliced Stream" }, { "code": "// Java program to get slice of a stream using// Stream skip() and limit()import java.util.*;import java.util.stream.Stream; class GFG { // Generic function to get Slice of a // Stream from startIndex to endIndex public static <T> Stream<T> getSliceOfStream(Stream<T> stream, int startIndex, int endIndex) { return stream // specify the number of elements to skip .skip(startIndex) // specify the no. of elements the stream // that should be limited .limit(endIndex - startIndex + 1); } public static void main(String[] args) { // Create a new List with values 11 - 20 List<Integer> list = new ArrayList<>(); for (int i = 11; i <= 20; i++) list.add(i); // Create stream from list Stream<Integer> intStream = list.stream(); // Print the stream System.out.println(\"List: \" + list); // Get Slice of Stream // containing of elements from the 4th index to 8th Stream<Integer> sliceOfIntStream = getSliceOfStream(intStream, 4, 8); // Print the slice System.out.println(\"\\nSlice of Stream:\"); sliceOfIntStream.forEach(System.out::println); }}", "e": 11165, "s": 9870, "text": null }, { "code": null, "e": 11246, "s": 11165, "text": "List: [11, 12, 13, 14, 15, 16, 17, 18, 19, 20]\n\nSlice of Stream:\n15\n16\n17\n18\n19\n" }, { "code": null, "e": 13693, "s": 11246, "text": "Using Collectors along with skip() and limit(): In this method, the Stream is converted to List and then a function of a collector to get sub-list of desired elements is used and the sub-list id converted back to a stream using stream.collect(Collectors.collectingAndThen()).Algorithm:Get the Stream to be sliced.Get the From and To index to be sliced from Stream as StartIndex and EndIndexUsing Collectors.collectingAndThen,Convert the Stream to List using Collectors.toList()Obtain the Stream from the List as list.stream()Call skip() method to specify the number of elements to be skipped before the starting index as skip(startIndex)Call limit() method to specify the number of elements, from the stream, that should be limited as limit(endIndex – startIndex + 1)Collect the sliced list stream using stream.collect()Return the Sliced Stream// Java program to get slice of a stream using// Collection skip() and limit()import java.util.*;import java.util.stream.*; class GFG { // Generic function to get Slice of a // Stream from startIndex to endIndex public static <T> Stream<T> getSliceOfStream(Stream<T> stream, int startIndex, int endIndex) { return stream.collect(Collectors.collectingAndThen( // 1st argument // Convert the stream to list Collectors.toList(), // 2nd argument list -> list.stream() // specify the number of elements to skip .skip(startIndex) // specify the no. of elements the stream // that should be limited .limit(endIndex - startIndex + 1))); } public static void main(String[] args) { // Create a new List with values 11 - 20 List<Integer> list = new ArrayList<>(); for (int i = 11; i <= 20; i++) list.add(i); // Create stream from list Stream<Integer> intStream = list.stream(); // Print the stream System.out.println(\"List: \" + list); // Get Slice of Stream // containing of elements from the 4th index to 8th Stream<Integer> sliceOfIntStream = getSliceOfStream(intStream, 4, 8); // Print the slice System.out.println(\"\\nSlice of Stream:\"); sliceOfIntStream.forEach(System.out::println); }}Output:List: [11, 12, 13, 14, 15, 16, 17, 18, 19, 20]\n\nSlice of Stream:\n15\n16\n17\n18\n19\n" }, { "code": null, "e": 13704, "s": 13693, "text": "Algorithm:" }, { "code": null, "e": 14264, "s": 13704, "text": "Get the Stream to be sliced.Get the From and To index to be sliced from Stream as StartIndex and EndIndexUsing Collectors.collectingAndThen,Convert the Stream to List using Collectors.toList()Obtain the Stream from the List as list.stream()Call skip() method to specify the number of elements to be skipped before the starting index as skip(startIndex)Call limit() method to specify the number of elements, from the stream, that should be limited as limit(endIndex – startIndex + 1)Collect the sliced list stream using stream.collect()Return the Sliced Stream" }, { "code": null, "e": 14293, "s": 14264, "text": "Get the Stream to be sliced." }, { "code": null, "e": 14371, "s": 14293, "text": "Get the From and To index to be sliced from Stream as StartIndex and EndIndex" }, { "code": null, "e": 14407, "s": 14371, "text": "Using Collectors.collectingAndThen," }, { "code": null, "e": 14460, "s": 14407, "text": "Convert the Stream to List using Collectors.toList()" }, { "code": null, "e": 14509, "s": 14460, "text": "Obtain the Stream from the List as list.stream()" }, { "code": null, "e": 14622, "s": 14509, "text": "Call skip() method to specify the number of elements to be skipped before the starting index as skip(startIndex)" }, { "code": null, "e": 14753, "s": 14622, "text": "Call limit() method to specify the number of elements, from the stream, that should be limited as limit(endIndex – startIndex + 1)" }, { "code": null, "e": 14807, "s": 14753, "text": "Collect the sliced list stream using stream.collect()" }, { "code": null, "e": 14832, "s": 14807, "text": "Return the Sliced Stream" }, { "code": "// Java program to get slice of a stream using// Collection skip() and limit()import java.util.*;import java.util.stream.*; class GFG { // Generic function to get Slice of a // Stream from startIndex to endIndex public static <T> Stream<T> getSliceOfStream(Stream<T> stream, int startIndex, int endIndex) { return stream.collect(Collectors.collectingAndThen( // 1st argument // Convert the stream to list Collectors.toList(), // 2nd argument list -> list.stream() // specify the number of elements to skip .skip(startIndex) // specify the no. of elements the stream // that should be limited .limit(endIndex - startIndex + 1))); } public static void main(String[] args) { // Create a new List with values 11 - 20 List<Integer> list = new ArrayList<>(); for (int i = 11; i <= 20; i++) list.add(i); // Create stream from list Stream<Integer> intStream = list.stream(); // Print the stream System.out.println(\"List: \" + list); // Get Slice of Stream // containing of elements from the 4th index to 8th Stream<Integer> sliceOfIntStream = getSliceOfStream(intStream, 4, 8); // Print the slice System.out.println(\"\\nSlice of Stream:\"); sliceOfIntStream.forEach(System.out::println); }}", "e": 16348, "s": 14832, "text": null }, { "code": null, "e": 16429, "s": 16348, "text": "List: [11, 12, 13, 14, 15, 16, 17, 18, 19, 20]\n\nSlice of Stream:\n15\n16\n17\n18\n19\n" }, { "code": null, "e": 18421, "s": 16429, "text": "Fetching a SubList: This method involves converting a Stream into a List. Now this list is used to fetch a required subList from it between the specified index. And finally, this subList is converted back to Stream.Algorithm:Get the Stream to be sliced.Get the From and To index to be sliced from Stream as StartIndex and EndIndexConvert the Stream to List using Collectors.toList() and then collect it using stream.collect()Fetch the subList from the collected List with the startIndex and endIndex+1 as the limit using subList(startIndex, endIndex + 1)Convert the subList back to stream using stream()Return the Sliced Stream// Java program to get slice of a stream by// fetching a sublistimport java.util.*;import java.util.stream.*; class GFG { // Generic function to get Slice of a // Stream from startIndex to endIndex public static <T> Stream<T> getSliceOfStream(Stream<T> stream, int startIndex, int endIndex) { return stream // Convert the stream to list .collect(Collectors.toList()) // Fetch the subList between the specified index .subList(startIndex, endIndex + 1) // Convert the subList to stream .stream(); } public static void main(String[] args) { // Create a new List with values 11 - 20 List<Integer> list = new ArrayList<>(); for (int i = 11; i <= 20; i++) list.add(i); // Create stream from list Stream<Integer> intStream = list.stream(); // Print the stream System.out.println(\"List: \" + list); // Get Slice of Stream // containing of elements from the 4th index to 8th Stream<Integer> sliceOfIntStream = getSliceOfStream(intStream, 4, 8); // Print the slice System.out.println(\"\\nSlice of Stream:\"); sliceOfIntStream.forEach(System.out::println); }}Output:List: [11, 12, 13, 14, 15, 16, 17, 18, 19, 20]\n\nSlice of Stream:\n15\n16\n17\n18\n19\n" }, { "code": null, "e": 18432, "s": 18421, "text": "Algorithm:" }, { "code": null, "e": 18835, "s": 18432, "text": "Get the Stream to be sliced.Get the From and To index to be sliced from Stream as StartIndex and EndIndexConvert the Stream to List using Collectors.toList() and then collect it using stream.collect()Fetch the subList from the collected List with the startIndex and endIndex+1 as the limit using subList(startIndex, endIndex + 1)Convert the subList back to stream using stream()Return the Sliced Stream" }, { "code": null, "e": 18864, "s": 18835, "text": "Get the Stream to be sliced." }, { "code": null, "e": 18942, "s": 18864, "text": "Get the From and To index to be sliced from Stream as StartIndex and EndIndex" }, { "code": null, "e": 19038, "s": 18942, "text": "Convert the Stream to List using Collectors.toList() and then collect it using stream.collect()" }, { "code": null, "e": 19168, "s": 19038, "text": "Fetch the subList from the collected List with the startIndex and endIndex+1 as the limit using subList(startIndex, endIndex + 1)" }, { "code": null, "e": 19218, "s": 19168, "text": "Convert the subList back to stream using stream()" }, { "code": null, "e": 19243, "s": 19218, "text": "Return the Sliced Stream" }, { "code": "// Java program to get slice of a stream by// fetching a sublistimport java.util.*;import java.util.stream.*; class GFG { // Generic function to get Slice of a // Stream from startIndex to endIndex public static <T> Stream<T> getSliceOfStream(Stream<T> stream, int startIndex, int endIndex) { return stream // Convert the stream to list .collect(Collectors.toList()) // Fetch the subList between the specified index .subList(startIndex, endIndex + 1) // Convert the subList to stream .stream(); } public static void main(String[] args) { // Create a new List with values 11 - 20 List<Integer> list = new ArrayList<>(); for (int i = 11; i <= 20; i++) list.add(i); // Create stream from list Stream<Integer> intStream = list.stream(); // Print the stream System.out.println(\"List: \" + list); // Get Slice of Stream // containing of elements from the 4th index to 8th Stream<Integer> sliceOfIntStream = getSliceOfStream(intStream, 4, 8); // Print the slice System.out.println(\"\\nSlice of Stream:\"); sliceOfIntStream.forEach(System.out::println); }}", "e": 20521, "s": 19243, "text": null }, { "code": null, "e": 20602, "s": 20521, "text": "List: [11, 12, 13, 14, 15, 16, 17, 18, 19, 20]\n\nSlice of Stream:\n15\n16\n17\n18\n19\n" }, { "code": null, "e": 20619, "s": 20602, "text": "Java-Collections" }, { "code": null, "e": 20631, "s": 20619, "text": "java-stream" }, { "code": null, "e": 20652, "s": 20631, "text": "Java-Stream-programs" }, { "code": null, "e": 20657, "s": 20652, "text": "Java" }, { "code": null, "e": 20671, "s": 20657, "text": "Java Programs" }, { "code": null, "e": 20676, "s": 20671, "text": "Java" }, { "code": null, "e": 20693, "s": 20676, "text": "Java-Collections" }, { "code": null, "e": 20791, "s": 20693, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 20842, "s": 20791, "text": "Object Oriented Programming (OOPs) Concept in Java" }, { "code": null, "e": 20873, "s": 20842, "text": "How to iterate any Map in Java" }, { "code": null, "e": 20892, "s": 20873, "text": "Interfaces in Java" }, { "code": null, "e": 20922, "s": 20892, "text": "HashMap in Java with Examples" }, { "code": null, "e": 20940, "s": 20922, "text": "ArrayList in Java" }, { "code": null, "e": 20968, "s": 20940, "text": "Initializing a List in Java" }, { "code": null, "e": 20994, "s": 20968, "text": "Java Programming Examples" }, { "code": null, "e": 21038, "s": 20994, "text": "Convert a String to Character Array in Java" }, { "code": null, "e": 21072, "s": 21038, "text": "Convert Double to Integer in Java" } ]
Why Thread.stop(), Thread.suspend(), and Thread.resume() Methods are Deprecated After JDK 1.1 Version?
29 Jul, 2021 The Thread class contains constructors and methods for creating and operating on threads. Thread is a subclass of Object that implements the Runnable interface. There are many methods in Thread Class but some of them are deprecated as of JDK 1.1. In this article, we will understand the reason behind it. Deprecated methods are those that are no longer considered important and should not be utilized because they may be removed from their class. Classes evolve over time, leading their APIs to alter, resulting in deprecation. Attributes change, methods are renamed, and new ones are added. To help developers shift from the old API to the new one, deprecated classes and methods are marked @deprecated in documentation comments. Why deprecated ?? Thread.stop() is being phased out due to its inherent risk. When you stop a thread, it unlocks all the monitors it has locked. Other threads might see these objects in an inconsistent state if any of the objects previously protected by these monitors were in an inconsistent state.Threads acting on damaged objects can act erratically, whether consciously or unconsciously. ThreadDeath, unlike other uncontrolled exceptions, silently kills threads, leaving the user with no warning that the program may be corrupted. After the damage has occurred, the corruption may appear at an unpredicted moment. Also, killing a thread will create a problem while working with DBMS – JDBC in a multithreaded environment. Thread.suspend() is deprecated because it is inherently deadlock-prone. As a result, Thread.resume() must be deprecated as well. When the target thread is suspended, it holds a lock on the monitor protecting a crucial system resource, and no other thread may access it until the target thread is resumed. Deadlock occurs if the thread that would restart the target thread tries to lock this monitor before invoking resume(). Example of possible deadlock from using these deprecated methods: Java // This class contains an integer array &// Threads set the element's value for this arrayclass NumVal { private int num[] = null; boolean valueSet = false; int i = 0; NumVal() { // Creating integer array of 10 elements num = new int[10]; } // method to set the values in the array public void setVal(int n) { if (i < 9) { System.out.println("Putting value " + n + " in the NumVal Array"); num[i] = n; i++; } } // method to get the values from the array public int getVal() { if (i >= 0) { System.out.println("Giving n = " + num[i]); i--; return num[i + 1]; } else { return -1; } }}// Creating Our Thread Classclass MyThread extends Thread { // MyThread want mutually exclusive // lock on the object // referred by: NumObjToSetVal NumVal NumObjToSetVal = null; // Constructor public MyThread(String threadName, NumVal numV) { super(threadName); NumObjToSetVal = numV; } public void run() { // Only 1 thread at a time an access the object // referred by : NumObjToSetVal synchronized (NumObjToSetVal) { int n = 0; while (n < 5) { System.out.println( "THREAD NAME : " + Thread.currentThread().getName()); n++; NumObjToSetVal.setVal(n); try { // Make the thread sleep for 100 ms Thread.sleep(100); System.out.println( Thread.currentThread().getName() + "is awake now"); } catch (Exception e) { System.out.println("Exception Caught"); } // If n is 2 , we suspend this thread if (n == 2) { // suspend the thread, now this thread // will release lock on NumObjToSetVal // only when resume() method is called // on this thread, thread will go in // waiting state Thread.currentThread().suspend(); } } } }} public class Main { public static void main(String[] args) { // TODO Auto-generated method stub NumVal v = new NumVal(); // Creating thread 1 that want exclusive lock on // object referred by v MyThread thread1 = new MyThread("Thread1 ", v); // Creating thread 2 that want exclusive lock on // object referred by v // thread1 is not going to release lock on Object // referred by v until resume() method is not called // and for acquiring lock on v Object refred by v , // thread1 must have released lock on Object // referred by v, if lock is not released, thread2 // will keep on waiting for thread1 to release lock // onbject referred by v & deadlock will be formed MyThread thread2 = new MyThread("Thread2 ", v); // starting both threads thread1.start(); thread2.start(); for (int i = 500; i <= 501; i++) { System.out.println("Main Thread " + i); } }} Output: THREAD NAME : Thread1 Putting value 1 in the NumVal Array Main Thread 500 Main Thread 501 Thread1 is awake now THREAD NAME : Thread1 Putting value 2 in the NumVal Array Thread1 is awake now //Deadlock is created & hence no output after this Explanation: We created 2 threads: thread1 & thread2. Both want to acquire a lock on the NumVal object referred to by ‘v’ reference. As we start both the threads by calling the start() method, the run() method will execute whenever the thread gets CPU. Thread1 gets CPU & when the value of n is 2 in its run method, the thread is suspended. Thread1 is not going to release lock on Object referred by ‘v’ until resume() is called on it. For thread2 to acquire a lock on v Object referred by ‘v’, thread1 must have released the lock on Object referred by ‘v’. Here the lock here is not released, thread2 will keep on waiting for thread1 to release the lock on the object referred by ‘v’ & a deadlock will be formed. So, you have always call resume() on a thread (at any time) whenever you call suspend() method on the same thread. gulshankumarar231 surindertarika1234 Java-Multithreading Java Java Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 54, "s": 26, "text": "\n29 Jul, 2021" }, { "code": null, "e": 359, "s": 54, "text": "The Thread class contains constructors and methods for creating and operating on threads. Thread is a subclass of Object that implements the Runnable interface. There are many methods in Thread Class but some of them are deprecated as of JDK 1.1. In this article, we will understand the reason behind it." }, { "code": null, "e": 785, "s": 359, "text": "Deprecated methods are those that are no longer considered important and should not be utilized because they may be removed from their class. Classes evolve over time, leading their APIs to alter, resulting in deprecation. Attributes change, methods are renamed, and new ones are added. To help developers shift from the old API to the new one, deprecated classes and methods are marked @deprecated in documentation comments." }, { "code": null, "e": 803, "s": 785, "text": "Why deprecated ??" }, { "code": null, "e": 1511, "s": 803, "text": "Thread.stop() is being phased out due to its inherent risk. When you stop a thread, it unlocks all the monitors it has locked. Other threads might see these objects in an inconsistent state if any of the objects previously protected by these monitors were in an inconsistent state.Threads acting on damaged objects can act erratically, whether consciously or unconsciously. ThreadDeath, unlike other uncontrolled exceptions, silently kills threads, leaving the user with no warning that the program may be corrupted. After the damage has occurred, the corruption may appear at an unpredicted moment. Also, killing a thread will create a problem while working with DBMS – JDBC in a multithreaded environment." }, { "code": null, "e": 1936, "s": 1511, "text": "Thread.suspend() is deprecated because it is inherently deadlock-prone. As a result, Thread.resume() must be deprecated as well. When the target thread is suspended, it holds a lock on the monitor protecting a crucial system resource, and no other thread may access it until the target thread is resumed. Deadlock occurs if the thread that would restart the target thread tries to lock this monitor before invoking resume()." }, { "code": null, "e": 2002, "s": 1936, "text": "Example of possible deadlock from using these deprecated methods:" }, { "code": null, "e": 2007, "s": 2002, "text": "Java" }, { "code": "// This class contains an integer array &// Threads set the element's value for this arrayclass NumVal { private int num[] = null; boolean valueSet = false; int i = 0; NumVal() { // Creating integer array of 10 elements num = new int[10]; } // method to set the values in the array public void setVal(int n) { if (i < 9) { System.out.println(\"Putting value \" + n + \" in the NumVal Array\"); num[i] = n; i++; } } // method to get the values from the array public int getVal() { if (i >= 0) { System.out.println(\"Giving n = \" + num[i]); i--; return num[i + 1]; } else { return -1; } }}// Creating Our Thread Classclass MyThread extends Thread { // MyThread want mutually exclusive // lock on the object // referred by: NumObjToSetVal NumVal NumObjToSetVal = null; // Constructor public MyThread(String threadName, NumVal numV) { super(threadName); NumObjToSetVal = numV; } public void run() { // Only 1 thread at a time an access the object // referred by : NumObjToSetVal synchronized (NumObjToSetVal) { int n = 0; while (n < 5) { System.out.println( \"THREAD NAME : \" + Thread.currentThread().getName()); n++; NumObjToSetVal.setVal(n); try { // Make the thread sleep for 100 ms Thread.sleep(100); System.out.println( Thread.currentThread().getName() + \"is awake now\"); } catch (Exception e) { System.out.println(\"Exception Caught\"); } // If n is 2 , we suspend this thread if (n == 2) { // suspend the thread, now this thread // will release lock on NumObjToSetVal // only when resume() method is called // on this thread, thread will go in // waiting state Thread.currentThread().suspend(); } } } }} public class Main { public static void main(String[] args) { // TODO Auto-generated method stub NumVal v = new NumVal(); // Creating thread 1 that want exclusive lock on // object referred by v MyThread thread1 = new MyThread(\"Thread1 \", v); // Creating thread 2 that want exclusive lock on // object referred by v // thread1 is not going to release lock on Object // referred by v until resume() method is not called // and for acquiring lock on v Object refred by v , // thread1 must have released lock on Object // referred by v, if lock is not released, thread2 // will keep on waiting for thread1 to release lock // onbject referred by v & deadlock will be formed MyThread thread2 = new MyThread(\"Thread2 \", v); // starting both threads thread1.start(); thread2.start(); for (int i = 500; i <= 501; i++) { System.out.println(\"Main Thread \" + i); } }}", "e": 5374, "s": 2007, "text": null }, { "code": null, "e": 5384, "s": 5374, "text": " Output: " }, { "code": null, "e": 5627, "s": 5384, "text": "THREAD NAME : Thread1 \nPutting value 1 in the NumVal Array\nMain Thread 500\nMain Thread 501\nThread1 is awake now\nTHREAD NAME : Thread1 \nPutting value 2 in the NumVal Array\nThread1 is awake now\n//Deadlock is created & hence no output after this" }, { "code": null, "e": 5761, "s": 5627, "text": "Explanation: We created 2 threads: thread1 & thread2. Both want to acquire a lock on the NumVal object referred to by ‘v’ reference. " }, { "code": null, "e": 6064, "s": 5761, "text": "As we start both the threads by calling the start() method, the run() method will execute whenever the thread gets CPU. Thread1 gets CPU & when the value of n is 2 in its run method, the thread is suspended. Thread1 is not going to release lock on Object referred by ‘v’ until resume() is called on it." }, { "code": null, "e": 6343, "s": 6064, "text": "For thread2 to acquire a lock on v Object referred by ‘v’, thread1 must have released the lock on Object referred by ‘v’. Here the lock here is not released, thread2 will keep on waiting for thread1 to release the lock on the object referred by ‘v’ & a deadlock will be formed." }, { "code": null, "e": 6458, "s": 6343, "text": "So, you have always call resume() on a thread (at any time) whenever you call suspend() method on the same thread." }, { "code": null, "e": 6478, "s": 6460, "text": "gulshankumarar231" }, { "code": null, "e": 6497, "s": 6478, "text": "surindertarika1234" }, { "code": null, "e": 6517, "s": 6497, "text": "Java-Multithreading" }, { "code": null, "e": 6522, "s": 6517, "text": "Java" }, { "code": null, "e": 6527, "s": 6522, "text": "Java" } ]
Stack Unwinding in C++
25 Nov, 2021 Stack Unwinding is the process of removing function entries from function call stack at run time. The local objects are destroyed in reverse order in which they were constructed. Stack Unwinding is generally related to Exception Handling. In C++, when an exception occurs, the function call stack is linearly searched for the exception handler, and all the entries before the function with exception handler are removed from the function call stack. So, exception handling involves Stack Unwinding if an exception is not handled in the same function (where it is thrown). Basically, Stack unwinding is a process of calling the destructors (whenever an exception is thrown) for all the automatic objects constructed at run time. For example, the output of the following program is: CPP // CPP Program to demonstrate Stack Unwinding#include <iostream>using namespace std; // A sample function f1() that throws an int exceptionvoid f1() throw(int){ cout << "\n f1() Start "; throw 100; cout << "\n f1() End ";} // Another sample function f2() that calls f1()void f2() throw(int){ cout << "\n f2() Start "; f1(); cout << "\n f2() End ";} // Another sample function f3() that calls f2() and handles// exception thrown by f1()void f3(){ cout << "\n f3() Start "; try { f2(); } catch (int i) { cout << "\n Caught Exception: " << i; } cout << "\n f3() End";} // Driver Codeint main(){ f3(); getchar(); return 0;} f3() Start f2() Start f1() Start Caught Exception: 100 f3() End Explanation: When f1() throws exception, its entry is removed from the function call stack, because f1() doesn’t contain exception handler for the thrown exception, then next entry in call stack is looked for exception handler. The next entry is f2(). Since f2() also doesn’t have a handler, its entry is also removed from the function call stack. The next entry in the function call stack is f3(). Since f3() contains an exception handler, the catch block inside f3() is executed, and finally, the code after the catch block is executed. Note that the following lines inside f1() and f2() are not executed at all. cout<<"\n f1() End "; // inside f1() cout<<"\n f2() End "; // inside f2() If there were some local class objects inside f1() and f2(), destructors for those local objects would have been called in the Stack Unwinding process. Note: Stack Unwinding also happens in Java when exception is not handled in same function. Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above. anshikajain26 C++-Exception Handling C++ CPP Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 54, "s": 26, "text": "\n25 Nov, 2021" }, { "code": null, "e": 234, "s": 54, "text": "Stack Unwinding is the process of removing function entries from function call stack at run time. The local objects are destroyed in reverse order in which they were constructed. " }, { "code": null, "e": 784, "s": 234, "text": "Stack Unwinding is generally related to Exception Handling. In C++, when an exception occurs, the function call stack is linearly searched for the exception handler, and all the entries before the function with exception handler are removed from the function call stack. So, exception handling involves Stack Unwinding if an exception is not handled in the same function (where it is thrown). Basically, Stack unwinding is a process of calling the destructors (whenever an exception is thrown) for all the automatic objects constructed at run time. " }, { "code": null, "e": 838, "s": 784, "text": "For example, the output of the following program is: " }, { "code": null, "e": 842, "s": 838, "text": "CPP" }, { "code": "// CPP Program to demonstrate Stack Unwinding#include <iostream>using namespace std; // A sample function f1() that throws an int exceptionvoid f1() throw(int){ cout << \"\\n f1() Start \"; throw 100; cout << \"\\n f1() End \";} // Another sample function f2() that calls f1()void f2() throw(int){ cout << \"\\n f2() Start \"; f1(); cout << \"\\n f2() End \";} // Another sample function f3() that calls f2() and handles// exception thrown by f1()void f3(){ cout << \"\\n f3() Start \"; try { f2(); } catch (int i) { cout << \"\\n Caught Exception: \" << i; } cout << \"\\n f3() End\";} // Driver Codeint main(){ f3(); getchar(); return 0;}", "e": 1527, "s": 842, "text": null }, { "code": null, "e": 1599, "s": 1527, "text": " f3() Start \n f2() Start \n f1() Start \n Caught Exception: 100\n f3() End" }, { "code": null, "e": 1612, "s": 1599, "text": "Explanation:" }, { "code": null, "e": 1827, "s": 1612, "text": "When f1() throws exception, its entry is removed from the function call stack, because f1() doesn’t contain exception handler for the thrown exception, then next entry in call stack is looked for exception handler." }, { "code": null, "e": 1947, "s": 1827, "text": "The next entry is f2(). Since f2() also doesn’t have a handler, its entry is also removed from the function call stack." }, { "code": null, "e": 2138, "s": 1947, "text": "The next entry in the function call stack is f3(). Since f3() contains an exception handler, the catch block inside f3() is executed, and finally, the code after the catch block is executed." }, { "code": null, "e": 2216, "s": 2138, "text": " Note that the following lines inside f1() and f2() are not executed at all. " }, { "code": null, "e": 2295, "s": 2216, "text": " cout<<\"\\n f1() End \"; // inside f1()\n\n cout<<\"\\n f2() End \"; // inside f2()" }, { "code": null, "e": 2447, "s": 2295, "text": "If there were some local class objects inside f1() and f2(), destructors for those local objects would have been called in the Stack Unwinding process." }, { "code": null, "e": 2539, "s": 2447, "text": "Note: Stack Unwinding also happens in Java when exception is not handled in same function. " }, { "code": null, "e": 2664, "s": 2539, "text": "Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above." }, { "code": null, "e": 2678, "s": 2664, "text": "anshikajain26" }, { "code": null, "e": 2701, "s": 2678, "text": "C++-Exception Handling" }, { "code": null, "e": 2705, "s": 2701, "text": "C++" }, { "code": null, "e": 2709, "s": 2705, "text": "CPP" } ]
Apache HttpClient - Multiple Threads
A multi-threaded program contains two or more parts that can run concurrently and each part can handle a different task at the same time making optimal use of the available resources. You can execute requests from multiple threads by writing a multithreaded HttpClient program. If you want to execute multiple client requests from threads consecutively, you need to create a ClientConnectionPoolManager. It maintains a pool of HttpClientConnections and serves multiple requests from threads. The connections manager pools the connections based on the route. If the manager has connections for a particular route, then it serves new requests in those routes by leasing an existing connection from the pool, instead of creating a new one. Follow the steps to execute requests from multiple threads − Create the Client Connection Pool Manager by instantiating the PoolingHttpClientConnectionManager class. PoolingHttpClientConnectionManager connManager = new PoolingHttpClientConnectionManager(); Set the maximum number of connections in the pool using the setMaxTotal() method. //Set the maximum number of connections in the pool connManager.setMaxTotal(100); Create a ClientBuilder Object by setting the connection manager using the setConnectionManager() method as shown below − HttpClientBuilder clientbuilder = HttpClients.custom().setConnectionManager(connManager); Instantiate the HttpGet class by passing the desired URI to its constructor as a parameter. HttpGet httpget1 = new HttpGet("URI1"); HttpGet httpget2 = new HttpGet("URI2"); . . . . . . . . . . . . Make sure that you have created a class, made it a thread (either by extending the thread class or, by implementing the Runnable interface) and implemented the run method. public class ClientMultiThreaded extends Thread { public void run() { //Run method implementation . . . . . . . . . . } } Create thread objects by instantiating the Thread class (ClientMultiThreaded) created above. Pass a HttpClient object, respective HttpGet object and, an integer representing the ID to these threads. ClientMultiThreaded thread1 = new ClientMultiThreaded(httpclient,httpget1, 1); ClientMultiThreaded thread2 = new ClientMultiThreaded(httpclient,httpget2, 2); . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . Start all the threads using start() method and join them using the join method(). thread1.start(); thread2.start(); . . . . . . . . thread1.join(); thread2.join(); . . . . . . . . . . . . Within the run method, execute the request, retrieve the response and print the results. Following example demonstrates the execution of HTTP requests simultaneously from multiple threads. In this example, we are trying to execute various requests from various threads and trying to print the status, and the number of bytes read by each client. import org.apache.http.HttpEntity; import org.apache.http.client.methods.CloseableHttpResponse; import org.apache.http.client.methods.HttpGet; import org.apache.http.impl.client.CloseableHttpClient; import org.apache.http.impl.client.HttpClientBuilder; import org.apache.http.impl.client.HttpClients; import org.apache.http.impl.conn.PoolingHttpClientConnectionManager; import org.apache.http.util.EntityUtils; public class ClientMultiThreaded extends Thread { CloseableHttpClient httpClient; HttpGet httpget; int id; public ClientMultiThreaded(CloseableHttpClient httpClient, HttpGet httpget, int id) { this.httpClient = httpClient; this.httpget = httpget; this.id = id; } @Override public void run() { try{ //Executing the request CloseableHttpResponse httpresponse = httpClient.execute(httpget); //Displaying the status of the request. System.out.println("status of thread "+id+":"+httpresponse.getStatusLine()); //Retrieving the HttpEntity and displaying the no.of bytes read HttpEntity entity = httpresponse.getEntity(); if (entity != null) { System.out.println("Bytes read by thread thread "+id+": "+EntityUtils.toByteArray(entity).length); } }catch(Exception e) { System.out.println(e.getMessage()); } } public static void main(String[] args) throws Exception { //Creating the Client Connection Pool Manager by instantiating the PoolingHttpClientConnectionManager class. PoolingHttpClientConnectionManager connManager = new PoolingHttpClientConnectionManager(); //Set the maximum number of connections in the pool connManager.setMaxTotal(100); //Create a ClientBuilder Object by setting the connection manager HttpClientBuilder clientbuilder = HttpClients.custom().setConnectionManager(connManager); //Build the CloseableHttpClient object using the build() method. CloseableHttpClient httpclient = clientbuilder.build(); //Creating the HttpGet requests HttpGet httpget1 = new HttpGet("http://www.tutorialspoint.com/"); HttpGet httpget2 = new HttpGet("http://www.google.com/"); HttpGet httpget3 = new HttpGet("https://www.qries.com/"); HttpGet httpget4 = new HttpGet("https://in.yahoo.com/"); //Creating the Thread objects ClientMultiThreaded thread1 = new ClientMultiThreaded(httpclient,httpget1, 1); ClientMultiThreaded thread2 = new ClientMultiThreaded(httpclient,httpget2, 2); ClientMultiThreaded thread3 = new ClientMultiThreaded(httpclient,httpget3, 3); ClientMultiThreaded thread4 = new ClientMultiThreaded(httpclient,httpget4, 4); //Starting all the threads thread1.start(); thread2.start(); thread3.start(); thread4.start(); //Joining all the threads thread1.join(); thread2.join(); thread3.join(); thread4.join(); } } On executing, the above program generates the following output − status of thread 1: HTTP/1.1 200 OK Bytes read by thread thread 1: 36907 status of thread 2: HTTP/1.1 200 OK Bytes read by thread thread 2: 13725 status of thread 3: HTTP/1.1 200 OK Bytes read by thread thread 3: 17319 status of thread 4: HTTP/1.1 200 OK Bytes read by thread thread 4: 127018 46 Lectures 3.5 hours Arnab Chakraborty 23 Lectures 1.5 hours Mukund Kumar Mishra 16 Lectures 1 hours Nilay Mehta 52 Lectures 1.5 hours Bigdata Engineer 14 Lectures 1 hours Bigdata Engineer 23 Lectures 1 hours Bigdata Engineer Print Add Notes Bookmark this page
[ { "code": null, "e": 2011, "s": 1827, "text": "A multi-threaded program contains two or more parts that can run concurrently and each part can handle a different task at the same time making optimal use of the available resources." }, { "code": null, "e": 2106, "s": 2011, "text": "You can execute requests from multiple threads by writing a multithreaded HttpClient program.\n" }, { "code": null, "e": 2320, "s": 2106, "text": "If you want to execute multiple client requests from threads consecutively, you need to create a ClientConnectionPoolManager. It maintains a pool of HttpClientConnections and serves multiple requests from threads." }, { "code": null, "e": 2565, "s": 2320, "text": "The connections manager pools the connections based on the route. If the manager has connections for a particular route, then it serves new requests in those routes by leasing an existing connection from the pool, instead of creating a new one." }, { "code": null, "e": 2626, "s": 2565, "text": "Follow the steps to execute requests from multiple threads −" }, { "code": null, "e": 2731, "s": 2626, "text": "Create the Client Connection Pool Manager by instantiating the PoolingHttpClientConnectionManager class." }, { "code": null, "e": 2827, "s": 2731, "text": "PoolingHttpClientConnectionManager connManager = new\n PoolingHttpClientConnectionManager(); \n" }, { "code": null, "e": 2909, "s": 2827, "text": "Set the maximum number of connections in the pool using the setMaxTotal() method." }, { "code": null, "e": 2993, "s": 2909, "text": "//Set the maximum number of connections in the pool\nconnManager.setMaxTotal(100); \n" }, { "code": null, "e": 3114, "s": 2993, "text": "Create a ClientBuilder Object by setting the connection manager using the setConnectionManager() method as shown below −" }, { "code": null, "e": 3205, "s": 3114, "text": "HttpClientBuilder clientbuilder =\nHttpClients.custom().setConnectionManager(connManager);\n" }, { "code": null, "e": 3298, "s": 3205, "text": "Instantiate the HttpGet class by passing the desired URI to its constructor as a parameter.\n" }, { "code": null, "e": 3404, "s": 3298, "text": "HttpGet httpget1 = new HttpGet(\"URI1\");\nHttpGet httpget2 = new HttpGet(\"URI2\");\n. . . . . . . . . . . . \n" }, { "code": null, "e": 3576, "s": 3404, "text": "Make sure that you have created a class, made it a thread (either by extending the thread class or, by implementing the Runnable interface) and implemented the run method." }, { "code": null, "e": 3711, "s": 3576, "text": "public class ClientMultiThreaded extends Thread {\n public void run() {\n //Run method implementation . . . . . . . . . .\n }\n}\n" }, { "code": null, "e": 3804, "s": 3711, "text": "Create thread objects by instantiating the Thread class (ClientMultiThreaded) created above." }, { "code": null, "e": 3910, "s": 3804, "text": "Pass a HttpClient object, respective HttpGet object and, an integer representing the ID to\nthese threads." }, { "code": null, "e": 4308, "s": 3910, "text": "ClientMultiThreaded thread1 = new ClientMultiThreaded(httpclient,httpget1, 1);\nClientMultiThreaded thread2 = new ClientMultiThreaded(httpclient,httpget2, 2);\n. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .\n. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .. . . .\n. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .\n" }, { "code": null, "e": 4390, "s": 4308, "text": "Start all the threads using start() method and join them using the join method()." }, { "code": null, "e": 4497, "s": 4390, "text": "thread1.start();\nthread2.start();\n. . . . . . . .\nthread1.join();\nthread2.join();\n. . . . . . . . . . . .\n" }, { "code": null, "e": 4586, "s": 4497, "text": "Within the run method, execute the request, retrieve the response and print the results." }, { "code": null, "e": 4843, "s": 4586, "text": "Following example demonstrates the execution of HTTP requests simultaneously from multiple threads. In this example, we are trying to execute various requests from various threads and trying to print the status, and the number of bytes read by each client." }, { "code": null, "e": 7844, "s": 4843, "text": "import org.apache.http.HttpEntity;\nimport org.apache.http.client.methods.CloseableHttpResponse;\nimport org.apache.http.client.methods.HttpGet;\nimport org.apache.http.impl.client.CloseableHttpClient;\nimport org.apache.http.impl.client.HttpClientBuilder;\nimport org.apache.http.impl.client.HttpClients;\nimport org.apache.http.impl.conn.PoolingHttpClientConnectionManager;\nimport org.apache.http.util.EntityUtils;\n\npublic class ClientMultiThreaded extends Thread {\n CloseableHttpClient httpClient;\n HttpGet httpget;\n int id;\n \n public ClientMultiThreaded(CloseableHttpClient httpClient, HttpGet httpget,\n int id) {\n this.httpClient = httpClient;\n this.httpget = httpget;\n this.id = id;\n }\n @Override\n public void run() {\n try{\n //Executing the request\n CloseableHttpResponse httpresponse = httpClient.execute(httpget);\n\n //Displaying the status of the request.\n System.out.println(\"status of thread \"+id+\":\"+httpresponse.getStatusLine());\n\n //Retrieving the HttpEntity and displaying the no.of bytes read\n HttpEntity entity = httpresponse.getEntity();\n if (entity != null) {\n System.out.println(\"Bytes read by thread thread \"+id+\":\n \"+EntityUtils.toByteArray(entity).length);\n }\n }catch(Exception e) {\n System.out.println(e.getMessage());\n }\n }\n \n public static void main(String[] args) throws Exception {\n\n //Creating the Client Connection Pool Manager by instantiating the PoolingHttpClientConnectionManager class.\n PoolingHttpClientConnectionManager connManager = new PoolingHttpClientConnectionManager();\n\n //Set the maximum number of connections in the pool\n connManager.setMaxTotal(100);\n\n //Create a ClientBuilder Object by setting the connection manager\n HttpClientBuilder clientbuilder = HttpClients.custom().setConnectionManager(connManager);\n \n //Build the CloseableHttpClient object using the build() method.\n CloseableHttpClient httpclient = clientbuilder.build();\n\n //Creating the HttpGet requests\n HttpGet httpget1 = new HttpGet(\"http://www.tutorialspoint.com/\");\n HttpGet httpget2 = new HttpGet(\"http://www.google.com/\");\n HttpGet httpget3 = new HttpGet(\"https://www.qries.com/\");\n HttpGet httpget4 = new HttpGet(\"https://in.yahoo.com/\");\n \n //Creating the Thread objects\n ClientMultiThreaded thread1 = new ClientMultiThreaded(httpclient,httpget1, 1);\n ClientMultiThreaded thread2 = new ClientMultiThreaded(httpclient,httpget2, 2);\n ClientMultiThreaded thread3 = new ClientMultiThreaded(httpclient,httpget3, 3);\n ClientMultiThreaded thread4 = new ClientMultiThreaded(httpclient,httpget4, 4);\n\n //Starting all the threads\n thread1.start();\n thread2.start();\n thread3.start();\n thread4.start();\n\n //Joining all the threads\n thread1.join();\n thread2.join();\n thread3.join();\n thread4.join();\n }\n}" }, { "code": null, "e": 7909, "s": 7844, "text": "On executing, the above program generates the following output −" }, { "code": null, "e": 8203, "s": 7909, "text": "status of thread 1: HTTP/1.1 200 OK\nBytes read by thread thread 1: 36907\nstatus of thread 2: HTTP/1.1 200 OK\nBytes read by thread thread 2: 13725\nstatus of thread 3: HTTP/1.1 200 OK\nBytes read by thread thread 3: 17319\nstatus of thread 4: HTTP/1.1 200 OK\nBytes read by thread thread 4: 127018\n" }, { "code": null, "e": 8238, "s": 8203, "text": "\n 46 Lectures \n 3.5 hours \n" }, { "code": null, "e": 8257, "s": 8238, "text": " Arnab Chakraborty" }, { "code": null, "e": 8292, "s": 8257, "text": "\n 23 Lectures \n 1.5 hours \n" }, { "code": null, "e": 8313, "s": 8292, "text": " Mukund Kumar Mishra" }, { "code": null, "e": 8346, "s": 8313, "text": "\n 16 Lectures \n 1 hours \n" }, { "code": null, "e": 8359, "s": 8346, "text": " Nilay Mehta" }, { "code": null, "e": 8394, "s": 8359, "text": "\n 52 Lectures \n 1.5 hours \n" }, { "code": null, "e": 8412, "s": 8394, "text": " Bigdata Engineer" }, { "code": null, "e": 8445, "s": 8412, "text": "\n 14 Lectures \n 1 hours \n" }, { "code": null, "e": 8463, "s": 8445, "text": " Bigdata Engineer" }, { "code": null, "e": 8496, "s": 8463, "text": "\n 23 Lectures \n 1 hours \n" }, { "code": null, "e": 8514, "s": 8496, "text": " Bigdata Engineer" }, { "code": null, "e": 8521, "s": 8514, "text": " Print" }, { "code": null, "e": 8532, "s": 8521, "text": " Add Notes" } ]
Anomaly Detection in Images. Classify and Individuate anomalies with... | by Marco Cerliani | Towards Data Science
In Machine Learning is normal to deal with Anomaly Detection tasks. Data Scientists frequently are engaged in problems where they have to show, explain and predict anomalies. I also made a post about Anomaly Detection with Time Series, where I studied internal system behaviors and I provided anomaly forecasts in the future. In this post, I try to solve a different challenge. I change the domain of interest: swapping from Time Series to Images. Given an image, we want to achieve a dual purpose: predict the presence of anomalies and individuate them, giving a colorful representation of the results. I got the data from the internet: The crack dataset contains images of wall cracks. Half of the images show new and uncorrupted pieces of the wall; the remaining part shows cracks of various dimensions and types. As you can see from the samples below, our data are present different types of wall cracks, some of them aren’t so easy to identify also for me. We want to build a machine learning model which is able to classify wall images and detect at the same time where anomalies are located. To achieve this dual purpose, the most efficient method consists in building a strong classifier. It will be able to read and classify our input images as ‘damaged’ or ‘not damaged’. At the last step, we’ll make use of knowledge learned by our classifier to extract useful information which will help us to detect also where are anomalies. But let’s proceed with order and start to assemble our Neural Net... For this kind of task, I’ve chosen a silver bullet of computer vision, the loyalty VGG16. We load and remake the train of VGG16. This is very easy to do in Keras with only a few lines of code. vgg_conv = vgg16.VGG16(weights='imagenet', include_top=False, input_shape = (224, 224, 3))for layer in vgg_conv.layers[:-8]: layer.trainable = False In detail, we imported the VGG architecture allowing training of the last two convolutional blocks. This will permit our model to specialize in our classification task. For this purpose, we’ve also excluded the top layers of the original model replacing them with another structure. x = vgg_conv.outputx = GlobalAveragePooling2D()(x)x = Dense(2, activation="softmax")(x)model = Model(vgg_conv.input, x)model.compile(loss = "categorical_crossentropy", optimizer = optimizers.SGD(lr=0.0001, momentum=0.9), metrics=["accuracy"]) At the classification stage, the GlobalAveragePooling layer reduces the size of the preceding layer by taking the average of each feature map. This choice, plus the omitted usage of intermediate dense layer, permits avoiding overfitting. The training is simple and easy if you have at disposal a GPU. COLAB or Kaggle gave us the weapons we needed to speed up this process. We also used a simple data generator provided by Keras for image augmentation. In the end, we were able to achieve an overall accuracy of 0.90, not bad! Now, with our model trained, we play with it in order to extract all the useful information which permits us to show cracks in our wall images. We try to make this process easy and nice to see at the end with heat map representation. The useful information we need is located at the top. Particularly we access to: Convolutional layers: upper we go in our VGG structure and more important features the network has created. We’ve selected the last convolutional layer (‘block5_conv3’) and cut here our classification model. We’ve recreated an intermediate model which, given the original image as input, output the related activation map. Thinking about dimensionality, our intermediate model augments the channels (new features) and reduces dimensions (height and width) of our initial image. Final Dense layer: for each class of interest we need these weights, which are responsible to provide the final results of the classification. With these compressed objects in our hands, we have all the knowledge to localize cracks. We want to ‘paint’ them on an original image in order to make the results easy to understand and nice to see. ‘Unzip’ this information is easy in python: we only have to make bilinear upsampling to resize each activation map and compute a dot product. This magic is accessible executing a simple function: def plot_activation(img): pred = model.predict(img[np.newaxis,:,:,:]) pred_class = np.argmax(pred) weights = model.layers[-1].get_weights()[0] class_weights = weights[:, pred_class] intermediate = Model(model.input, model.get_layer("block5_conv3").output) conv_output = intermediate.predict(img[np.newaxis,:,:,:]) conv_output = np.squeeze(conv_output) h = int(img.shape[0]/conv_output.shape[0]) w = int(img.shape[1]/conv_output.shape[1]) act_maps = sp.ndimage.zoom(conv_output, (h, w, 1), order=1) out = np.dot(act_maps.reshape((img.shape[0]*img.shape[1],512)), class_weights).reshape(img.shape[0],img.shape[1]) plt.imshow(img.astype('float32').reshape(img.shape[0], img.shape[1],3)) plt.imshow(out, cmap='jet', alpha=0.35) plt.title('Crack' if pred_class == 1 else 'No Crack') I display the results in the image below, where I’ve plotted the crack heat maps on test images classified as crack. We can see that the heat map is able to generalize well and point pieces of wall containing cracks. In this post, we produce a machine learning solution for anomaly identifications and localizations. All these functionalities are accessible by implementing a single classification model. During training our Neural Network acquires all the relevant information which permits it to operate classification. After this phase, we’ve assembled the final pieces which have told us where the crack is in the image, without additional work! CHECK MY GITHUB REPO Keep in touch: Linkedin
[ { "code": null, "e": 347, "s": 172, "text": "In Machine Learning is normal to deal with Anomaly Detection tasks. Data Scientists frequently are engaged in problems where they have to show, explain and predict anomalies." }, { "code": null, "e": 498, "s": 347, "text": "I also made a post about Anomaly Detection with Time Series, where I studied internal system behaviors and I provided anomaly forecasts in the future." }, { "code": null, "e": 776, "s": 498, "text": "In this post, I try to solve a different challenge. I change the domain of interest: swapping from Time Series to Images. Given an image, we want to achieve a dual purpose: predict the presence of anomalies and individuate them, giving a colorful representation of the results." }, { "code": null, "e": 989, "s": 776, "text": "I got the data from the internet: The crack dataset contains images of wall cracks. Half of the images show new and uncorrupted pieces of the wall; the remaining part shows cracks of various dimensions and types." }, { "code": null, "e": 1134, "s": 989, "text": "As you can see from the samples below, our data are present different types of wall cracks, some of them aren’t so easy to identify also for me." }, { "code": null, "e": 1611, "s": 1134, "text": "We want to build a machine learning model which is able to classify wall images and detect at the same time where anomalies are located. To achieve this dual purpose, the most efficient method consists in building a strong classifier. It will be able to read and classify our input images as ‘damaged’ or ‘not damaged’. At the last step, we’ll make use of knowledge learned by our classifier to extract useful information which will help us to detect also where are anomalies." }, { "code": null, "e": 1680, "s": 1611, "text": "But let’s proceed with order and start to assemble our Neural Net..." }, { "code": null, "e": 1873, "s": 1680, "text": "For this kind of task, I’ve chosen a silver bullet of computer vision, the loyalty VGG16. We load and remake the train of VGG16. This is very easy to do in Keras with only a few lines of code." }, { "code": null, "e": 2025, "s": 1873, "text": "vgg_conv = vgg16.VGG16(weights='imagenet', include_top=False, input_shape = (224, 224, 3))for layer in vgg_conv.layers[:-8]: layer.trainable = False" }, { "code": null, "e": 2308, "s": 2025, "text": "In detail, we imported the VGG architecture allowing training of the last two convolutional blocks. This will permit our model to specialize in our classification task. For this purpose, we’ve also excluded the top layers of the original model replacing them with another structure." }, { "code": null, "e": 2551, "s": 2308, "text": "x = vgg_conv.outputx = GlobalAveragePooling2D()(x)x = Dense(2, activation=\"softmax\")(x)model = Model(vgg_conv.input, x)model.compile(loss = \"categorical_crossentropy\", optimizer = optimizers.SGD(lr=0.0001, momentum=0.9), metrics=[\"accuracy\"])" }, { "code": null, "e": 2789, "s": 2551, "text": "At the classification stage, the GlobalAveragePooling layer reduces the size of the preceding layer by taking the average of each feature map. This choice, plus the omitted usage of intermediate dense layer, permits avoiding overfitting." }, { "code": null, "e": 3003, "s": 2789, "text": "The training is simple and easy if you have at disposal a GPU. COLAB or Kaggle gave us the weapons we needed to speed up this process. We also used a simple data generator provided by Keras for image augmentation." }, { "code": null, "e": 3077, "s": 3003, "text": "In the end, we were able to achieve an overall accuracy of 0.90, not bad!" }, { "code": null, "e": 3311, "s": 3077, "text": "Now, with our model trained, we play with it in order to extract all the useful information which permits us to show cracks in our wall images. We try to make this process easy and nice to see at the end with heat map representation." }, { "code": null, "e": 3392, "s": 3311, "text": "The useful information we need is located at the top. Particularly we access to:" }, { "code": null, "e": 3870, "s": 3392, "text": "Convolutional layers: upper we go in our VGG structure and more important features the network has created. We’ve selected the last convolutional layer (‘block5_conv3’) and cut here our classification model. We’ve recreated an intermediate model which, given the original image as input, output the related activation map. Thinking about dimensionality, our intermediate model augments the channels (new features) and reduces dimensions (height and width) of our initial image." }, { "code": null, "e": 4013, "s": 3870, "text": "Final Dense layer: for each class of interest we need these weights, which are responsible to provide the final results of the classification." }, { "code": null, "e": 4355, "s": 4013, "text": "With these compressed objects in our hands, we have all the knowledge to localize cracks. We want to ‘paint’ them on an original image in order to make the results easy to understand and nice to see. ‘Unzip’ this information is easy in python: we only have to make bilinear upsampling to resize each activation map and compute a dot product." }, { "code": null, "e": 4409, "s": 4355, "text": "This magic is accessible executing a simple function:" }, { "code": null, "e": 5284, "s": 4409, "text": "def plot_activation(img): pred = model.predict(img[np.newaxis,:,:,:]) pred_class = np.argmax(pred) weights = model.layers[-1].get_weights()[0] class_weights = weights[:, pred_class] intermediate = Model(model.input, model.get_layer(\"block5_conv3\").output) conv_output = intermediate.predict(img[np.newaxis,:,:,:]) conv_output = np.squeeze(conv_output) h = int(img.shape[0]/conv_output.shape[0]) w = int(img.shape[1]/conv_output.shape[1]) act_maps = sp.ndimage.zoom(conv_output, (h, w, 1), order=1) out = np.dot(act_maps.reshape((img.shape[0]*img.shape[1],512)), class_weights).reshape(img.shape[0],img.shape[1]) plt.imshow(img.astype('float32').reshape(img.shape[0], img.shape[1],3)) plt.imshow(out, cmap='jet', alpha=0.35) plt.title('Crack' if pred_class == 1 else 'No Crack')" }, { "code": null, "e": 5501, "s": 5284, "text": "I display the results in the image below, where I’ve plotted the crack heat maps on test images classified as crack. We can see that the heat map is able to generalize well and point pieces of wall containing cracks." }, { "code": null, "e": 5934, "s": 5501, "text": "In this post, we produce a machine learning solution for anomaly identifications and localizations. All these functionalities are accessible by implementing a single classification model. During training our Neural Network acquires all the relevant information which permits it to operate classification. After this phase, we’ve assembled the final pieces which have told us where the crack is in the image, without additional work!" }, { "code": null, "e": 5955, "s": 5934, "text": "CHECK MY GITHUB REPO" } ]
C++ Program to Implement Dequeue
Dequeue or Double Ended Queue is a generalized version of Queue data structure that allows insert and delete at both ends. Some basic operations of dequeue are − insert_at_beg(): inserts an item at the front of Dequeue. insert_at_end(): inserts an item at the rear of Dequeue. delete_fr_beg(): Deletes an item from front of Dequeue. delete_fr_rear(): Deletes an item from rear of Dequeue. Following is a C++ program to implement Dequeue Begin Declare a class dequeue to declare front f and rear r and following functions: function insert_at_beg(int) to insert item at front: If queue is not completely filled up, insert element at the front and update front and rear Otherwise print overflow. function insert_at_end(int) to insert item at rear: If queue is not completely filled up, insert element at the rear and update front and rear Otherwise print overflow. function delete_fr_beg() to delete item from front: If queue is empty, print underflow otherwise delete the front element and update front. function delete_fr_end() to delete item from end: If queue is empty, print underflow otherwise delete the rear element and update rear. End #include<iostream> using namespace std; #define SIZE 10 class dequeue { int a[20],f,r; public: dequeue(); void insert_at_beg(int); void insert_at_end(int); void delete_fr_front(); void delete_fr_rear(); void show(); }; dequeue::dequeue() { f=-1; r=-1; } void dequeue::insert_at_end(int i) { if(r>=SIZE-1) { cout<<"\n insertion is not possible, overflow!!!!"; } else { if(f==-1) { f++; r++; } else { r=r+1; } a[r]=i; cout<<"\nInserted item is"<<a[r]; } } void dequeue::insert_at_beg(int i) { if(f==-1) { f=0; a[++r]=i; cout<<"\n inserted element is:"<<i; } else if(f!=0) { a[--f]=i; cout<<"\n inserted element is:"<<i; } else { cout<<"\n insertion is not possible, overflow!!!"; } } void dequeue::delete_fr_front() { if(f==-1) { cout<<"deletion is not possible::dequeue is empty"; return; } else { cout<<"the deleted element is:"<<a[f]; if(f==r) { f=r=-1; return; } else f=f+1; } } void dequeue::delete_fr_rear() { if(f==-1) { cout<<"deletion is not possible::dequeue is empty"; return; } else { cout<<"the deleted element is:"<<a[r]; if(f==r) { f=r=-1; } else r=r-1; } } void dequeue::show() { if(f==-1) { cout<<"Dequeue is empty"; } else { for(int i=f;i<=r;i++) { cout<<a[i]<<" "; } } } int main() { int c,i; dequeue d; Do//perform switch opeartion { cout<<"\n 1.insert at beginning"; cout<<"\n 2.insert at end"; cout<<"\n 3.show"; cout<<"\n 4.deletion from front"; cout<<"\n 5.deletion from rear"; cout<<"\n 6.exit"; cout<<"\n enter your choice:"; cin>>c; switch(c) { case 1: cout<<"enter the element to be inserted"; cin>>i; d.insert_at_beg(i); break; case 2: cout<<"enter the element to be inserted"; cin>>i; d.insert_at_end(i); break; case 3: d.show(); break; case 4: d.delete_fr_front(); break; case 5: d.delete_fr_rear(); break; case 6: exit(1); break; default: cout<<"invalid choice"; break; } } while(c!=7); } 1.insert at beginning 2.insert at end 3.show 4.deletion from front 5.deletion from rear 6.exit enter your choice:4 deletion is not possible::dequeue is empty 1.insert at beginning 2.insert at end 3.show 4.deletion from front 5.deletion from rear 6.exit enter your choice:5 deletion is not possible::dequeue is empty 1.insert at beginning 2.insert at end 3.show 4.deletion from front 5.deletion from rear 6.exit enter your choice:1 enter the element to be inserted7 inserted element is:7 1.insert at beginning 2.insert at end 3.show 4.deletion from front 5.deletion from rear 6.exit enter your choice:1 enter the element to be inserted6 insertion is not possible, overflow!!! 1.insert at beginning 2.insert at end 3.show 4.deletion from front 5.deletion from rear 6.exit enter your choice:1 enter the element to be inserted4 insertion is not possible, overflow!!! 1.insert at beginning 2.insert at end 3.show 4.deletion from front 5.deletion from rear 6.exit enter your choice:2 enter the element to be inserted6 Inserted item is6 1.insert at beginning 2.insert at end 3.show 4.deletion from front 5.deletion from rear 6.exit enter your choice:2 enter the element to be inserted4 Inserted item is4 1.insert at beginning 2.insert at end 3.show 4.deletion from front 5.deletion from rear 6.exit enter your choice:3 7 6 4 1.insert at beginning 2.insert at end 3.show 4.deletion from front 5.deletion from rear 6.exit enter your choice:4 the deleted element is:7 1.insert at beginning 2.insert at end 3.show 4.deletion from front 5.deletion from rear 6.exit enter your choice:5 the deleted element is:4 1.insert at beginning 2.insert at end 3.show 4.deletion from front 5.deletion from rear 6.exit enter your choice:1 enter the element to be inserted7 inserted element is:7 1.insert at beginning 2.insert at end 3.show 4.deletion from front 5.deletion from rear 6.exit enter your choice:3 7 6 1.insert at beginning 2.insert at end 3.show 4.deletion from front 5.deletion from rear 6.exit enter your choice:6
[ { "code": null, "e": 1185, "s": 1062, "text": "Dequeue or Double Ended Queue is a generalized version of Queue data structure that allows insert and delete at both ends." }, { "code": null, "e": 1224, "s": 1185, "text": "Some basic operations of dequeue are −" }, { "code": null, "e": 1282, "s": 1224, "text": "insert_at_beg(): inserts an item at the front of Dequeue." }, { "code": null, "e": 1339, "s": 1282, "text": "insert_at_end(): inserts an item at the rear of Dequeue." }, { "code": null, "e": 1395, "s": 1339, "text": "delete_fr_beg(): Deletes an item from front of Dequeue." }, { "code": null, "e": 1451, "s": 1395, "text": "delete_fr_rear(): Deletes an item from rear of Dequeue." }, { "code": null, "e": 1499, "s": 1451, "text": "Following is a C++ program to implement Dequeue" }, { "code": null, "e": 2255, "s": 1499, "text": "Begin\n Declare a class dequeue to declare front f and rear r and following functions:\n function insert_at_beg(int) to insert item at front:\n If queue is not completely filled up, insert element at the front and update front and rear\n Otherwise print overflow.\n function insert_at_end(int) to insert item at rear:\n If queue is not completely filled up, insert element at the rear and update front and rear\n Otherwise print overflow.\n function delete_fr_beg() to delete item from front:\n If queue is empty, print underflow otherwise delete the front element and update front.\n function delete_fr_end() to delete item from end:\n If queue is empty, print underflow otherwise delete the rear element and update rear.\nEnd" }, { "code": null, "e": 4821, "s": 2255, "text": "#include<iostream>\nusing namespace std;\n#define SIZE 10\nclass dequeue {\n int a[20],f,r;\n public:\n dequeue();\n void insert_at_beg(int);\n void insert_at_end(int);\n void delete_fr_front();\n void delete_fr_rear();\n void show();\n};\ndequeue::dequeue() {\n f=-1;\n r=-1;\n}\nvoid dequeue::insert_at_end(int i) {\n if(r>=SIZE-1) {\n cout<<\"\\n insertion is not possible, overflow!!!!\";\n } else {\n if(f==-1) {\n f++;\n r++;\n } else {\n r=r+1;\n }\n a[r]=i;\n cout<<\"\\nInserted item is\"<<a[r];\n }\n}\nvoid dequeue::insert_at_beg(int i) {\n if(f==-1) {\n f=0;\n a[++r]=i;\n cout<<\"\\n inserted element is:\"<<i;\n } else if(f!=0) {\n a[--f]=i;\n cout<<\"\\n inserted element is:\"<<i;\n } else {\n cout<<\"\\n insertion is not possible, overflow!!!\";\n }\n}\nvoid dequeue::delete_fr_front() {\n if(f==-1) {\n cout<<\"deletion is not possible::dequeue is empty\";\n return;\n }\n else {\n cout<<\"the deleted element is:\"<<a[f];\n if(f==r) {\n f=r=-1;\n return;\n } else\n f=f+1;\n }\n }\n void dequeue::delete_fr_rear() {\n if(f==-1) {\n cout<<\"deletion is not possible::dequeue is empty\";\n return;\n }\n else {\n cout<<\"the deleted element is:\"<<a[r];\n if(f==r) {\n f=r=-1;\n } else\n r=r-1;\n }\n }\n void dequeue::show() {\n if(f==-1) {\n cout<<\"Dequeue is empty\";\n } else {\n for(int i=f;i<=r;i++) {\n cout<<a[i]<<\" \";\n }\n }\n }\n int main() {\n int c,i;\n dequeue d;\n Do//perform switch opeartion {\n cout<<\"\\n 1.insert at beginning\";\n cout<<\"\\n 2.insert at end\";\n cout<<\"\\n 3.show\";\n cout<<\"\\n 4.deletion from front\";\n cout<<\"\\n 5.deletion from rear\";\n cout<<\"\\n 6.exit\";\n cout<<\"\\n enter your choice:\";\n cin>>c;\n switch(c) {\n case 1:\n cout<<\"enter the element to be inserted\";\n cin>>i;\n d.insert_at_beg(i);\n break;\n case 2:\n cout<<\"enter the element to be inserted\";\n cin>>i;\n d.insert_at_end(i);\n break;\n case 3:\n d.show();\n break;\n case 4:\n d.delete_fr_front();\n break;\n case 5:\n d.delete_fr_rear();\n break;\n case 6:\n exit(1);\n break;\n default:\n cout<<\"invalid choice\";\n break;\n }\n } while(c!=7);\n}" }, { "code": null, "e": 6830, "s": 4821, "text": "1.insert at beginning\n2.insert at end\n3.show\n4.deletion from front\n5.deletion from rear\n6.exit\nenter your choice:4\ndeletion is not possible::dequeue is empty\n1.insert at beginning\n2.insert at end\n3.show\n4.deletion from front\n5.deletion from rear\n6.exit\nenter your choice:5\ndeletion is not possible::dequeue is empty\n1.insert at beginning\n2.insert at end\n3.show\n4.deletion from front\n5.deletion from rear\n6.exit\nenter your choice:1\nenter the element to be inserted7\n\ninserted element is:7\n1.insert at beginning\n2.insert at end\n3.show\n4.deletion from front\n5.deletion from rear\n6.exit\nenter your choice:1\nenter the element to be inserted6\n\ninsertion is not possible, overflow!!!\n1.insert at beginning\n2.insert at end\n3.show\n4.deletion from front\n5.deletion from rear\n6.exit\nenter your choice:1\nenter the element to be inserted4\n\ninsertion is not possible, overflow!!!\n1.insert at beginning\n2.insert at end\n3.show\n4.deletion from front\n5.deletion from rear\n6.exit\nenter your choice:2\nenter the element to be inserted6\n\nInserted item is6\n1.insert at beginning\n2.insert at end\n3.show\n4.deletion from front\n5.deletion from rear\n6.exit\nenter your choice:2\nenter the element to be inserted4\n\nInserted item is4\n1.insert at beginning\n2.insert at end\n3.show\n4.deletion from front\n5.deletion from rear\n6.exit\nenter your choice:3\n7 6 4\n1.insert at beginning\n2.insert at end\n3.show\n4.deletion from front\n5.deletion from rear\n6.exit\nenter your choice:4\nthe deleted element is:7\n1.insert at beginning\n2.insert at end\n3.show\n4.deletion from front\n5.deletion from rear\n6.exit\nenter your choice:5\nthe deleted element is:4\n1.insert at beginning\n2.insert at end\n3.show\n4.deletion from front\n5.deletion from rear\n6.exit\nenter your choice:1\nenter the element to be inserted7\n\ninserted element is:7\n1.insert at beginning\n2.insert at end\n3.show\n4.deletion from front\n5.deletion from rear\n6.exit\nenter your choice:3\n7 6\n1.insert at beginning\n2.insert at end\n3.show\n4.deletion from front\n5.deletion from rear\n6.exit\nenter your choice:6" } ]
Getting Started with Cron Job in the Linux Server: A Complete Tutorial for Beginner | by Audhi Aprilliant | Towards Data Science
1 What are cron, cron job, and crontab?2 Understand a cron job syntax3 How to handle an error on your cron job • Send output to a specific file • Use /dev/null4 Write a simple cron automation script5 Conclusion6 References Cron is a system that helps Linux users to schedule any task. However, a cron job is any defined task to run in a given time period. It can be a shell script or a simple bash command. Cron job helps us automate our routine tasks, it can be hourly, daily, monthly, etc. Note: in most of Linux system, we must get a permission of system administrator before defining a spesific cron job that is listed on crontab Meanwhile, the crontab stands for cron table. It is a Linux system file that contains a list of the cron job. We define our task — bash command, shell script, Python script, etc scheduled in crontab. # Check cron service on Linux systemsudo systemctl status cron.service It’s time to learn about cron job syntax on crontab. crontab -a <filename>: create a new <filename> as crontab file crontab -e: edit our crontab file or create one if it doesn’t already exist crontab -l: show up our crontab file crontab -r: delete our crontab file crontab -v: show up the last time we have edited our crontab file minute(s) hour(s) day(s) month(s) weekday(s) command(s) Note: day names 0–6 begin with Sunday. We can easily determine our schedule on https://crontab.guru/ If the cron job encounters an error, the default, it will send an email to the system administrator. Instead, we will find out two common ways when we encounter the error. It’s a common way and I always use it on my cron job. It’s simple. We just need to create a file that will save our cron job logs. It will print out the output just in case the job is accomplished properly or print out an error if it fails. In this tutorial, it just created a log.out file. The output will be redirected to log.out. * * * * * cd /home/audhi && /bin/bash shell-script.sh >> log.out The description of the above syntax on a crontab file is as follows. The * * * * * means that a task will be executed every minute of every hour of every day of every month and every day of the week The directory will be switched to /home/audhi where the shell-script.sh is located /bin/bash is the path and executable of the Bash shell The >> symbol will append the output to an existing file (log.out), while a single > symbol will overwrite the file The shell-script.sh is a certain shell script Note: we need to write the complete and clear command in a crontab. It needed to specify the file location using cd We can easily send our cron job logs and error to the dev/null instead of an alert via email. Whatever we send or write to dev/null, it will be discarded. * * * * * cd /home/audhi && /bin/bash shell-script.sh > /dev/null 2>&1 A little description of the commands: The > /dev/null tells the cron to redirect the output (STDOUT) to /dev/null 2 is the file descriptor for Standard Error (STDERR) & is the symbol for file descriptor (without it, the following 1 will be a filename) 1 is the file descriptor for Standard Out (STDOUT) Note: The 2>&1 tells the cron to redirect all errors (STDERR) to same as standard out (STDOUT) To complete this article, I have created a Python script to demonstrate how to use a cron job. This Python script will collect the Covid-19 data from one of the largest Indonesian online news, Kompas News. You can find out my Python script for Covid-19 data web scraping at my GitHub repo. Its filename is Web Scraping Covid-19 Kompas News.py. Open our terminal and type crontab -e to open a crontab file. Then, scroll down and type the following command. 5 16 * * * cd 'covid19 data' && /usr/bin/python3 'Web Scraping Covid-19 Kompas News.py' >> test.out The description of the above syntax on a crontab file is as follows. The crontab is located in /home and my script is in /home/covid19 data , so we need to switch to the /home/covid19 data first The python3 interpreter is located in /usr/bin/python3 The output will be redirected to test.out file in /home/covid19 data Note: cron uses the local time You can also learn Apache Airflow as job orchestration to automate the regular task! medium.com The cron job runs on a Linux system to run and execute our regular tasks (terminal commands). The most important thing to learn about the cron job is the bash command on the terminal, how to set our task schedule, and make sure to catch the whole possibilities when our script is running on production, so we can prevent the error. [1] Schkn. Cron Jobs and Crontab on Linux Explained (2019), https://devconnected.com/cron-jobs-and-crontab-on-linux-explained/. [2] C. Murray. Understanding Crontab in Linux With Examples (2019), https://linuxhandbook.com/crontab/#quick-introduction-to-key-cron-concepts. [3] N. Agatha. Cron Job: Panduan Lengkap untuk Pemula 2020 (2020), https://www.hostinger.co.id/tutorial/cron-job/.
[ { "code": null, "e": 397, "s": 172, "text": "1 What are cron, cron job, and crontab?2 Understand a cron job syntax3 How to handle an error on your cron job • Send output to a specific file • Use /dev/null4 Write a simple cron automation script5 Conclusion6 References" }, { "code": null, "e": 666, "s": 397, "text": "Cron is a system that helps Linux users to schedule any task. However, a cron job is any defined task to run in a given time period. It can be a shell script or a simple bash command. Cron job helps us automate our routine tasks, it can be hourly, daily, monthly, etc." }, { "code": null, "e": 808, "s": 666, "text": "Note: in most of Linux system, we must get a permission of system administrator before defining a spesific cron job that is listed on crontab" }, { "code": null, "e": 1008, "s": 808, "text": "Meanwhile, the crontab stands for cron table. It is a Linux system file that contains a list of the cron job. We define our task — bash command, shell script, Python script, etc scheduled in crontab." }, { "code": null, "e": 1079, "s": 1008, "text": "# Check cron service on Linux systemsudo systemctl status cron.service" }, { "code": null, "e": 1132, "s": 1079, "text": "It’s time to learn about cron job syntax on crontab." }, { "code": null, "e": 1195, "s": 1132, "text": "crontab -a <filename>: create a new <filename> as crontab file" }, { "code": null, "e": 1271, "s": 1195, "text": "crontab -e: edit our crontab file or create one if it doesn’t already exist" }, { "code": null, "e": 1308, "s": 1271, "text": "crontab -l: show up our crontab file" }, { "code": null, "e": 1344, "s": 1308, "text": "crontab -r: delete our crontab file" }, { "code": null, "e": 1410, "s": 1344, "text": "crontab -v: show up the last time we have edited our crontab file" }, { "code": null, "e": 1466, "s": 1410, "text": "minute(s) hour(s) day(s) month(s) weekday(s) command(s)" }, { "code": null, "e": 1567, "s": 1466, "text": "Note: day names 0–6 begin with Sunday. We can easily determine our schedule on https://crontab.guru/" }, { "code": null, "e": 1739, "s": 1567, "text": "If the cron job encounters an error, the default, it will send an email to the system administrator. Instead, we will find out two common ways when we encounter the error." }, { "code": null, "e": 1980, "s": 1739, "text": "It’s a common way and I always use it on my cron job. It’s simple. We just need to create a file that will save our cron job logs. It will print out the output just in case the job is accomplished properly or print out an error if it fails." }, { "code": null, "e": 2072, "s": 1980, "text": "In this tutorial, it just created a log.out file. The output will be redirected to log.out." }, { "code": null, "e": 2137, "s": 2072, "text": "* * * * * cd /home/audhi && /bin/bash shell-script.sh >> log.out" }, { "code": null, "e": 2206, "s": 2137, "text": "The description of the above syntax on a crontab file is as follows." }, { "code": null, "e": 2336, "s": 2206, "text": "The * * * * * means that a task will be executed every minute of every hour of every day of every month and every day of the week" }, { "code": null, "e": 2419, "s": 2336, "text": "The directory will be switched to /home/audhi where the shell-script.sh is located" }, { "code": null, "e": 2474, "s": 2419, "text": "/bin/bash is the path and executable of the Bash shell" }, { "code": null, "e": 2590, "s": 2474, "text": "The >> symbol will append the output to an existing file (log.out), while a single > symbol will overwrite the file" }, { "code": null, "e": 2636, "s": 2590, "text": "The shell-script.sh is a certain shell script" }, { "code": null, "e": 2752, "s": 2636, "text": "Note: we need to write the complete and clear command in a crontab. It needed to specify the file location using cd" }, { "code": null, "e": 2907, "s": 2752, "text": "We can easily send our cron job logs and error to the dev/null instead of an alert via email. Whatever we send or write to dev/null, it will be discarded." }, { "code": null, "e": 2978, "s": 2907, "text": "* * * * * cd /home/audhi && /bin/bash shell-script.sh > /dev/null 2>&1" }, { "code": null, "e": 3016, "s": 2978, "text": "A little description of the commands:" }, { "code": null, "e": 3092, "s": 3016, "text": "The > /dev/null tells the cron to redirect the output (STDOUT) to /dev/null" }, { "code": null, "e": 3145, "s": 3092, "text": "2 is the file descriptor for Standard Error (STDERR)" }, { "code": null, "e": 3230, "s": 3145, "text": "& is the symbol for file descriptor (without it, the following 1 will be a filename)" }, { "code": null, "e": 3281, "s": 3230, "text": "1 is the file descriptor for Standard Out (STDOUT)" }, { "code": null, "e": 3376, "s": 3281, "text": "Note: The 2>&1 tells the cron to redirect all errors (STDERR) to same as standard out (STDOUT)" }, { "code": null, "e": 3720, "s": 3376, "text": "To complete this article, I have created a Python script to demonstrate how to use a cron job. This Python script will collect the Covid-19 data from one of the largest Indonesian online news, Kompas News. You can find out my Python script for Covid-19 data web scraping at my GitHub repo. Its filename is Web Scraping Covid-19 Kompas News.py." }, { "code": null, "e": 3832, "s": 3720, "text": "Open our terminal and type crontab -e to open a crontab file. Then, scroll down and type the following command." }, { "code": null, "e": 3932, "s": 3832, "text": "5 16 * * * cd 'covid19 data' && /usr/bin/python3 'Web Scraping Covid-19 Kompas News.py' >> test.out" }, { "code": null, "e": 4001, "s": 3932, "text": "The description of the above syntax on a crontab file is as follows." }, { "code": null, "e": 4127, "s": 4001, "text": "The crontab is located in /home and my script is in /home/covid19 data , so we need to switch to the /home/covid19 data first" }, { "code": null, "e": 4182, "s": 4127, "text": "The python3 interpreter is located in /usr/bin/python3" }, { "code": null, "e": 4251, "s": 4182, "text": "The output will be redirected to test.out file in /home/covid19 data" }, { "code": null, "e": 4282, "s": 4251, "text": "Note: cron uses the local time" }, { "code": null, "e": 4367, "s": 4282, "text": "You can also learn Apache Airflow as job orchestration to automate the regular task!" }, { "code": null, "e": 4378, "s": 4367, "text": "medium.com" }, { "code": null, "e": 4710, "s": 4378, "text": "The cron job runs on a Linux system to run and execute our regular tasks (terminal commands). The most important thing to learn about the cron job is the bash command on the terminal, how to set our task schedule, and make sure to catch the whole possibilities when our script is running on production, so we can prevent the error." }, { "code": null, "e": 4838, "s": 4710, "text": "[1] Schkn. Cron Jobs and Crontab on Linux Explained (2019), https://devconnected.com/cron-jobs-and-crontab-on-linux-explained/." }, { "code": null, "e": 4982, "s": 4838, "text": "[2] C. Murray. Understanding Crontab in Linux With Examples (2019), https://linuxhandbook.com/crontab/#quick-introduction-to-key-cron-concepts." } ]
How can we split a string by sentence as a delimiter in Java?
The split() method of the String class accepts a String value representing the delimiter and splits into an array of tokens (words), treating the string between the occurrence of two delimiters as one token. For example, if you pass single space “ ” as a delimiter to this method and try to split a String. This method considers the word between two spaces as one token and returns an array of words (between spaces) in the current String. If the String does not contain the specified delimiter this method returns an array containing the whole string as an element. Live Demo public class SplitExample { public static void main(String[] args) { String str = "Hi how are you welcome to Tutorialspoint"; String words[] = str.split(" "); for(String token : words) { System.out.println(token); } } } Hi how are you welcome to Tutorialspoint You can also split a sentence by passing a sentence as a delimiter if you do so each time the specified sentence occurs the String is divided as a separate token. Following Java program reads the contents of a file into a Sting and splits it using the split() method with a sentence as a delimiter. public class StringOccurrence { public static String fileToString(String filePath){ Scanner sc = null; String input = null; StringBuffer sb = null; try { sc = new Scanner(new File(filePath)); sb = new StringBuffer(); while (sc.hasNextLine()) { input = sc.nextLine(); sb.append(" "+input); } } catch(Exception ex) { ex.toString(); } return sb.toString(); } public static void main(String args[]) throws FileNotFoundException { String filePath = "D://sampleData.txt"; String text = fileToString(filePath); String array[] = text.split("We don’t force our readers to sign up with us or submit their details either"); for(String token : array) { System.out.println(" "); System.out.println(token); } } } Tutorials Point originated from the idea that there exists a class of readers who respond better to online content and prefer to learn new skills at their own pace from the comforts of their drawing rooms. The journey commenced with a single tutorial on HTML in 2006 and elated by the response it generated, we worked our way to adding fresh tutorials to our repository which now proudly flaunts a wealth of tutorials and allied articles on topics ranging from programming languages to web designing to academics and much more. 40 million readers read 100 million pages every month. Our content and resources are freely available and we prefer to keep it that way to encourage our readers acquire as many skills as they would like to. No preconditions and no impediments. Simply Easy Learning!
[ { "code": null, "e": 1270, "s": 1062, "text": "The split() method of the String class accepts a String value representing the delimiter and splits into an array of tokens (words), treating the string between the occurrence of two delimiters as one token." }, { "code": null, "e": 1502, "s": 1270, "text": "For example, if you pass single space “ ” as a delimiter to this method and try to split a String. This method considers the word between two spaces as one token and returns an array of words (between spaces) in the current String." }, { "code": null, "e": 1629, "s": 1502, "text": "If the String does not contain the specified delimiter this method returns an array containing the whole string as an element." }, { "code": null, "e": 1640, "s": 1629, "text": " Live Demo" }, { "code": null, "e": 1899, "s": 1640, "text": "public class SplitExample {\n public static void main(String[] args) {\n String str = \"Hi how are you welcome to Tutorialspoint\";\n String words[] = str.split(\" \");\n for(String token : words) {\n System.out.println(token);\n }\n }\n}" }, { "code": null, "e": 1940, "s": 1899, "text": "Hi\nhow\nare\nyou\nwelcome\nto\nTutorialspoint" }, { "code": null, "e": 2103, "s": 1940, "text": "You can also split a sentence by passing a sentence as a delimiter if you do so each time the specified sentence occurs the String is divided as a separate token." }, { "code": null, "e": 2239, "s": 2103, "text": "Following Java program reads the contents of a file into a Sting and splits it using the split() method with a sentence as a delimiter." }, { "code": null, "e": 3115, "s": 2239, "text": "public class StringOccurrence {\n public static String fileToString(String filePath){\n Scanner sc = null;\n String input = null;\n StringBuffer sb = null;\n try {\n sc = new Scanner(new File(filePath));\n sb = new StringBuffer();\n while (sc.hasNextLine()) {\n input = sc.nextLine();\n sb.append(\" \"+input);\n }\n }\n catch(Exception ex) {\n ex.toString();\n }\n return sb.toString();\n }\n public static void main(String args[]) throws FileNotFoundException {\n String filePath = \"D://sampleData.txt\";\n String text = fileToString(filePath);\n String array[] = text.split(\"We don’t force our readers to sign up with us or submit their details either\");\n for(String token : array) {\n System.out.println(\" \");\n System.out.println(token);\n }\n }\n}" }, { "code": null, "e": 3918, "s": 3115, "text": "Tutorials Point originated from the idea that there exists a class of readers \nwho respond better to online content and prefer to learn new skills at their \nown pace from the comforts of their drawing rooms. The journey commenced with \na single tutorial on HTML in 2006 and elated by the response it generated, \nwe worked our way to adding fresh tutorials to our repository which now \nproudly flaunts a wealth of tutorials and allied articles on topics ranging \nfrom programming languages to web designing to academics and much more. \n40 million readers read 100 million pages every month. Our content and \nresources are freely available and we prefer to keep it that way to \nencourage our readers acquire as many skills as they would like to.\nNo preconditions and no impediments. Simply Easy Learning!" } ]
Angular 8 - Installation
This chapter explains about how to install Angular 8 on your machine. Before moving to the installation, let’s verify the prerequisite first. As we know already, Angular is written in TypeScript. We need Node and npm to compile the files into JavaScript after that, we can deploy our application. For this purpose, Node.js must be installed in your system. Hopefully, you have installed Node.js on your machine. We can check it using the below command − node --version You could see the version of node. It is show below − v14.2.0 If Node is not installed, you can download and install by visiting the following link − Angular 8 CLI installation is based on very simple steps. It will take not more than five minutes to install. npm is used to install Angular 8 CLI. Once Node.js is installed, npm is also installed. If you want verify it, type the below command npm -v You could see the version below − 6.14.4 Let’s install Angular 8 CLI using npmas follows − npm install -g @angular/cli@^8.0.0 To verify Angular 8 is properly installed on your machine, type the below command − ng version You could see the following response − Angular CLI: 8.3.26 Node: 14.2.0 OS: win32 x64 Angular: ... Package Version ------------------------------------------------------ @angular-devkit/architect 0.803.26 @angular-devkit/core 8.3.26 @angular-devkit/schematics 8.3.26 @schematics/angular 8.3.26 @schematics/update 0.803.26 rxjs 6.4.0 16 Lectures 1.5 hours Anadi Sharma 28 Lectures 2.5 hours Anadi Sharma 11 Lectures 7.5 hours SHIVPRASAD KOIRALA 16 Lectures 2.5 hours Frahaan Hussain 69 Lectures 5 hours Senol Atac 53 Lectures 3.5 hours Senol Atac Print Add Notes Bookmark this page
[ { "code": null, "e": 2530, "s": 2388, "text": "This chapter explains about how to install Angular 8 on your machine. Before moving to the installation, let’s verify the prerequisite first." }, { "code": null, "e": 2800, "s": 2530, "text": "As we know already, Angular is written in TypeScript. We need Node and npm to compile the files into JavaScript after that, we can deploy our application. For this purpose, Node.js must be installed in your system. Hopefully, you have installed Node.js on your machine." }, { "code": null, "e": 2842, "s": 2800, "text": "We can check it using the below command −" }, { "code": null, "e": 2858, "s": 2842, "text": "node --version\n" }, { "code": null, "e": 2912, "s": 2858, "text": "You could see the version of node. It is show below −" }, { "code": null, "e": 2921, "s": 2912, "text": "v14.2.0\n" }, { "code": null, "e": 3009, "s": 2921, "text": "If Node is not installed, you can download and install by visiting the following link −" }, { "code": null, "e": 3119, "s": 3009, "text": "Angular 8 CLI installation is based on very simple steps. It will take not more than five minutes to install." }, { "code": null, "e": 3253, "s": 3119, "text": "npm is used to install Angular 8 CLI. Once Node.js is installed, npm is also installed. If you want verify it, type the below command" }, { "code": null, "e": 3261, "s": 3253, "text": "npm -v\n" }, { "code": null, "e": 3295, "s": 3261, "text": "You could see the version below −" }, { "code": null, "e": 3303, "s": 3295, "text": "6.14.4\n" }, { "code": null, "e": 3353, "s": 3303, "text": "Let’s install Angular 8 CLI using npmas follows −" }, { "code": null, "e": 3389, "s": 3353, "text": "npm install -g @angular/cli@^8.0.0\n" }, { "code": null, "e": 3473, "s": 3389, "text": "To verify Angular 8 is properly installed on your machine, type the below command −" }, { "code": null, "e": 3485, "s": 3473, "text": "ng version\n" }, { "code": null, "e": 3524, "s": 3485, "text": "You could see the following response −" }, { "code": null, "e": 3892, "s": 3524, "text": "Angular CLI: 8.3.26 \nNode: 14.2.0 \nOS: win32 x64 \nAngular: ... \nPackage Version \n------------------------------------------------------\n@angular-devkit/architect 0.803.26 \n@angular-devkit/core 8.3.26 \n@angular-devkit/schematics 8.3.26 \n@schematics/angular 8.3.26 \n@schematics/update 0.803.26 \nrxjs 6.4.0\n" }, { "code": null, "e": 3927, "s": 3892, "text": "\n 16 Lectures \n 1.5 hours \n" }, { "code": null, "e": 3941, "s": 3927, "text": " Anadi Sharma" }, { "code": null, "e": 3976, "s": 3941, "text": "\n 28 Lectures \n 2.5 hours \n" }, { "code": null, "e": 3990, "s": 3976, "text": " Anadi Sharma" }, { "code": null, "e": 4025, "s": 3990, "text": "\n 11 Lectures \n 7.5 hours \n" }, { "code": null, "e": 4045, "s": 4025, "text": " SHIVPRASAD KOIRALA" }, { "code": null, "e": 4080, "s": 4045, "text": "\n 16 Lectures \n 2.5 hours \n" }, { "code": null, "e": 4097, "s": 4080, "text": " Frahaan Hussain" }, { "code": null, "e": 4130, "s": 4097, "text": "\n 69 Lectures \n 5 hours \n" }, { "code": null, "e": 4142, "s": 4130, "text": " Senol Atac" }, { "code": null, "e": 4177, "s": 4142, "text": "\n 53 Lectures \n 3.5 hours \n" }, { "code": null, "e": 4189, "s": 4177, "text": " Senol Atac" }, { "code": null, "e": 4196, "s": 4189, "text": " Print" }, { "code": null, "e": 4207, "s": 4196, "text": " Add Notes" } ]
How to preload the video when the page loads in HTML5 ? - GeeksforGeeks
25 Mar, 2021 The HTML <preload> attribute is used to specify the way the developer thinks the video should be loaded when the page loads. Syntax <video preload=""> </video> There are 3 values for preload attribute auto, metadata and none. Note: A empty string lead to default auto attribute value. Example 1: The following example demonstrates the video element using none attribute value for the preload property. HTML <!DOCTYPE html> <html> <body> <center> <h1 style="color:green;">GeeksforGeeks</h1> <h3>HTML preload Attribute</h3> <video width="400" height="200" controls preload="none"> <source src= "https://media.geeksforgeeks.org/wp-content/uploads/20190616234019/Canvas.move_.mp4" type="video/mp4"> <source src= "https://media.geeksforgeeks.org/wp-content/uploads/20190616234019/Canvas.move_.ogg" type="video/ogg"> </video> </center> </body> </html> Output: preload with none value Example 2: The following example demonstrates the video element using auto attribute value. HTML <!DOCTYPE html> <html> <body> <center> <h1 style="color:green;">GeeksforGeeks</h1> <h3>HTML preload Attribute</h3> <video width="400" height="200" controls preload="auto"> <source src= "https://media.geeksforgeeks.org/wp-content/uploads/20190616234019/Canvas.move_.mp4" type="video/mp4"> <source src= "https://media.geeksforgeeks.org/wp-content/uploads/20190616234019/Canvas.move_.ogg" type="video/ogg"> </video> </center> </body> </html> Output: preload with auto value Attention reader! Don’t stop learning now. Get hold of all the important HTML concepts with the Web Design for Beginners | HTML course. HTML-Attributes HTML-Questions HTML-Tags Picked HTML Web Technologies HTML Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. How to Insert Form Data into Database using PHP ? REST API (Introduction) Types of CSS (Cascading Style Sheet) Form validation using HTML and JavaScript How to position a div at the bottom of its container using CSS? Roadmap to Become a Web Developer in 2022 Installation of Node.js on Linux How to fetch data from an API in ReactJS ? Convert a string to an integer in JavaScript Difference between var, let and const keywords in JavaScript
[ { "code": null, "e": 25536, "s": 25508, "text": "\n25 Mar, 2021" }, { "code": null, "e": 25661, "s": 25536, "text": "The HTML <preload> attribute is used to specify the way the developer thinks the video should be loaded when the page loads." }, { "code": null, "e": 25668, "s": 25661, "text": "Syntax" }, { "code": null, "e": 25696, "s": 25668, "text": "<video preload=\"\"> </video>" }, { "code": null, "e": 25762, "s": 25696, "text": "There are 3 values for preload attribute auto, metadata and none." }, { "code": null, "e": 25821, "s": 25762, "text": "Note: A empty string lead to default auto attribute value." }, { "code": null, "e": 25938, "s": 25821, "text": "Example 1: The following example demonstrates the video element using none attribute value for the preload property." }, { "code": null, "e": 25943, "s": 25938, "text": "HTML" }, { "code": "<!DOCTYPE html> <html> <body> <center> <h1 style=\"color:green;\">GeeksforGeeks</h1> <h3>HTML preload Attribute</h3> <video width=\"400\" height=\"200\" controls preload=\"none\"> <source src= \"https://media.geeksforgeeks.org/wp-content/uploads/20190616234019/Canvas.move_.mp4\" type=\"video/mp4\"> <source src= \"https://media.geeksforgeeks.org/wp-content/uploads/20190616234019/Canvas.move_.ogg\" type=\"video/ogg\"> </video> </center> </body> </html> ", "e": 26492, "s": 25943, "text": null }, { "code": null, "e": 26500, "s": 26492, "text": "Output:" }, { "code": null, "e": 26524, "s": 26500, "text": "preload with none value" }, { "code": null, "e": 26616, "s": 26524, "text": "Example 2: The following example demonstrates the video element using auto attribute value." }, { "code": null, "e": 26621, "s": 26616, "text": "HTML" }, { "code": "<!DOCTYPE html> <html> <body> <center> <h1 style=\"color:green;\">GeeksforGeeks</h1> <h3>HTML preload Attribute</h3> <video width=\"400\" height=\"200\" controls preload=\"auto\"> <source src= \"https://media.geeksforgeeks.org/wp-content/uploads/20190616234019/Canvas.move_.mp4\" type=\"video/mp4\"> <source src= \"https://media.geeksforgeeks.org/wp-content/uploads/20190616234019/Canvas.move_.ogg\" type=\"video/ogg\"> </video> </center> </body> </html> ", "e": 27169, "s": 26621, "text": null }, { "code": null, "e": 27177, "s": 27169, "text": "Output:" }, { "code": null, "e": 27201, "s": 27177, "text": "preload with auto value" }, { "code": null, "e": 27338, "s": 27201, "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": 27354, "s": 27338, "text": "HTML-Attributes" }, { "code": null, "e": 27369, "s": 27354, "text": "HTML-Questions" }, { "code": null, "e": 27379, "s": 27369, "text": "HTML-Tags" }, { "code": null, "e": 27386, "s": 27379, "text": "Picked" }, { "code": null, "e": 27391, "s": 27386, "text": "HTML" }, { "code": null, "e": 27408, "s": 27391, "text": "Web Technologies" }, { "code": null, "e": 27413, "s": 27408, "text": "HTML" }, { "code": null, "e": 27511, "s": 27413, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 27561, "s": 27511, "text": "How to Insert Form Data into Database using PHP ?" }, { "code": null, "e": 27585, "s": 27561, "text": "REST API (Introduction)" }, { "code": null, "e": 27622, "s": 27585, "text": "Types of CSS (Cascading Style Sheet)" }, { "code": null, "e": 27664, "s": 27622, "text": "Form validation using HTML and JavaScript" }, { "code": null, "e": 27728, "s": 27664, "text": "How to position a div at the bottom of its container using CSS?" }, { "code": null, "e": 27770, "s": 27728, "text": "Roadmap to Become a Web Developer in 2022" }, { "code": null, "e": 27803, "s": 27770, "text": "Installation of Node.js on Linux" }, { "code": null, "e": 27846, "s": 27803, "text": "How to fetch data from an API in ReactJS ?" }, { "code": null, "e": 27891, "s": 27846, "text": "Convert a string to an integer in JavaScript" } ]
array-of- arrays double [][] in C#?
Arrays of arrays in C# are known as Jagged Arrays. To declare jagged arrays, use the double [ ][ ]. Let us now declare them − int [][] marks; Now, let us initialize it, wherein marks are arrays of 5 integers − int[][] marks = new int[][]{new int[]{ 90,95 },new int[]{ 89,94 }, new int[]{ 78,87 },new int[]{ 76, 68 }, new int[]{ 98, 91 } }; Let us now see the complete example of jagged arrays in C# and learn how to implement it − Live Demo using System; namespace MyApplication { class MyDemoClass { static void Main(string[] args) { int i, j; /* jagged array of 5 array of integers */ int[][] marks = new int[][]{new int[]{90,95},new int[]{89,94}, new int[]{78,87},new int[]{ 76, 68 }, new int[]{ 98, 91}}; for (i = 0; i < 5; i++) { for (j = 0; j < 2; j++) { Console.WriteLine("marks[{0}][{1}] = {2}", i, j, marks[i][j]); } } Console.ReadKey(); } } } marks[0][0] = 90 marks[0][1] = 95 marks[1][0] = 89 marks[1][1] = 94 marks[2][0] = 78 marks[2][1] = 87 marks[3][0] = 76 marks[3][1] = 68 marks[4][0] = 98 marks[4][1] = 91
[ { "code": null, "e": 1162, "s": 1062, "text": "Arrays of arrays in C# are known as Jagged Arrays. To declare jagged arrays, use the double [ ][ ]." }, { "code": null, "e": 1188, "s": 1162, "text": "Let us now declare them −" }, { "code": null, "e": 1204, "s": 1188, "text": "int [][] marks;" }, { "code": null, "e": 1272, "s": 1204, "text": "Now, let us initialize it, wherein marks are arrays of 5 integers −" }, { "code": null, "e": 1402, "s": 1272, "text": "int[][] marks = new int[][]{new int[]{ 90,95 },new int[]{ 89,94 }, new int[]{ 78,87 },new int[]{ 76, 68 }, new\nint[]{ 98, 91 } };" }, { "code": null, "e": 1493, "s": 1402, "text": "Let us now see the complete example of jagged arrays in C# and learn how to implement it −" }, { "code": null, "e": 1503, "s": 1493, "text": "Live Demo" }, { "code": null, "e": 2036, "s": 1503, "text": "using System;\nnamespace MyApplication {\n class MyDemoClass {\n static void Main(string[] args) {\n int i, j;\n /* jagged array of 5 array of integers */\n int[][] marks = new int[][]{new int[]{90,95},new int[]{89,94}, new int[]{78,87},new int[]{ 76, 68 },\n new int[]{ 98, 91}};\n\n for (i = 0; i < 5; i++) {\n for (j = 0; j < 2; j++) {\n Console.WriteLine(\"marks[{0}][{1}] = {2}\", i, j, marks[i][j]);\n }\n }\n Console.ReadKey();\n }\n }\n}" }, { "code": null, "e": 2206, "s": 2036, "text": "marks[0][0] = 90\nmarks[0][1] = 95\nmarks[1][0] = 89\nmarks[1][1] = 94\nmarks[2][0] = 78\nmarks[2][1] = 87\nmarks[3][0] = 76\nmarks[3][1] = 68\nmarks[4][0] = 98\nmarks[4][1] = 91" } ]
PHP program to find the minimum element in an array
To find the minimum element in an array, the PHP code is as follows − Live Demo <?php function get_min_value($my_array){ $n = count($my_array); $min_val = $my_array[0]; for ($i = 1; $i < $n; $i++) if ($min_val > $my_array[$i]) $min_val = $my_array[$i]; return $min_val; } $my_array = array(56, 78, 91, 44, 0, 11); print_r("The lowest value of the array is "); echo(get_min_value($my_array)); echo("\n"); ?> The lowest value of the array is 0 A function named ‘get_min_value()’ takes an array as parameter. Inside this function, the count function is used to find the number of elements in the array, and it is assigned to a variable − $n = count($my_array); The first element in the array is assigned to a variable, and the array is iterated over, and adjacent values in the array are compared, and the lowest value amongst all of them is given as output − $min_val = $my_array[0]; for ($i = 1; $i < $n; $i++) if ($min_val > $my_array[$i]) $min_val = $my_array[$i]; return $min_val; Outside the function, the array is defined, and the function is called by passing this array as a parameter. The output is displayed on the screen. $my_array = array(56, 78, 91, 44, 0, 11); print_r("The lowest value of the array is "); echo(get_min_value($my_array));
[ { "code": null, "e": 1132, "s": 1062, "text": "To find the minimum element in an array, the PHP code is as follows −" }, { "code": null, "e": 1143, "s": 1132, "text": " Live Demo" }, { "code": null, "e": 1539, "s": 1143, "text": "<?php\n function get_min_value($my_array){\n $n = count($my_array);\n $min_val = $my_array[0];\n for ($i = 1; $i < $n; $i++)\n if ($min_val > $my_array[$i])\n $min_val = $my_array[$i];\n return $min_val;\n }\n $my_array = array(56, 78, 91, 44, 0, 11);\n print_r(\"The lowest value of the array is \");\n echo(get_min_value($my_array));\n echo(\"\\n\");\n?>" }, { "code": null, "e": 1574, "s": 1539, "text": "The lowest value of the array is 0" }, { "code": null, "e": 1767, "s": 1574, "text": "A function named ‘get_min_value()’ takes an array as parameter. Inside this function, the count\nfunction is used to find the number of elements in the array, and it is assigned to a variable −" }, { "code": null, "e": 1790, "s": 1767, "text": "$n = count($my_array);" }, { "code": null, "e": 1989, "s": 1790, "text": "The first element in the array is assigned to a variable, and the array is iterated over, and adjacent\nvalues in the array are compared, and the lowest value amongst all of them is given as output −" }, { "code": null, "e": 2124, "s": 1989, "text": "$min_val = $my_array[0];\nfor ($i = 1; $i < $n; $i++)\n if ($min_val > $my_array[$i])\n $min_val = $my_array[$i];\nreturn $min_val;" }, { "code": null, "e": 2272, "s": 2124, "text": "Outside the function, the array is defined, and the function is called by passing this array as a\nparameter. The output is displayed on the screen." }, { "code": null, "e": 2392, "s": 2272, "text": "$my_array = array(56, 78, 91, 44, 0, 11);\nprint_r(\"The lowest value of the array is \");\necho(get_min_value($my_array));" } ]
C# | Dictionary.Add() Method - GeeksforGeeks
01 Feb, 2019 Dictionary<TKey,TValue>.Add() Method is used to add a specified key and value to the dictionary. Syntax: public void Add (TKey key, TValue value); Parameters: key: It is the key of the element to add.value: It is the value of the element to add. The value can be null for reference types. Exceptions: ArgumentNullException : If the key is null. ArgumentException : If an element with the same key already exists in the Dictionary. Below are the programs to illustrate the use of Dictionary<TKey,TValue>.Add() Method: Example 1: // C# code to add the specified key// and value into the Dictionaryusing System;using System.Collections.Generic; class GFG { // Driver code public static void Main() { // Create a new dictionary // of strings, with string keys. Dictionary<string, string> myDict = new Dictionary<string, string>(); // Adding key/value pairs in myDict myDict.Add("Australia", "Canberra"); myDict.Add("Belgium", "Brussels"); myDict.Add("Netherlands", "Amsterdam"); myDict.Add("China", "Beijing"); myDict.Add("Russia", "Moscow"); myDict.Add("India", "New Delhi"); // To get count of key/value // pairs in myDict Console.WriteLine("Total key/value pairs in"+ " myDict are : " + myDict.Count); // Displaying the key/value // pairs in myDict Console.WriteLine("The key/value pairs"+ " in myDict are : "); foreach(KeyValuePair<string, string> kvp in myDict) { Console.WriteLine("Key = {0}, Value = {1}", kvp.Key, kvp.Value); } }} Total key/value pairs in myDict are : 6 The key/value pairs in myDict are : Key = Australia, Value = Canberra Key = Belgium, Value = Brussels Key = Netherlands, Value = Amsterdam Key = China, Value = Beijing Key = Russia, Value = Moscow Key = India, Value = New Delhi Example 2: // C# code to add the specified // key and value into the Dictionaryusing System;using System.Collections.Generic; class GFG { // Driver code public static void Main() { // Create a new dictionary of // strings, with string keys. Dictionary<string, string> myDict = new Dictionary<string, string>(); // Adding key/value pairs in myDict myDict.Add("Australia", "Canberra"); myDict.Add("Belgium", "Brussels"); myDict.Add("Netherlands", "Amsterdam"); myDict.Add("China", "Beijing"); myDict.Add("Russia", "Moscow"); myDict.Add("India", "New Delhi"); // The Add method throws an // exception if the new key is // already in the dictionary. try { myDict.Add("Russia", "Moscow"); } catch (ArgumentException) { Console.WriteLine("An element with Key "+ "= \"Russia\" already exists."); } }} An element with Key = "Russia" already exists. Note: A key cannot be null, but a value can be if TValue is a reference type. If Count is less than the capacity, this method approaches an O(1) operation. If the capacity must be increased to accommodate the new element, this method becomes an O(n) operation, where n is Count. Reference: https://docs.microsoft.com/en-us/dotnet/api/system.collections.generic.dictionary-2.add?view=netframework-4.7.2 CSharp Dictionary Class CSharp-Generic-Namespace CSharp-method C# Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments C# | Delegates Top 50 C# Interview Questions & Answers Introduction to .NET Framework C# | Constructors C# | Class and Object Extension Method in C# C# | Abstract Classes C# | String.IndexOf( ) Method | Set - 1 Common Language Runtime (CLR) in C# C# | Arrays
[ { "code": null, "e": 24283, "s": 24255, "text": "\n01 Feb, 2019" }, { "code": null, "e": 24380, "s": 24283, "text": "Dictionary<TKey,TValue>.Add() Method is used to add a specified key and value to the dictionary." }, { "code": null, "e": 24388, "s": 24380, "text": "Syntax:" }, { "code": null, "e": 24431, "s": 24388, "text": "public void Add (TKey key, TValue value);\n" }, { "code": null, "e": 24443, "s": 24431, "text": "Parameters:" }, { "code": null, "e": 24573, "s": 24443, "text": "key: It is the key of the element to add.value: It is the value of the element to add. The value can be null for reference types." }, { "code": null, "e": 24585, "s": 24573, "text": "Exceptions:" }, { "code": null, "e": 24629, "s": 24585, "text": "ArgumentNullException : If the key is null." }, { "code": null, "e": 24715, "s": 24629, "text": "ArgumentException : If an element with the same key already exists in the Dictionary." }, { "code": null, "e": 24801, "s": 24715, "text": "Below are the programs to illustrate the use of Dictionary<TKey,TValue>.Add() Method:" }, { "code": null, "e": 24812, "s": 24801, "text": "Example 1:" }, { "code": "// C# code to add the specified key// and value into the Dictionaryusing System;using System.Collections.Generic; class GFG { // Driver code public static void Main() { // Create a new dictionary // of strings, with string keys. Dictionary<string, string> myDict = new Dictionary<string, string>(); // Adding key/value pairs in myDict myDict.Add(\"Australia\", \"Canberra\"); myDict.Add(\"Belgium\", \"Brussels\"); myDict.Add(\"Netherlands\", \"Amsterdam\"); myDict.Add(\"China\", \"Beijing\"); myDict.Add(\"Russia\", \"Moscow\"); myDict.Add(\"India\", \"New Delhi\"); // To get count of key/value // pairs in myDict Console.WriteLine(\"Total key/value pairs in\"+ \" myDict are : \" + myDict.Count); // Displaying the key/value // pairs in myDict Console.WriteLine(\"The key/value pairs\"+ \" in myDict are : \"); foreach(KeyValuePair<string, string> kvp in myDict) { Console.WriteLine(\"Key = {0}, Value = {1}\", kvp.Key, kvp.Value); } }}", "e": 25974, "s": 24812, "text": null }, { "code": null, "e": 26244, "s": 25974, "text": "Total key/value pairs in myDict are : 6\nThe key/value pairs in myDict are : \nKey = Australia, Value = Canberra\nKey = Belgium, Value = Brussels\nKey = Netherlands, Value = Amsterdam\nKey = China, Value = Beijing\nKey = Russia, Value = Moscow\nKey = India, Value = New Delhi\n" }, { "code": null, "e": 26255, "s": 26244, "text": "Example 2:" }, { "code": "// C# code to add the specified // key and value into the Dictionaryusing System;using System.Collections.Generic; class GFG { // Driver code public static void Main() { // Create a new dictionary of // strings, with string keys. Dictionary<string, string> myDict = new Dictionary<string, string>(); // Adding key/value pairs in myDict myDict.Add(\"Australia\", \"Canberra\"); myDict.Add(\"Belgium\", \"Brussels\"); myDict.Add(\"Netherlands\", \"Amsterdam\"); myDict.Add(\"China\", \"Beijing\"); myDict.Add(\"Russia\", \"Moscow\"); myDict.Add(\"India\", \"New Delhi\"); // The Add method throws an // exception if the new key is // already in the dictionary. try { myDict.Add(\"Russia\", \"Moscow\"); } catch (ArgumentException) { Console.WriteLine(\"An element with Key \"+ \"= \\\"Russia\\\" already exists.\"); } }}", "e": 27237, "s": 26255, "text": null }, { "code": null, "e": 27285, "s": 27237, "text": "An element with Key = \"Russia\" already exists.\n" }, { "code": null, "e": 27291, "s": 27285, "text": "Note:" }, { "code": null, "e": 27363, "s": 27291, "text": "A key cannot be null, but a value can be if TValue is a reference type." }, { "code": null, "e": 27441, "s": 27363, "text": "If Count is less than the capacity, this method approaches an O(1) operation." }, { "code": null, "e": 27564, "s": 27441, "text": "If the capacity must be increased to accommodate the new element, this method becomes an O(n) operation, where n is Count." }, { "code": null, "e": 27575, "s": 27564, "text": "Reference:" }, { "code": null, "e": 27687, "s": 27575, "text": "https://docs.microsoft.com/en-us/dotnet/api/system.collections.generic.dictionary-2.add?view=netframework-4.7.2" }, { "code": null, "e": 27711, "s": 27687, "text": "CSharp Dictionary Class" }, { "code": null, "e": 27736, "s": 27711, "text": "CSharp-Generic-Namespace" }, { "code": null, "e": 27750, "s": 27736, "text": "CSharp-method" }, { "code": null, "e": 27753, "s": 27750, "text": "C#" }, { "code": null, "e": 27851, "s": 27753, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 27860, "s": 27851, "text": "Comments" }, { "code": null, "e": 27873, "s": 27860, "text": "Old Comments" }, { "code": null, "e": 27888, "s": 27873, "text": "C# | Delegates" }, { "code": null, "e": 27928, "s": 27888, "text": "Top 50 C# Interview Questions & Answers" }, { "code": null, "e": 27959, "s": 27928, "text": "Introduction to .NET Framework" }, { "code": null, "e": 27977, "s": 27959, "text": "C# | Constructors" }, { "code": null, "e": 27999, "s": 27977, "text": "C# | Class and Object" }, { "code": null, "e": 28022, "s": 27999, "text": "Extension Method in C#" }, { "code": null, "e": 28044, "s": 28022, "text": "C# | Abstract Classes" }, { "code": null, "e": 28084, "s": 28044, "text": "C# | String.IndexOf( ) Method | Set - 1" }, { "code": null, "e": 28120, "s": 28084, "text": "Common Language Runtime (CLR) in C#" } ]
How to create comma separated list from an array in PHP?
To create a comma-separated list from an array in PHP, the code is as follows− Live Demo <?php $arr = array( " John ", "Jacob ", " Tom ", " Tim "); echo "Array with leading and trailing whitespaces...\n"; foreach( $arr as $value ) { echo "Value = $value \n"; } echo "\nComma separated list...\n"; print_r(implode(', ', $arr)); $result = array_map('trim', $arr); echo "\nUpdated Array...\n"; foreach( $result as $value ) { echo "Value = $value \n"; } ?> This will produce the following output− Array with leading and trailing whitespaces... Value = John Value = Jacob Value = Tom Value = Tim Comma separated list... John , Jacob , Tom , Tim Updated Array... Value = John Value = Jacob Value = Tom Value = Tim Let us now see another example − Live Demo <?php $arr = array(100, 200, 300, 400, 500); echo "Comma separated list...\n"; print_r(implode(', ', $arr)); ?> This will produce the following output− Comma separated list... 100, 200, 300, 400, 500
[ { "code": null, "e": 1141, "s": 1062, "text": "To create a comma-separated list from an array in PHP, the code is as follows−" }, { "code": null, "e": 1152, "s": 1141, "text": " Live Demo" }, { "code": null, "e": 1558, "s": 1152, "text": "<?php\n $arr = array( \" John \", \"Jacob \", \" Tom \", \" Tim \");\n echo \"Array with leading and trailing whitespaces...\\n\";\n foreach( $arr as $value ) {\n echo \"Value = $value \\n\";\n }\n echo \"\\nComma separated list...\\n\";\n print_r(implode(', ', $arr));\n $result = array_map('trim', $arr);\n echo \"\\nUpdated Array...\\n\";\n foreach( $result as $value ) {\n echo \"Value = $value \\n\";\n }\n?>" }, { "code": null, "e": 1598, "s": 1558, "text": "This will produce the following output−" }, { "code": null, "e": 1816, "s": 1598, "text": "Array with leading and trailing whitespaces...\nValue = John\nValue = Jacob\nValue = Tom\nValue = Tim\nComma separated list...\n John , Jacob , Tom , Tim\nUpdated Array...\nValue = John\nValue = Jacob\nValue = Tom\nValue = Tim" }, { "code": null, "e": 1849, "s": 1816, "text": "Let us now see another example −" }, { "code": null, "e": 1860, "s": 1849, "text": " Live Demo" }, { "code": null, "e": 1981, "s": 1860, "text": "<?php\n $arr = array(100, 200, 300, 400, 500);\n echo \"Comma separated list...\\n\";\n print_r(implode(', ', $arr));\n?>" }, { "code": null, "e": 2021, "s": 1981, "text": "This will produce the following output−" }, { "code": null, "e": 2070, "s": 2021, "text": "Comma separated list... \n100, 200, 300, 400, 500" } ]
Are Multiple Constructors possible in Java?
There can be multiple constructors in a class. However, the parameter list of the constructors should not be same. This is known as constructor overloading. A program that demonstrates this is given as follows − Live Demo class NumberValue { private int num; public NumberValue() { num = 6; } public NumberValue(int n) { num = n; } public void display() { System.out.println("The number is: " + num); } } public class Demo { public static void main(String[] args) { NumberValue obj1 = new NumberValue(); NumberValue obj2 = new NumberValue(15); obj1.display(); obj2.display(); } } The number is: 6 The number is: 15 Now let us understand the above program. The NumberValue class is created with a data member num and single member function display() that displays the value of num. There are two constructors in class NumberValue where one of these takes no parameters and the other takes a single parameter of type int. A code snippet which demonstrates this is as follows − class NumberValue { private int num; public NumberValue() { num = 6; } public NumberValue(int n) { num = n; } public void display() { System.out.println("The number is: " + num); } } In the main() method, objects obj1 and obj2 of class NumberValue are created and the display() method is called for both of them. A code snippet which demonstrates this is as follows: public class Demo { public static void main(String[] args) { NumberValue obj1 = new NumberValue(); NumberValue obj2 = new NumberValue(15); obj1.display(); obj2.display(); } }
[ { "code": null, "e": 1219, "s": 1062, "text": "There can be multiple constructors in a class. However, the parameter list of the constructors should not be same. This is known as constructor overloading." }, { "code": null, "e": 1274, "s": 1219, "text": "A program that demonstrates this is given as follows −" }, { "code": null, "e": 1285, "s": 1274, "text": " Live Demo" }, { "code": null, "e": 1712, "s": 1285, "text": "class NumberValue {\n private int num;\n public NumberValue() {\n num = 6;\n }\n public NumberValue(int n) {\n num = n;\n }\n public void display() {\n System.out.println(\"The number is: \" + num);\n }\n}\npublic class Demo {\n public static void main(String[] args) {\n NumberValue obj1 = new NumberValue();\n NumberValue obj2 = new NumberValue(15);\n obj1.display();\n obj2.display();\n }\n}" }, { "code": null, "e": 1747, "s": 1712, "text": "The number is: 6\nThe number is: 15" }, { "code": null, "e": 1788, "s": 1747, "text": "Now let us understand the above program." }, { "code": null, "e": 2107, "s": 1788, "text": "The NumberValue class is created with a data member num and single member function display() that displays the value of num. There are two constructors in class NumberValue where one of these takes no parameters and the other takes a single parameter of type int. A code snippet which demonstrates this is as follows −" }, { "code": null, "e": 2329, "s": 2107, "text": "class NumberValue {\n private int num;\n public NumberValue() {\n num = 6;\n }\n public NumberValue(int n) {\n num = n;\n }\n public void display() {\n System.out.println(\"The number is: \" + num);\n }\n}" }, { "code": null, "e": 2513, "s": 2329, "text": "In the main() method, objects obj1 and obj2 of class NumberValue are created and the display() method is called for both of them. A code snippet which demonstrates this is as follows:" }, { "code": null, "e": 2718, "s": 2513, "text": "public class Demo {\n public static void main(String[] args) {\n NumberValue obj1 = new NumberValue();\n NumberValue obj2 = new NumberValue(15);\n obj1.display();\n obj2.display();\n }\n}" } ]
Ensemble Classification: A Brief Overview With Examples | by Pranav Thaenraj | Towards Data Science
Note: This article is the final article in a series of articles regarding the classification of transportation POI data. The first article looked to use various Machine Learning models to classify records as Airports, Bus stops, and Train stations. The second article was centered around the use of feature reduction algorithms as means of tuning the models from the first article to provide better accuracy. The third article looked to use the Spark Multilayer Perceptron Classifier to classify these records properly. Check out these articles to see how this project has evolved in the search for the best way to classify POI data. This article will use ensemble classification for properly classifying the POI records from SafeGraph using foot traffic patterns. SafeGraph is a data provider that provides POI data for hundreds of businesses and categories. It provides data for free to academics. For this project, I have chosen to use SafeGraph patterns data to classify records as various POI’s. The schema for the patterns data can be found here: Schema Info Ensemble learning is the concept of multiple “weak learners” being used together to create a machine learning model that is capable of performing better than they each could individually. Most of the time these weak learners don’t perform well on their own because they have either high bias or high variance. The point of combining multiple weak learners in an ensemble model is to reduce this bias and variance. Before we can start with the Ensemble Classification aspects we must first load the Data. This particular step has been covered in both the first article of the series as well as the second one. The basic steps behind the data loading and preprocessing to fit our needs for this article are: Before we take our first steps into the notions of ensemble classification we must first load the data that we will use for this project: This process of loading the data can be found in the notebook and has been explained in detail in the first part of the series. The steps taken were: Dropping unnecesscay columns- [‘parent_safegraph_place_id’,’placekey’,’safegraph_place_id’,’parent_placekey’,’parent_placekey’,’safegraph_brand_ids’,’brands’, ‘poi_cbg’]Creating ground truth column that establishes each record as either Airport, Bus station, Airport, or UnkownDropping Unknown records to clear out records that cannot be identifiedHorizontally exploding columns of JSON strings using pysparkHorizontally exploding columns of arraysUsing Sklearn LabelEncoder package to transform class column Dropping unnecesscay columns- [‘parent_safegraph_place_id’,’placekey’,’safegraph_place_id’,’parent_placekey’,’parent_placekey’,’safegraph_brand_ids’,’brands’, ‘poi_cbg’] Creating ground truth column that establishes each record as either Airport, Bus station, Airport, or Unkown Dropping Unknown records to clear out records that cannot be identified Horizontally exploding columns of JSON strings using pyspark Horizontally exploding columns of arrays Using Sklearn LabelEncoder package to transform class column As a result of these transformations the outputted data looks like this and has the following columns: Raw_visit_counts: Number of visits in our panel to this POI during the date range. Raw_visitor_counts: Number of unique visitors from our panel to this POI during the date range. Distance_from_home: Median distance from home traveled by visitors (of visitors whose home we have identified) in meters. Median_dwell: Median minimum dwell time in minutes. Bucketed Dwells (Exploded to <5, 5–10,11–20,21–60,61–120,121–240): Key is the range of minutes and value is the number of visits that were within that duration Popularity_by_day(Exploded to Monday-Sunday): A mapping of the day of the week to the number of visits on each day (local time) in the course of the date range Popularity_by_hour(Exploded to popularity_1-popularity_24): A mapping of the hour of the day to the number of visits in each hour over the course of the date range in local time. The first element in the array corresponds to the hour of midnight to 1 am Device_type(Exploded to IOS and Android): The number of visitors to the POI that is using android vs. ios. Only device_type with at least 2 devices are shown and any category with less than 5 devices are reported as Now that the data is ready to go, we can begin on the Ensemble Learning aspects. For this portion of the article, we will be using the Sklearn Voting Classifier. This is the built-in model for ensemble learning in the Sklearn package. Before using this, however, we need to first train the three weak learners that we are using for this model. The models we are using are the same as those from the first portions of this series of articles, the Gaussian Naive Bayes model, the Decision Tree model, and the K-Nearest Neighbors model. #Training all three modelsfrom sklearn.neighbors import KNeighborsClassifierfrom sklearn.naive_bayes import GaussianNBfrom sklearn.tree import DecisionTreeClassifierdtree_model = DecisionTreeClassifier(max_depth = 3).fit(X_train, y_train)gnb = GaussianNB().fit(X_train, y_train)knn = KNeighborsClassifier(n_neighbors = 22).fit(X_train, y_train) Now that all three models have been trained we can use these models to perform the next steps of the process is to call the model and aggregate the created models into a dictionary for the ensemble model’s use from sklearn.ensemble import VotingClassifierestimators=[(‘knn’, knn), (‘gnb’, gnb), (‘dtree_model’, dtree_model)]ensemble = VotingClassifier(estimators, voting=’hard’) Upon training and testing the model we receive the following outputs: ensemble.fit(X_train, y_train)ensemble.score(X_test, y_test) from sklearn.metrics import confusion_matrixprediction = ensemble.predict(X_test)confusion_matrix(y_test, prediction) plot_confusion_matrix(ensemble, X_test, y_test, normalize=’true’, values_format = ‘.3f’, display_labels=[‘Airport’,’Bus’,’Train’]) The accuracy of this model is slightly lower than that of the most effective model of the models used to create the ensemble classification model (.75 vs .68). The model performs much better than the Gaussian Naive Bayes model (.265) and performs on par with the K-Nearest Neighbors classifier (.679). Seeing the model is performing better than the average of these three accuracies, one can say that the use of ensemble classification for this particular dataset is an efficient way to increase the accuracy of the predictions. As before, the main cause for the model’s shortcomings is the imbalance in the dataset and the lack of Bus Station records. This problem was not solved by manually rebalancing the data as we saw in the Spark Deep Learning article, thus the best course of action for future classification endeavors would be to avoid strongly imbalanced data at all costs or suffer a severe drop in accuracy. Through this project we were able to determine the importance of ensemble classification and the efficiency the technique can have when using several weak learners to create the model. From this exercise we were able to derive a model that performs much better than the average accuracy of the three weak learners that it combined. This concludes this series of articles on POI classification. Through the analysis that we have made in the last 4 portions of the series we can see the efficiency by which SafeGraph data can be classified using Machine Learning and that the accuracy of the predictions can be quite high. Questions? I invite you to ask them in the #safegraphdata channel of the SafeGraph Community, a free Slack community for data enthusiasts. Receive support, share your work, or connect with others in the GIS community. Through the SafeGraph Community, academics have free access to data on over 7 million businesses in the USA, UK, and Canada.
[ { "code": null, "e": 805, "s": 171, "text": "Note: This article is the final article in a series of articles regarding the classification of transportation POI data. The first article looked to use various Machine Learning models to classify records as Airports, Bus stops, and Train stations. The second article was centered around the use of feature reduction algorithms as means of tuning the models from the first article to provide better accuracy. The third article looked to use the Spark Multilayer Perceptron Classifier to classify these records properly. Check out these articles to see how this project has evolved in the search for the best way to classify POI data." }, { "code": null, "e": 1236, "s": 805, "text": "This article will use ensemble classification for properly classifying the POI records from SafeGraph using foot traffic patterns. SafeGraph is a data provider that provides POI data for hundreds of businesses and categories. It provides data for free to academics. For this project, I have chosen to use SafeGraph patterns data to classify records as various POI’s. The schema for the patterns data can be found here: Schema Info" }, { "code": null, "e": 1650, "s": 1236, "text": "Ensemble learning is the concept of multiple “weak learners” being used together to create a machine learning model that is capable of performing better than they each could individually. Most of the time these weak learners don’t perform well on their own because they have either high bias or high variance. The point of combining multiple weak learners in an ensemble model is to reduce this bias and variance." }, { "code": null, "e": 1942, "s": 1650, "text": "Before we can start with the Ensemble Classification aspects we must first load the Data. This particular step has been covered in both the first article of the series as well as the second one. The basic steps behind the data loading and preprocessing to fit our needs for this article are:" }, { "code": null, "e": 2230, "s": 1942, "text": "Before we take our first steps into the notions of ensemble classification we must first load the data that we will use for this project: This process of loading the data can be found in the notebook and has been explained in detail in the first part of the series. The steps taken were:" }, { "code": null, "e": 2739, "s": 2230, "text": "Dropping unnecesscay columns- [‘parent_safegraph_place_id’,’placekey’,’safegraph_place_id’,’parent_placekey’,’parent_placekey’,’safegraph_brand_ids’,’brands’, ‘poi_cbg’]Creating ground truth column that establishes each record as either Airport, Bus station, Airport, or UnkownDropping Unknown records to clear out records that cannot be identifiedHorizontally exploding columns of JSON strings using pysparkHorizontally exploding columns of arraysUsing Sklearn LabelEncoder package to transform class column" }, { "code": null, "e": 2909, "s": 2739, "text": "Dropping unnecesscay columns- [‘parent_safegraph_place_id’,’placekey’,’safegraph_place_id’,’parent_placekey’,’parent_placekey’,’safegraph_brand_ids’,’brands’, ‘poi_cbg’]" }, { "code": null, "e": 3018, "s": 2909, "text": "Creating ground truth column that establishes each record as either Airport, Bus station, Airport, or Unkown" }, { "code": null, "e": 3090, "s": 3018, "text": "Dropping Unknown records to clear out records that cannot be identified" }, { "code": null, "e": 3151, "s": 3090, "text": "Horizontally exploding columns of JSON strings using pyspark" }, { "code": null, "e": 3192, "s": 3151, "text": "Horizontally exploding columns of arrays" }, { "code": null, "e": 3253, "s": 3192, "text": "Using Sklearn LabelEncoder package to transform class column" }, { "code": null, "e": 3356, "s": 3253, "text": "As a result of these transformations the outputted data looks like this and has the following columns:" }, { "code": null, "e": 3439, "s": 3356, "text": "Raw_visit_counts: Number of visits in our panel to this POI during the date range." }, { "code": null, "e": 3535, "s": 3439, "text": "Raw_visitor_counts: Number of unique visitors from our panel to this POI during the date range." }, { "code": null, "e": 3657, "s": 3535, "text": "Distance_from_home: Median distance from home traveled by visitors (of visitors whose home we have identified) in meters." }, { "code": null, "e": 3709, "s": 3657, "text": "Median_dwell: Median minimum dwell time in minutes." }, { "code": null, "e": 3869, "s": 3709, "text": "Bucketed Dwells (Exploded to <5, 5–10,11–20,21–60,61–120,121–240): Key is the range of minutes and value is the number of visits that were within that duration" }, { "code": null, "e": 4029, "s": 3869, "text": "Popularity_by_day(Exploded to Monday-Sunday): A mapping of the day of the week to the number of visits on each day (local time) in the course of the date range" }, { "code": null, "e": 4283, "s": 4029, "text": "Popularity_by_hour(Exploded to popularity_1-popularity_24): A mapping of the hour of the day to the number of visits in each hour over the course of the date range in local time. The first element in the array corresponds to the hour of midnight to 1 am" }, { "code": null, "e": 4499, "s": 4283, "text": "Device_type(Exploded to IOS and Android): The number of visitors to the POI that is using android vs. ios. Only device_type with at least 2 devices are shown and any category with less than 5 devices are reported as" }, { "code": null, "e": 4580, "s": 4499, "text": "Now that the data is ready to go, we can begin on the Ensemble Learning aspects." }, { "code": null, "e": 5033, "s": 4580, "text": "For this portion of the article, we will be using the Sklearn Voting Classifier. This is the built-in model for ensemble learning in the Sklearn package. Before using this, however, we need to first train the three weak learners that we are using for this model. The models we are using are the same as those from the first portions of this series of articles, the Gaussian Naive Bayes model, the Decision Tree model, and the K-Nearest Neighbors model." }, { "code": null, "e": 5378, "s": 5033, "text": "#Training all three modelsfrom sklearn.neighbors import KNeighborsClassifierfrom sklearn.naive_bayes import GaussianNBfrom sklearn.tree import DecisionTreeClassifierdtree_model = DecisionTreeClassifier(max_depth = 3).fit(X_train, y_train)gnb = GaussianNB().fit(X_train, y_train)knn = KNeighborsClassifier(n_neighbors = 22).fit(X_train, y_train)" }, { "code": null, "e": 5588, "s": 5378, "text": "Now that all three models have been trained we can use these models to perform the next steps of the process is to call the model and aggregate the created models into a dictionary for the ensemble model’s use" }, { "code": null, "e": 5757, "s": 5588, "text": "from sklearn.ensemble import VotingClassifierestimators=[(‘knn’, knn), (‘gnb’, gnb), (‘dtree_model’, dtree_model)]ensemble = VotingClassifier(estimators, voting=’hard’)" }, { "code": null, "e": 5827, "s": 5757, "text": "Upon training and testing the model we receive the following outputs:" }, { "code": null, "e": 5888, "s": 5827, "text": "ensemble.fit(X_train, y_train)ensemble.score(X_test, y_test)" }, { "code": null, "e": 6006, "s": 5888, "text": "from sklearn.metrics import confusion_matrixprediction = ensemble.predict(X_test)confusion_matrix(y_test, prediction)" }, { "code": null, "e": 6137, "s": 6006, "text": "plot_confusion_matrix(ensemble, X_test, y_test, normalize=’true’, values_format = ‘.3f’, display_labels=[‘Airport’,’Bus’,’Train’])" }, { "code": null, "e": 7057, "s": 6137, "text": "The accuracy of this model is slightly lower than that of the most effective model of the models used to create the ensemble classification model (.75 vs .68). The model performs much better than the Gaussian Naive Bayes model (.265) and performs on par with the K-Nearest Neighbors classifier (.679). Seeing the model is performing better than the average of these three accuracies, one can say that the use of ensemble classification for this particular dataset is an efficient way to increase the accuracy of the predictions. As before, the main cause for the model’s shortcomings is the imbalance in the dataset and the lack of Bus Station records. This problem was not solved by manually rebalancing the data as we saw in the Spark Deep Learning article, thus the best course of action for future classification endeavors would be to avoid strongly imbalanced data at all costs or suffer a severe drop in accuracy." }, { "code": null, "e": 7678, "s": 7057, "text": "Through this project we were able to determine the importance of ensemble classification and the efficiency the technique can have when using several weak learners to create the model. From this exercise we were able to derive a model that performs much better than the average accuracy of the three weak learners that it combined. This concludes this series of articles on POI classification. Through the analysis that we have made in the last 4 portions of the series we can see the efficiency by which SafeGraph data can be classified using Machine Learning and that the accuracy of the predictions can be quite high." }, { "code": null, "e": 7689, "s": 7678, "text": "Questions?" } ]
How To Make Your Python Code Run Faster — 1st Installment | by Ujjwal Dalmia | Towards Data Science
In the last tutorial, we introduced you to line_profiler, a package that can help you time profile your code. It is now time to take a step forward. In this tutorial, we will learn about implementing multi-threading and multi-processing approaches using Python. These approaches guide the operating system to make optimum utilization of one’s system hardware and hence make the code execution efficient. Let’s get started... Quoting Wiki — In computer architecture, multi-threading is the ability of a central processing unit (CPU) (or a single core in a multi-core processor) to provide multiple threads of execution concurrently, supported by the operating system. Given concurrency, one can initiate parallel execution of multiple processes and achieve faster runtime. Without going into the technical details (google and read about GIL), one thing to keep in mind is that multi-threading is more efficient when performing I/O based tasks like downloading images and files. On the other hand, multi-processing is better suited for CPU based tasks that are computationally intensive. To implement multi-threading, we will be using Python’s standard library, threading. The library comes by default with standard Python installation and hence can be imported directly in our code. For demonstrating the effectiveness of multi-threading, we will be downloading 5 images from Unsplash. Let us observe the execution time when we download these images sequentially: #### Importing requests libraryimport requests#### Defining the function def down_img(name,link): data = requests.get(link).content name = f"/home/isud/DidYouKnow/Tutorial 5/{name}.jpg" with open(name, "wb") as file: file.write(data)#### 5 images downloaded sequentially%%timeit -n1 -r1images = ['https://images.unsplash.com/photo-1531458999205-f31f14fa217b', 'https://images.unsplash.com/photo-1488572749058-7f52dd70e0fa', 'https://images.unsplash.com/photo-1531404610614-68f9e73e35db', 'https://images.unsplash.com/photo-1523489405193-3884f5ca475f', 'https://images.unsplash.com/photo-1565098735462-5db3412ac4cb']for i,link in enumerate(images): down_img(i,link)#### %%timeit results51.4 s ± 0 ns per loop (mean ± std. dev. of 1 run, 1 loop each) As can be observed, a complete download of 5 images took 51.4 seconds. Also, a new download started only after the previous download has ended. Let us now see how multi-threading can improve code performance. #### Importing necessary libraryimport threadingimport requests#### Defining the functiondef down_img(name,link): data = requests.get(link).content name = f"/home/isud/DidYouKnow/Tutorial 5/{name}.jpg" with open(name, "wb") as file: file.write(data)#### Images downloaded in parallel threads%%timeit -n1 -r1threads = []images = ['https://images.unsplash.com/photo-1531458999205-f31f14fa217b', 'https://images.unsplash.com/photo-1488572749058-7f52dd70e0fa', 'https://images.unsplash.com/photo-1531404610614-68f9e73e35db', 'https://images.unsplash.com/photo-1523489405193-3884f5ca475f', 'https://images.unsplash.com/photo-1565098735462-5db3412ac4cb']for i,link in enumerate(images): t = threading.Thread(target=down_img, args=(i,link)) t.start() threads.append(t)for thread in threads: thread.join()#### %%timeit results25.6 s ± 0 ns per loop (mean ± std. dev. of 1 run, 1 loop each) Step 1 (Thread Initiation) — Python runs the complete code in a single thread (let’s call it the main thread). In this example, by calling Thread function from the threading library, we are initiating parallel threads and assigning them a target process to be executed (down_image in this case). All the arguments, required by the called function, should be passed as a sequence object (tuple in this case). Each call to the Thread function initiates a new thread (let’s call them parallel threads). Step 2 (Thread start) — Call to the thread’s start method will instruct Python to start thread execution. Given the for loop is executing in the main thread and the function calls are in a parallel thread, the for loop execution will continue while the image download is in progress. Step 3 (Thread join) — Each new thread is captured in a list named threads. The parallel threads are then joined to the main thread by calling the join method. Until step 2, all our threads (main thread and parallel threads) were under parallel execution. In such a scenario, the main thread execution can complete much before the parallel threads. To avoid this, joining the parallel threads to the main thread is inevitable. This will ensure that the execution of the main thread completes only after the completion of parallel threads. The following diagram explains these 2 scenarios: As can be seen, the execution time to download images has gone down by close to 50% (25.6 seconds approx.). The above example showcases how multi-threading can be helpful in I/O operations and improves the efficiency of the download/upload processes. Unlike multi-threading which executes multiple threads in a single process, multi-processing initiates a new parallel process for every task. As mentioned above, it delivers considerable improvement in runtime for CPU intensive tasks, tasks requiring heavy computations. Multiprocessing is another standard library which enables multi-processing feature in Python. To understand it’s functionality, we will call a computationally intensive function multiple times. The function used for demonstration purpose calculates the square of numbers from 1 to 10 million. This function is executed in parallel 8 times. Let’s observe the performance of this function under normal circumstances. #### Importing time libraryimport time#### Defining the function def demo_func(num): for i in range(num): a = i**2#### Calling demo function sequentially%%timeit -n1 -r1for i in range(8): demo_func(10000000)#### %%timeit results21.2 s ± 0 ns per loop (mean ± std. dev. of 1 run, 1 loop each) The sequential execution of the demo function took a total of 21.2 seconds. Now let’s check the performance uplift when this is done in a multi-processing setup. #### Importing time libraryimport time#### Defining the function def demo_func(num): for i in range(num): a = i**2#### Multi-processing demo function %%timeit -n1 -r1processes = []lop_size = [10000000,10000000,10000000,10000000,10000000,10000000,10000000, 10000000]p = multiprocessing.Pool()p.map(demo_func,lop_size)p.close()p.join()#### %%timeit results11.6 s ± 0 ns per loop (mean ± std. dev. of 1 run, 1 loop each) Under a multi-processing framework, the execution time dropped by 50% to 11.6 seconds. In sequential processing, a single CPU core is utilized at a time whereas, in multi-processing, all the system cores are utilized in parallel. The CPU usage screenshots demonstrate the same: Each line in the above graph represents a CPU core. Notice how in sequential execution, a single core is triggered for every function call where as in parallel execution, all the cores are triggered at once. Step 1(Pool Creation) — The Pooling method creates the pool of processes that can be leveraged in parallel. Without any arguments, the number of processes created is equal to the number of CPU cores on your system. I have a quad-core system (4 cores) which means, on execution, out of 8 function calls, the first 4 calls will run in parallel followed by the next 4 calls. Note that one can also define a custom number of processes in the pool (more than number of cores) but beyond a point, it will start eating up your system memory and might degrade performance Step 2 (Pool Mapping) — This is where your processes are instructed to execute a specific function (first argument) along with a list of arguments to be passed to it (second argument) Step 3(Pool Close) — Close method instructs Python interpreter that we have submitted everything we wanted to submit to the pool and there will be no more inputs provided to the pool in the future. Step 4(Pool Join) — As in the case of threading, the join method ensures that the code execution completes only once all the parallel processes complete. From the above scenario, we could see how multi-processing can be a great weapon to fight against in-efficient code performances. In this tutorial, we kept our focus on improving the code performance by making optimum utilization of our system hardware. In the next installment, we will demonstrate specific programming practices to improve code performance. I hope this tutorial was informative and you learned something new. Will try and bring more interesting topics in future tutorials. Till then: HAPPY LEARNING ! ! ! !
[ { "code": null, "e": 195, "s": 46, "text": "In the last tutorial, we introduced you to line_profiler, a package that can help you time profile your code. It is now time to take a step forward." }, { "code": null, "e": 450, "s": 195, "text": "In this tutorial, we will learn about implementing multi-threading and multi-processing approaches using Python. These approaches guide the operating system to make optimum utilization of one’s system hardware and hence make the code execution efficient." }, { "code": null, "e": 471, "s": 450, "text": "Let’s get started..." }, { "code": null, "e": 713, "s": 471, "text": "Quoting Wiki — In computer architecture, multi-threading is the ability of a central processing unit (CPU) (or a single core in a multi-core processor) to provide multiple threads of execution concurrently, supported by the operating system." }, { "code": null, "e": 1132, "s": 713, "text": "Given concurrency, one can initiate parallel execution of multiple processes and achieve faster runtime. Without going into the technical details (google and read about GIL), one thing to keep in mind is that multi-threading is more efficient when performing I/O based tasks like downloading images and files. On the other hand, multi-processing is better suited for CPU based tasks that are computationally intensive." }, { "code": null, "e": 1328, "s": 1132, "text": "To implement multi-threading, we will be using Python’s standard library, threading. The library comes by default with standard Python installation and hence can be imported directly in our code." }, { "code": null, "e": 1509, "s": 1328, "text": "For demonstrating the effectiveness of multi-threading, we will be downloading 5 images from Unsplash. Let us observe the execution time when we download these images sequentially:" }, { "code": null, "e": 2313, "s": 1509, "text": "#### Importing requests libraryimport requests#### Defining the function def down_img(name,link): data = requests.get(link).content name = f\"/home/isud/DidYouKnow/Tutorial 5/{name}.jpg\" with open(name, \"wb\") as file: file.write(data)#### 5 images downloaded sequentially%%timeit -n1 -r1images = ['https://images.unsplash.com/photo-1531458999205-f31f14fa217b', 'https://images.unsplash.com/photo-1488572749058-7f52dd70e0fa', 'https://images.unsplash.com/photo-1531404610614-68f9e73e35db', 'https://images.unsplash.com/photo-1523489405193-3884f5ca475f', 'https://images.unsplash.com/photo-1565098735462-5db3412ac4cb']for i,link in enumerate(images): down_img(i,link)#### %%timeit results51.4 s ± 0 ns per loop (mean ± std. dev. of 1 run, 1 loop each)" }, { "code": null, "e": 2522, "s": 2313, "text": "As can be observed, a complete download of 5 images took 51.4 seconds. Also, a new download started only after the previous download has ended. Let us now see how multi-threading can improve code performance." }, { "code": null, "e": 3468, "s": 2522, "text": "#### Importing necessary libraryimport threadingimport requests#### Defining the functiondef down_img(name,link): data = requests.get(link).content name = f\"/home/isud/DidYouKnow/Tutorial 5/{name}.jpg\" with open(name, \"wb\") as file: file.write(data)#### Images downloaded in parallel threads%%timeit -n1 -r1threads = []images = ['https://images.unsplash.com/photo-1531458999205-f31f14fa217b', 'https://images.unsplash.com/photo-1488572749058-7f52dd70e0fa', 'https://images.unsplash.com/photo-1531404610614-68f9e73e35db', 'https://images.unsplash.com/photo-1523489405193-3884f5ca475f', 'https://images.unsplash.com/photo-1565098735462-5db3412ac4cb']for i,link in enumerate(images): t = threading.Thread(target=down_img, args=(i,link)) t.start() threads.append(t)for thread in threads: thread.join()#### %%timeit results25.6 s ± 0 ns per loop (mean ± std. dev. of 1 run, 1 loop each)" }, { "code": null, "e": 3968, "s": 3468, "text": "Step 1 (Thread Initiation) — Python runs the complete code in a single thread (let’s call it the main thread). In this example, by calling Thread function from the threading library, we are initiating parallel threads and assigning them a target process to be executed (down_image in this case). All the arguments, required by the called function, should be passed as a sequence object (tuple in this case). Each call to the Thread function initiates a new thread (let’s call them parallel threads)." }, { "code": null, "e": 4252, "s": 3968, "text": "Step 2 (Thread start) — Call to the thread’s start method will instruct Python to start thread execution. Given the for loop is executing in the main thread and the function calls are in a parallel thread, the for loop execution will continue while the image download is in progress." }, { "code": null, "e": 4412, "s": 4252, "text": "Step 3 (Thread join) — Each new thread is captured in a list named threads. The parallel threads are then joined to the main thread by calling the join method." }, { "code": null, "e": 4841, "s": 4412, "text": "Until step 2, all our threads (main thread and parallel threads) were under parallel execution. In such a scenario, the main thread execution can complete much before the parallel threads. To avoid this, joining the parallel threads to the main thread is inevitable. This will ensure that the execution of the main thread completes only after the completion of parallel threads. The following diagram explains these 2 scenarios:" }, { "code": null, "e": 5092, "s": 4841, "text": "As can be seen, the execution time to download images has gone down by close to 50% (25.6 seconds approx.). The above example showcases how multi-threading can be helpful in I/O operations and improves the efficiency of the download/upload processes." }, { "code": null, "e": 5363, "s": 5092, "text": "Unlike multi-threading which executes multiple threads in a single process, multi-processing initiates a new parallel process for every task. As mentioned above, it delivers considerable improvement in runtime for CPU intensive tasks, tasks requiring heavy computations." }, { "code": null, "e": 5778, "s": 5363, "text": "Multiprocessing is another standard library which enables multi-processing feature in Python. To understand it’s functionality, we will call a computationally intensive function multiple times. The function used for demonstration purpose calculates the square of numbers from 1 to 10 million. This function is executed in parallel 8 times. Let’s observe the performance of this function under normal circumstances." }, { "code": null, "e": 6083, "s": 5778, "text": "#### Importing time libraryimport time#### Defining the function def demo_func(num): for i in range(num): a = i**2#### Calling demo function sequentially%%timeit -n1 -r1for i in range(8): demo_func(10000000)#### %%timeit results21.2 s ± 0 ns per loop (mean ± std. dev. of 1 run, 1 loop each)" }, { "code": null, "e": 6245, "s": 6083, "text": "The sequential execution of the demo function took a total of 21.2 seconds. Now let’s check the performance uplift when this is done in a multi-processing setup." }, { "code": null, "e": 6673, "s": 6245, "text": "#### Importing time libraryimport time#### Defining the function def demo_func(num): for i in range(num): a = i**2#### Multi-processing demo function %%timeit -n1 -r1processes = []lop_size = [10000000,10000000,10000000,10000000,10000000,10000000,10000000, 10000000]p = multiprocessing.Pool()p.map(demo_func,lop_size)p.close()p.join()#### %%timeit results11.6 s ± 0 ns per loop (mean ± std. dev. of 1 run, 1 loop each)" }, { "code": null, "e": 6951, "s": 6673, "text": "Under a multi-processing framework, the execution time dropped by 50% to 11.6 seconds. In sequential processing, a single CPU core is utilized at a time whereas, in multi-processing, all the system cores are utilized in parallel. The CPU usage screenshots demonstrate the same:" }, { "code": null, "e": 7159, "s": 6951, "text": "Each line in the above graph represents a CPU core. Notice how in sequential execution, a single core is triggered for every function call where as in parallel execution, all the cores are triggered at once." }, { "code": null, "e": 7723, "s": 7159, "text": "Step 1(Pool Creation) — The Pooling method creates the pool of processes that can be leveraged in parallel. Without any arguments, the number of processes created is equal to the number of CPU cores on your system. I have a quad-core system (4 cores) which means, on execution, out of 8 function calls, the first 4 calls will run in parallel followed by the next 4 calls. Note that one can also define a custom number of processes in the pool (more than number of cores) but beyond a point, it will start eating up your system memory and might degrade performance" }, { "code": null, "e": 7907, "s": 7723, "text": "Step 2 (Pool Mapping) — This is where your processes are instructed to execute a specific function (first argument) along with a list of arguments to be passed to it (second argument)" }, { "code": null, "e": 8105, "s": 7907, "text": "Step 3(Pool Close) — Close method instructs Python interpreter that we have submitted everything we wanted to submit to the pool and there will be no more inputs provided to the pool in the future." }, { "code": null, "e": 8259, "s": 8105, "text": "Step 4(Pool Join) — As in the case of threading, the join method ensures that the code execution completes only once all the parallel processes complete." }, { "code": null, "e": 8389, "s": 8259, "text": "From the above scenario, we could see how multi-processing can be a great weapon to fight against in-efficient code performances." }, { "code": null, "e": 8618, "s": 8389, "text": "In this tutorial, we kept our focus on improving the code performance by making optimum utilization of our system hardware. In the next installment, we will demonstrate specific programming practices to improve code performance." }, { "code": null, "e": 8686, "s": 8618, "text": "I hope this tutorial was informative and you learned something new." }, { "code": null, "e": 8761, "s": 8686, "text": "Will try and bring more interesting topics in future tutorials. Till then:" } ]
Python - Remove empty value types in dictionaries list - GeeksforGeeks
08 May, 2020 Sometimes, while working with Python dictionaries, we require to remove all the values that are virtually Null, i.e does not hold any meaningful value and are to be removed before processing data, this can be empty string, empty list, dictionary or even 0. This has application in data preprocessing. Lets discuss certain ways in which this task can be performed. Method #1 : Using list comprehensionThis is shorthand to brute way by which this task can be performed. In this we remake the dictionary with only the valid values. # Python3 code to demonstrate working of # Remove None value types in dictionaries list# Using list comprehension # initializing listtest_list = [{'gfg' : 4, 'is' : '', 'best' : []}, {'I' : {}, 'like' : 5, 'gfg' : 0}] # printing original listprint("The original list is : " + str(test_list)) # Remove None value types in dictionaries list# Using list comprehensionres = [ele for ele in ({key: val for key, val in sub.items() if val} for sub in test_list) if ele] # printing result print("The filtered list : " + str(res)) The original list is : [{'is': '', 'best': [], 'gfg': 4}, {'like': 5, 'gfg': 0, 'I': {}}] The filtered list : [{'gfg': 4}, {'like': 5}] Method #2 : Using filter() + lambda + list comprehensionThe combination of above methods can be used to solve this problem. In this, we use filter() + lambda to perform the conditional statement task as in above method to reduce a nesting level. # Python3 code to demonstrate working of # Remove None value types in dictionaries list# Using filter() + lambda + list comprehension # initializing listtest_list = [{'gfg' : 4, 'is' : '', 'best' : []}, {'I' : {}, 'like' : 5, 'gfg' : 0}] # printing original listprint("The original list is : " + str(test_list)) # Remove None value types in dictionaries list# Using filter() + lambda + list comprehensionres = list(filter(None, ({key : val for key, val in sub.items() if val} for sub in test_list))) # printing result print("The filtered list : " + str(res)) The original list is : [{'is': '', 'best': [], 'gfg': 4}, {'like': 5, 'gfg': 0, 'I': {}}] The filtered list : [{'gfg': 4}, {'like': 5}] Python list-programs Python Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments Enumerate() in Python Read a file line by line in Python Defaultdict in Python Different ways to create Pandas Dataframe sum() function in Python Iterate over a list in Python Deque in Python How to Install PIP on Windows ? Python String | replace() Convert integer to string in Python
[ { "code": null, "e": 24009, "s": 23981, "text": "\n08 May, 2020" }, { "code": null, "e": 24373, "s": 24009, "text": "Sometimes, while working with Python dictionaries, we require to remove all the values that are virtually Null, i.e does not hold any meaningful value and are to be removed before processing data, this can be empty string, empty list, dictionary or even 0. This has application in data preprocessing. Lets discuss certain ways in which this task can be performed." }, { "code": null, "e": 24538, "s": 24373, "text": "Method #1 : Using list comprehensionThis is shorthand to brute way by which this task can be performed. In this we remake the dictionary with only the valid values." }, { "code": "# Python3 code to demonstrate working of # Remove None value types in dictionaries list# Using list comprehension # initializing listtest_list = [{'gfg' : 4, 'is' : '', 'best' : []}, {'I' : {}, 'like' : 5, 'gfg' : 0}] # printing original listprint(\"The original list is : \" + str(test_list)) # Remove None value types in dictionaries list# Using list comprehensionres = [ele for ele in ({key: val for key, val in sub.items() if val} for sub in test_list) if ele] # printing result print(\"The filtered list : \" + str(res)) ", "e": 25104, "s": 24538, "text": null }, { "code": null, "e": 25241, "s": 25104, "text": "The original list is : [{'is': '', 'best': [], 'gfg': 4}, {'like': 5, 'gfg': 0, 'I': {}}]\nThe filtered list : [{'gfg': 4}, {'like': 5}]\n" }, { "code": null, "e": 25489, "s": 25243, "text": "Method #2 : Using filter() + lambda + list comprehensionThe combination of above methods can be used to solve this problem. In this, we use filter() + lambda to perform the conditional statement task as in above method to reduce a nesting level." }, { "code": "# Python3 code to demonstrate working of # Remove None value types in dictionaries list# Using filter() + lambda + list comprehension # initializing listtest_list = [{'gfg' : 4, 'is' : '', 'best' : []}, {'I' : {}, 'like' : 5, 'gfg' : 0}] # printing original listprint(\"The original list is : \" + str(test_list)) # Remove None value types in dictionaries list# Using filter() + lambda + list comprehensionres = list(filter(None, ({key : val for key, val in sub.items() if val} for sub in test_list))) # printing result print(\"The filtered list : \" + str(res)) ", "e": 26092, "s": 25489, "text": null }, { "code": null, "e": 26229, "s": 26092, "text": "The original list is : [{'is': '', 'best': [], 'gfg': 4}, {'like': 5, 'gfg': 0, 'I': {}}]\nThe filtered list : [{'gfg': 4}, {'like': 5}]\n" }, { "code": null, "e": 26250, "s": 26229, "text": "Python list-programs" }, { "code": null, "e": 26257, "s": 26250, "text": "Python" }, { "code": null, "e": 26355, "s": 26257, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 26364, "s": 26355, "text": "Comments" }, { "code": null, "e": 26377, "s": 26364, "text": "Old Comments" }, { "code": null, "e": 26399, "s": 26377, "text": "Enumerate() in Python" }, { "code": null, "e": 26434, "s": 26399, "text": "Read a file line by line in Python" }, { "code": null, "e": 26456, "s": 26434, "text": "Defaultdict in Python" }, { "code": null, "e": 26498, "s": 26456, "text": "Different ways to create Pandas Dataframe" }, { "code": null, "e": 26523, "s": 26498, "text": "sum() function in Python" }, { "code": null, "e": 26553, "s": 26523, "text": "Iterate over a list in Python" }, { "code": null, "e": 26569, "s": 26553, "text": "Deque in Python" }, { "code": null, "e": 26601, "s": 26569, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 26627, "s": 26601, "text": "Python String | replace()" } ]
How to search for a pattern in a Java string?
Java provides the java.util.regex package for pattern matching with regular expressions. You can then search for a pattern in a Java string using classes and methods of this packages. import java.util.regex.Matcher; import java.util.regex.Pattern; public class RegexMatches { public static void main( String args[] ) { String line = "This order was placed for QT3000! OK?"; String pattern = "(.*)(\\d+)(.*)"; Pattern r = Pattern.compile(pattern); Matcher m = r.matcher(line); if (m.find( )) { System.out.println("Found value: " + m.group(0)); System.out.println("Found value: " + m.group(1)); System.out.println("Found value: " + m.group(2)); }else{ System.out.println("NO MATCH"); } } } Found value: This order was placed for QT3000! OK? Found value: This order was placed for QT300 Found value: 0
[ { "code": null, "e": 1246, "s": 1062, "text": "Java provides the java.util.regex package for pattern matching with regular expressions. You can then search for a pattern in a Java string using classes and methods of this packages." }, { "code": null, "e": 1841, "s": 1246, "text": "import java.util.regex.Matcher;\nimport java.util.regex.Pattern;\npublic class RegexMatches {\n public static void main( String args[] ) {\n\n String line = \"This order was placed for QT3000! OK?\";\n String pattern = \"(.*)(\\\\d+)(.*)\";\n Pattern r = Pattern.compile(pattern);\n Matcher m = r.matcher(line);\n \n if (m.find( )) {\n System.out.println(\"Found value: \" + m.group(0));\n System.out.println(\"Found value: \" + m.group(1));\n System.out.println(\"Found value: \" + m.group(2));\n }else{\n System.out.println(\"NO MATCH\");\n }\n }\n}" }, { "code": null, "e": 1952, "s": 1841, "text": "Found value: This order was placed for QT3000! OK?\nFound value: This order was placed for QT300\nFound value: 0" } ]
Image processing/OpenCV image erosion Java Example.
Erosion and dilation are the two basic morphological operations. As the name implies, morphological operations are the set of operations that process images according to their shapes. During erosion operation, additional pixels are removed from image boundaries, total number of pixels removed during the erosion process depends on the dimensions of the structuring element used. You can perform erosion operation on an image using the erode() method of the Imgproc class, this method three mat objects representing source, destination, and kernel. import java.awt.Image; import java.awt.image.BufferedImage; import java.io.IOException; import javafx.application.Application; import javafx.embed.swing.SwingFXUtils; import javafx.scene.Group; import javafx.scene.Scene; import javafx.scene.image.ImageView; import javafx.scene.image.WritableImage; import javafx.stage.Stage; import org.opencv.core.Core; import org.opencv.core.Mat; import org.opencv.core.Size; import org.opencv.highgui.HighGui; import org.opencv.imgcodecs.Imgcodecs; import org.opencv.imgproc.Imgproc; public class ImageErosion extends Application { public void start(Stage stage) throws IOException { //Loading the OpenCV core library System.loadLibrary( Core.NATIVE_LIBRARY_NAME ); //Reading image data String file ="D:\\Images\\lamma2.jpg"; Mat src = Imgcodecs.imread(file); //Creating destination matrix Mat dst = new Mat(src.rows(), src.cols(), src.type()); //Preparing the kernel matrix object Mat kernel = Imgproc.getStructuringElement(Imgproc.MORPH_RECT, new Size((2*2) + 1, (2*2)+1)); //Applying erosion on the Image Imgproc.erode(src, dst, kernel); //Converting matrix to JavaFX writable image Image img = HighGui.toBufferedImage(dst); WritableImage writableImage= SwingFXUtils.toFXImage((BufferedImage) img, null); //Setting the image view ImageView imageView = new ImageView(writableImage); imageView.setX(10); imageView.setY(10); imageView.setFitWidth(575); imageView.setPreserveRatio(true); //Setting the Scene object Group root = new Group(imageView); Scene scene = new Scene(root, 595, 400); stage.setTitle("Erosion Example"); stage.setScene(scene); stage.show(); } public static void main(String args[]) { launch(args); } } On executing, the above program generates the following output −
[ { "code": null, "e": 1246, "s": 1062, "text": "Erosion and dilation are the two basic morphological operations. As the name\nimplies, morphological operations are the set of operations that process images\naccording to their shapes." }, { "code": null, "e": 1442, "s": 1246, "text": "During erosion operation, additional pixels are removed from image boundaries,\ntotal number of pixels removed during the erosion process depends on the\ndimensions of the structuring element used." }, { "code": null, "e": 1611, "s": 1442, "text": "You can perform erosion operation on an image using the erode() method of the Imgproc class, this method three mat objects representing source, destination, and kernel." }, { "code": null, "e": 3445, "s": 1611, "text": "import java.awt.Image;\nimport java.awt.image.BufferedImage;\nimport java.io.IOException;\nimport javafx.application.Application;\nimport javafx.embed.swing.SwingFXUtils;\nimport javafx.scene.Group;\nimport javafx.scene.Scene;\nimport javafx.scene.image.ImageView;\nimport javafx.scene.image.WritableImage;\nimport javafx.stage.Stage;\nimport org.opencv.core.Core;\nimport org.opencv.core.Mat;\nimport org.opencv.core.Size;\nimport org.opencv.highgui.HighGui;\nimport org.opencv.imgcodecs.Imgcodecs;\nimport org.opencv.imgproc.Imgproc;\npublic class ImageErosion extends Application {\n public void start(Stage stage) throws IOException {\n //Loading the OpenCV core library\n System.loadLibrary( Core.NATIVE_LIBRARY_NAME );\n //Reading image data\n String file =\"D:\\\\Images\\\\lamma2.jpg\";\n Mat src = Imgcodecs.imread(file);\n //Creating destination matrix\n Mat dst = new Mat(src.rows(), src.cols(), src.type());\n //Preparing the kernel matrix object\n Mat kernel = Imgproc.getStructuringElement(Imgproc.MORPH_RECT, new Size((2*2) + 1, (2*2)+1));\n //Applying erosion on the Image\n Imgproc.erode(src, dst, kernel);\n //Converting matrix to JavaFX writable image\n Image img = HighGui.toBufferedImage(dst);\n WritableImage writableImage= SwingFXUtils.toFXImage((BufferedImage) img, null);\n //Setting the image view\n ImageView imageView = new ImageView(writableImage);\n imageView.setX(10);\n imageView.setY(10);\n imageView.setFitWidth(575);\n imageView.setPreserveRatio(true);\n //Setting the Scene object\n Group root = new Group(imageView);\n Scene scene = new Scene(root, 595, 400);\n stage.setTitle(\"Erosion Example\");\n stage.setScene(scene);\n stage.show();\n }\n public static void main(String args[]) {\n launch(args);\n }\n}" }, { "code": null, "e": 3510, "s": 3445, "text": "On executing, the above program generates the following output −" } ]
Change the color of certain words in the tkinter text widget - GeeksforGeeks
01 Aug, 2020 Python has various options for Graphical User Interface (GUI) development. One of the options is Tkinter. Tkinter and Python together provide a faster way for GUI development. The Tk GUI toolkit provides an object-oriented interface. For creating GUI applications using Tkinter we have to follow a few steps – Import Tkinter module. Create the main window. Add various widgets to the GUI application as per requirements. Main event loop for every trigger by the user for performing specific actions. Text widgets have advanced options for editing a text with multiple lines and format the display settings of that text example font, text color, background color. We can also use tabs and marks for locating and editing sections of data. We can also use images in the text and insert borders as well. And everything can be formatted as per the requirements. Syntax : Text ( master, option, ... ) Parameters : master represents parent window and option represents various widget options. They can be given as key-value pairs separated by commas. Return : Return a Text object. Example 1 : In first example we will add a tag to a section of text by specifying the indices and highlight the selected text. Here, we are using tag_add and tag_config. Python3 # import all functions from the tkinterfrom tkinter import * # Create a GUI window root = Tk() # Create a text area box # for filling or typing the information.text = Text(root) # insert given string in text areatext.insert(INSERT, "Hello, everyone!\n") text.insert(END, "This is 2020.\n") text.insert(END, "Pandemic has resulted in economic slowdown worldwide") text.pack(expand=1, fill=BOTH) # add tag using indices for the# part of text to be highlightedtext.tag_add("start", "2.8", "1.13") #configuring a tag called starttext.tag_config("start", background="black", foreground="red") # start the GUIroot.mainloop() Output : Example 2 : In this example, user can highlight text as per their wish by selecting the text to be highlighted. Here, we are using tag_configure and tag_add. Python3 # import all functions from the tkinter import tkinter as tkfrom tkinter.font import Font # create a Pad classclass Pad(tk.Frame): # constructor to add buttons and text to the window def __init__(self, parent, *args, **kwargs): tk.Frame.__init__(self, parent, *args, **kwargs) self.toolbar = tk.Frame(self, bg="#eee") self.toolbar.pack(side="top", fill="x") # this will add Highlight button in the window self.bold_btn = tk.Button(self.toolbar, text="Highlight", command=self.highlight_text) self.bold_btn.pack(side="left") # this will add Clear button in the window self.clear_btn = tk.Button(self.toolbar, text="Clear", command=self.clear) self.clear_btn.pack(side="left") # adding the text self.text = tk.Text(self) self.text.insert("end", "Pandemic has resulted in economic slowdown worldwide") self.text.focus() self.text.pack(fill="both", expand=True) #configuring a tag called start self.text.tag_configure("start", background="black", foreground="red") # method to highlight the selected text def highlight_text(self): # if no text is selected then tk.TclError exception occurs try: self.text.tag_add("start", "sel.first", "sel.last") except tk.TclError: pass # method to clear all contents from text widget. def clear(self): self.text.tag_remove("start", "1.0", 'end') # functiondef demo(): # Create a GUI window root = tk.Tk() # place Pad object in the root window Pad(root).pack(expand=1, fill="both") # start the GUI root.mainloop() # Driver codeif __name__ == "__main__": # function calling demo() Output : Before selecting the text and hitting the highlight button : After selecting the text and hitting the highlight button : Python-tkinter Python Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments How to Install PIP on Windows ? How to drop one or multiple columns in Pandas Dataframe How To Convert Python Dictionary To JSON? Check if element exists in list in Python Python | Pandas dataframe.groupby() Defaultdict in Python Python | Get unique values from a list Python Classes and Objects Python | os.path.join() method Create a directory in Python
[ { "code": null, "e": 23926, "s": 23898, "text": "\n01 Aug, 2020" }, { "code": null, "e": 24160, "s": 23926, "text": "Python has various options for Graphical User Interface (GUI) development. One of the options is Tkinter. Tkinter and Python together provide a faster way for GUI development. The Tk GUI toolkit provides an object-oriented interface." }, { "code": null, "e": 24236, "s": 24160, "text": "For creating GUI applications using Tkinter we have to follow a few steps –" }, { "code": null, "e": 24259, "s": 24236, "text": "Import Tkinter module." }, { "code": null, "e": 24283, "s": 24259, "text": "Create the main window." }, { "code": null, "e": 24347, "s": 24283, "text": "Add various widgets to the GUI application as per requirements." }, { "code": null, "e": 24426, "s": 24347, "text": "Main event loop for every trigger by the user for performing specific actions." }, { "code": null, "e": 24784, "s": 24426, "text": "Text widgets have advanced options for editing a text with multiple lines and format the display settings of that text example font, text color, background color. We can also use tabs and marks for locating and editing sections of data. We can also use images in the text and insert borders as well. And everything can be formatted as per the requirements. " }, { "code": null, "e": 24822, "s": 24784, "text": "Syntax : Text ( master, option, ... )" }, { "code": null, "e": 24971, "s": 24822, "text": "Parameters : master represents parent window and option represents various widget options. They can be given as key-value pairs separated by commas." }, { "code": null, "e": 25004, "s": 24971, "text": "Return : Return a Text object. " }, { "code": null, "e": 25175, "s": 25004, "text": "Example 1 : In first example we will add a tag to a section of text by specifying the indices and highlight the selected text. Here, we are using tag_add and tag_config. " }, { "code": null, "e": 25183, "s": 25175, "text": "Python3" }, { "code": "# import all functions from the tkinterfrom tkinter import * # Create a GUI window root = Tk() # Create a text area box # for filling or typing the information.text = Text(root) # insert given string in text areatext.insert(INSERT, \"Hello, everyone!\\n\") text.insert(END, \"This is 2020.\\n\") text.insert(END, \"Pandemic has resulted in economic slowdown worldwide\") text.pack(expand=1, fill=BOTH) # add tag using indices for the# part of text to be highlightedtext.tag_add(\"start\", \"2.8\", \"1.13\") #configuring a tag called starttext.tag_config(\"start\", background=\"black\", foreground=\"red\") # start the GUIroot.mainloop()", "e": 25843, "s": 25183, "text": null }, { "code": null, "e": 25854, "s": 25843, "text": "Output : " }, { "code": null, "e": 26014, "s": 25854, "text": "Example 2 : In this example, user can highlight text as per their wish by selecting the text to be highlighted. Here, we are using tag_configure and tag_add. " }, { "code": null, "e": 26022, "s": 26014, "text": "Python3" }, { "code": "# import all functions from the tkinter import tkinter as tkfrom tkinter.font import Font # create a Pad classclass Pad(tk.Frame): # constructor to add buttons and text to the window def __init__(self, parent, *args, **kwargs): tk.Frame.__init__(self, parent, *args, **kwargs) self.toolbar = tk.Frame(self, bg=\"#eee\") self.toolbar.pack(side=\"top\", fill=\"x\") # this will add Highlight button in the window self.bold_btn = tk.Button(self.toolbar, text=\"Highlight\", command=self.highlight_text) self.bold_btn.pack(side=\"left\") # this will add Clear button in the window self.clear_btn = tk.Button(self.toolbar, text=\"Clear\", command=self.clear) self.clear_btn.pack(side=\"left\") # adding the text self.text = tk.Text(self) self.text.insert(\"end\", \"Pandemic has resulted in economic slowdown worldwide\") self.text.focus() self.text.pack(fill=\"both\", expand=True) #configuring a tag called start self.text.tag_configure(\"start\", background=\"black\", foreground=\"red\") # method to highlight the selected text def highlight_text(self): # if no text is selected then tk.TclError exception occurs try: self.text.tag_add(\"start\", \"sel.first\", \"sel.last\") except tk.TclError: pass # method to clear all contents from text widget. def clear(self): self.text.tag_remove(\"start\", \"1.0\", 'end') # functiondef demo(): # Create a GUI window root = tk.Tk() # place Pad object in the root window Pad(root).pack(expand=1, fill=\"both\") # start the GUI root.mainloop() # Driver codeif __name__ == \"__main__\": # function calling demo()", "e": 27870, "s": 26022, "text": null }, { "code": null, "e": 27879, "s": 27870, "text": "Output :" }, { "code": null, "e": 27940, "s": 27879, "text": "Before selecting the text and hitting the highlight button :" }, { "code": null, "e": 28000, "s": 27940, "text": "After selecting the text and hitting the highlight button :" }, { "code": null, "e": 28017, "s": 28002, "text": "Python-tkinter" }, { "code": null, "e": 28024, "s": 28017, "text": "Python" }, { "code": null, "e": 28122, "s": 28024, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 28131, "s": 28122, "text": "Comments" }, { "code": null, "e": 28144, "s": 28131, "text": "Old Comments" }, { "code": null, "e": 28176, "s": 28144, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 28232, "s": 28176, "text": "How to drop one or multiple columns in Pandas Dataframe" }, { "code": null, "e": 28274, "s": 28232, "text": "How To Convert Python Dictionary To JSON?" }, { "code": null, "e": 28316, "s": 28274, "text": "Check if element exists in list in Python" }, { "code": null, "e": 28352, "s": 28316, "text": "Python | Pandas dataframe.groupby()" }, { "code": null, "e": 28374, "s": 28352, "text": "Defaultdict in Python" }, { "code": null, "e": 28413, "s": 28374, "text": "Python | Get unique values from a list" }, { "code": null, "e": 28440, "s": 28413, "text": "Python Classes and Objects" }, { "code": null, "e": 28471, "s": 28440, "text": "Python | os.path.join() method" } ]
How can we create the MySQL view with ORDER BY clause?
We can use MySQL ORDER BY clause to sort the records in our result set. . To understand GROUP BY clause with views we are creating a view named ‘Info’ using the base table ‘Student_info’ having the following data − mysql> Select * from Student_info; +------+---------+------------+------------+ | id | Name | Address | Subject | +------+---------+------------+------------+ | 101 | YashPal | Amritsar | History | | 105 | Gaurav | Chandigarh | Literature | | 125 | Raman | Shimla | Computers | | 130 | Ram | Jhansi | Computers | | 132 | Shyam | Chandigarh | Economics | | 133 | Mohan | Delhi | Computers | +------+---------+------------+------------+ 6 rows in set (0.00 sec) Create or Replace View view_name AS Select_statements FROM table ORDER BY expression [ASC|DESC] mysql> Create or Replace View Info AS select ID, Name, Address , Subject FROM Student_info ORDER BY Name ASC; Query OK, 0 rows affected (0.11 sec) mysql> Select * from info; +------+---------+------------+------------+ | ID | Name | Address | Subject | +------+---------+------------+------------+ | 105 | Gaurav | Chandigarh | Literature | | 133 | Mohan | Delhi | Computers | | 130 | Ram | Jhansi | Computers | | 125 | Raman | Shimla | Computers | | 132 | Shyam | Chandigarh | Economics | | 101 | YashPal | Amritsar | History | +------+---------+------------+------------+ 6 rows in set (0.00 sec) mysql> Create or Replace View Info AS select ID, Name, Address , Subject FROM Student_info ORDER BY Name DESC; Query OK, 0 rows affected (0.10 sec) mysql> Select * from info; +------+---------+------------+------------+ | ID | Name | Address | Subject | +------+---------+------------+------------+ | 101 | YashPal | Amritsar | History | | 132 | Shyam | Chandigarh | Economics | | 125 | Raman | Shimla | Computers | | 130 | Ram | Jhansi | Computers | | 133 | Mohan | Delhi | Computers | | 105 | Gaurav | Chandigarh | Literature | +------+---------+------------+------------+ 6 rows in set (0.00 sec)
[ { "code": null, "e": 1277, "s": 1062, "text": "We can use MySQL ORDER BY clause to sort the records in our result set. . To understand GROUP BY clause with views we are creating a view named ‘Info’ using the base table ‘Student_info’ having the following data −" }, { "code": null, "e": 1787, "s": 1277, "text": "mysql> Select * from Student_info;\n+------+---------+------------+------------+\n| id | Name | Address | Subject |\n+------+---------+------------+------------+\n| 101 | YashPal | Amritsar | History |\n| 105 | Gaurav | Chandigarh | Literature |\n| 125 | Raman | Shimla | Computers |\n| 130 | Ram | Jhansi | Computers |\n| 132 | Shyam | Chandigarh | Economics |\n| 133 | Mohan | Delhi | Computers |\n+------+---------+------------+------------+\n6 rows in set (0.00 sec)" }, { "code": null, "e": 1883, "s": 1787, "text": "Create or Replace View view_name AS Select_statements FROM table ORDER BY expression [ASC|DESC]" }, { "code": null, "e": 3185, "s": 1883, "text": "mysql> Create or Replace View Info AS select ID, Name, Address , Subject FROM Student_info ORDER BY Name ASC;\nQuery OK, 0 rows affected (0.11 sec)\n\nmysql> Select * from info;\n+------+---------+------------+------------+\n| ID | Name | Address | Subject |\n+------+---------+------------+------------+\n| 105 | Gaurav | Chandigarh | Literature |\n| 133 | Mohan | Delhi | Computers |\n| 130 | Ram | Jhansi | Computers |\n| 125 | Raman | Shimla | Computers |\n| 132 | Shyam | Chandigarh | Economics |\n| 101 | YashPal | Amritsar | History |\n+------+---------+------------+------------+\n6 rows in set (0.00 sec)\n\nmysql> Create or Replace View Info AS select ID, Name, Address , Subject FROM Student_info ORDER BY Name DESC;\nQuery OK, 0 rows affected (0.10 sec)\n\nmysql> Select * from info;\n+------+---------+------------+------------+\n| ID | Name | Address | Subject |\n+------+---------+------------+------------+\n| 101 | YashPal | Amritsar | History |\n| 132 | Shyam | Chandigarh | Economics |\n| 125 | Raman | Shimla | Computers |\n| 130 | Ram | Jhansi | Computers |\n| 133 | Mohan | Delhi | Computers |\n| 105 | Gaurav | Chandigarh | Literature |\n+------+---------+------------+------------+\n6 rows in set (0.00 sec)" } ]
Make computations on cross joined Spark DataFrames faster | Towards Data Science
Apache Spark splits data into partitions and performs tasks on these partitions in parallel to make your computations run concurrently. The number of partitions has a direct impact on the run time of Spark computations. Often times your Spark computations involve cross joining two Spark DataFrames i.e. creating a new DataFrame containing a combination of every row from the two input DataFrames. Spark multiplies the number of partitions of the input DataFrames when cross joining large DataFrames. This can result in a significantly higher number of partitions in the cross joined DataFrame. As a result, running computations on this DataFrame can be very slow due to excessive overhead in managing many small tasks on the partitions. This blog post will demonstrate how repartitioning the large input DataFrames with a smaller number of partitions before cross join can make computations on the resulting cross joined DataFrame faster. Let's consider two scenarios to understand how partitioning works when cross joining DataFrames: If your input DataFrames are smaller in size, then the cross joined DataFrame would have partitions equal to the number of the partitions of the input DataFrame. scala> val xDF = (1 to 1000).toList.toDF("x")scala> xDF.rdd.partitions.sizeres11: Int = 2scala> val yDF = (1 to 1000).toList.toDF("y")scala> yDF.rdd.partitions.sizeres12: Int = 2scala> val crossJoinDF = xDF.crossJoin(yDF)scala> crossJoinDF.rdd.partitions.sizeres13: Int = 2 In this case, Partitions of xDF == Partitions of yDF == Partitions of crossJoinDF If the partitions of input DataFrames, i.e xDF or yDF are not equal, then the partitions of the cross joined DataFrame would be equal to one of the input DataFrames. If we increase the data size of the input DataFrames, the partitioning behavior on the cross joined DataFrame changes. In the following example, I have increased the number of rows in input DataFrames from 1000 to 1,000,000 scala> val xDF = (1 to 1000000).toList.toDF("x")scala> xDF.rdd.partitions.sizeres15: Int = 2scala> val yDF = (1 to 1000000).toList.toDF("y")scala> yDF.rdd.partitions.sizeres16: Int = 2scala> val crossJoinDF = xDF.crossJoin(yDF)scala> crossJoinDF.rdd.partitions.sizeres17: Int = 4 In this scenario, the partition size of the cross joined DataFrame is equal to the multiplication of input DataFrames partition Partitions of crossJoinDF = (Partitions of xDF) * (Partitions of yDF). If your input DataFrame has more columns or larger data types, you would be able to replicate this behavior on a DataFrame with few thousand rows as well. The exact number of partitions for a DataFrame vary depending upon your hardware but the cross multiplication of partitions when cross joining large DataFrames is consistent across all types of hardware. If your input DataFrame contains few hundred partitions (~100), which is typically the case when dealing with big data, then the cross joined DataFrame would have partitions in the order of ~ 10,000. The number of DataFrame partitions has an impact on the run time of your computations: If you have too few partitions, your computations will not be able to utilize all the parallelism available in the cluster. If you have too many partitions, there will be excessive overhead in managing many small tasks, making your computations very slow to run. Cross joining large DataFrames with few 100 partitions falls into the latter case, which results in a DataFrame with too many partitions in the order of 10,000. This makes any operations on the cross joined DataFrame very slow. You might encounter the following exception, when running operations on cross joined DataFrame with a lot of partitions: org.apache.spark.SparkException Job aborted due to stage failure: Total size of serialized results of 147936 tasks (1024.0 MB) is bigger than spark.driver.maxResultSize (1024.0 MB) This occurs because Spark is sending status data for each task back to the driver. Since there are lots of partitions (or tasks), this data can often go over the default limit of 1024 MB. Increasing the value of the Spark configuration spark.driver.maxResultSize will make your computation run without throwing the above exception but will not make it any faster. The inherent problem of large number of partitions still persists. To make the computation faster, reduce the number of partitions of the input DataFrames before the cross join, so that the resulting cross joined DataFrame doesn’t have too many partitions. As a real world example, I need to cross join two DataFrames df1 and df2 to compute cosine similarity between every combination of the rows from two DataFrames. Both the DataFrames consist of text and an array of doubles of length 500, representing text embeddings. DataFrame df1 consists of about 60,000 rows and DataFrame df2 consists of 130,000 rows. Running count on cross joined DataFrame takes about 6 hrs on AWS Glue with 40 Workers of type G.1X. Re-partitioning df1 and df2 into smaller number of partitions before cross join reduces the time to compute count on cross joined DataFrame to 40 mins! For the purpose of illustration, I will take a small sample of df1 and df2 DataFrames. Cross joining df1 containing 17,000 rows and 200 partitions with df2 containing 15,000 rows and 200 partitions, creates a cross joined DataFrame with 40,000 partitions. Running a count on cross joined DataFrame takes 285,163,427,988 ns i.e 4.75 minutes. Following code was executed on AWS Glue running with 40 workers with type G1.X using Spark 2.4 scala> df1.count()res73: Long = 17000scala> df1.show(4)+---------------------------+--------------------+| text| text_embedding|+---------------------------+--------------------+|eiffel tower location |[0.4, 0.02, 0.1, ...||pounds kilogram conversion |[0.01, 0.2, 0.1, ...||capital of spain |[0.05, 0.2, 0.2, ...||mount everest height |[0.07, 0.1, 0.1, ...|+---------------------------+--------------------+scala> df1.rdd.partitions.sizeres74: Int = 200scala> df2.count()res75: Long = 15000scala> df2.rdd.partitions.sizeres76: Int = 200scala> df2.show(4)+------------------------------+--------------------+| text| text_embedding|+------------------------------+--------------------+|where is eiffel tower located |[0.3, 0.01, 0.1, ...||how many pounds in a kilogram |[0.02, 0.2, 0.1, ...||what is the capital of spain |[0.03, 0.2, 0.2, ...||how tall is mount everest |[0.06, 0.1, 0.1, ...|+------------------------------+--------------------+scala> val finalDF = df1.crossJoin(df2)scala> finalDF.rdd.partitions.size res77: Int = 40000scala> time {finalDF.count()}Elapsed time: 285163427988nsres78: Long = 255000000 If we reduce the number of partitions on df1 and df2 to 40 before executing the cross join, the time to run count on the cross joined DataFrame reduces to 47,178,149,994 ns i.e 47 seconds! We chose 40 partitions to utilize all the parallelism available in 40 worker cluster. scala> val df1 = df1.repartition(40)scala> df1.rdd.partitions.size res80: Int = 40scala> val df2 = df2.repartition(40)scala> df2.rdd.partitions.size res81: Int = 40scala> val finalDF = df1.crossJoin(df2)scala> finalDF.rdd.partitions.size res82: Int = 1600scala> time {finalDF.count()}Elapsed time: 47178149994nsres86: Long = 255000000 Lowering the number of partitions before cross joining the DataFrames reduces the time to compute count on cross joined DataFrame by 6x on this sample data! Next time you find Spark computations slow after performing a cross join, do check the number of partitions on the cross joined DataFrame. If it has too many partitions, reduce the number of partitions on the input DataFrames to speed up operations on the resulting cross joined DataFrame.
[ { "code": null, "e": 1211, "s": 171, "text": "Apache Spark splits data into partitions and performs tasks on these partitions in parallel to make your computations run concurrently. The number of partitions has a direct impact on the run time of Spark computations. Often times your Spark computations involve cross joining two Spark DataFrames i.e. creating a new DataFrame containing a combination of every row from the two input DataFrames. Spark multiplies the number of partitions of the input DataFrames when cross joining large DataFrames. This can result in a significantly higher number of partitions in the cross joined DataFrame. As a result, running computations on this DataFrame can be very slow due to excessive overhead in managing many small tasks on the partitions. This blog post will demonstrate how repartitioning the large input DataFrames with a smaller number of partitions before cross join can make computations on the resulting cross joined DataFrame faster. Let's consider two scenarios to understand how partitioning works when cross joining DataFrames:" }, { "code": null, "e": 1373, "s": 1211, "text": "If your input DataFrames are smaller in size, then the cross joined DataFrame would have partitions equal to the number of the partitions of the input DataFrame." }, { "code": null, "e": 1647, "s": 1373, "text": "scala> val xDF = (1 to 1000).toList.toDF(\"x\")scala> xDF.rdd.partitions.sizeres11: Int = 2scala> val yDF = (1 to 1000).toList.toDF(\"y\")scala> yDF.rdd.partitions.sizeres12: Int = 2scala> val crossJoinDF = xDF.crossJoin(yDF)scala> crossJoinDF.rdd.partitions.sizeres13: Int = 2" }, { "code": null, "e": 1895, "s": 1647, "text": "In this case, Partitions of xDF == Partitions of yDF == Partitions of crossJoinDF If the partitions of input DataFrames, i.e xDF or yDF are not equal, then the partitions of the cross joined DataFrame would be equal to one of the input DataFrames." }, { "code": null, "e": 2119, "s": 1895, "text": "If we increase the data size of the input DataFrames, the partitioning behavior on the cross joined DataFrame changes. In the following example, I have increased the number of rows in input DataFrames from 1000 to 1,000,000" }, { "code": null, "e": 2399, "s": 2119, "text": "scala> val xDF = (1 to 1000000).toList.toDF(\"x\")scala> xDF.rdd.partitions.sizeres15: Int = 2scala> val yDF = (1 to 1000000).toList.toDF(\"y\")scala> yDF.rdd.partitions.sizeres16: Int = 2scala> val crossJoinDF = xDF.crossJoin(yDF)scala> crossJoinDF.rdd.partitions.sizeres17: Int = 4" }, { "code": null, "e": 2958, "s": 2399, "text": "In this scenario, the partition size of the cross joined DataFrame is equal to the multiplication of input DataFrames partition Partitions of crossJoinDF = (Partitions of xDF) * (Partitions of yDF). If your input DataFrame has more columns or larger data types, you would be able to replicate this behavior on a DataFrame with few thousand rows as well. The exact number of partitions for a DataFrame vary depending upon your hardware but the cross multiplication of partitions when cross joining large DataFrames is consistent across all types of hardware." }, { "code": null, "e": 3246, "s": 2958, "text": "If your input DataFrame contains few hundred partitions (~100), which is typically the case when dealing with big data, then the cross joined DataFrame would have partitions in the order of ~ 10,000. The number of DataFrame partitions has an impact on the run time of your computations:" }, { "code": null, "e": 3370, "s": 3246, "text": "If you have too few partitions, your computations will not be able to utilize all the parallelism available in the cluster." }, { "code": null, "e": 3509, "s": 3370, "text": "If you have too many partitions, there will be excessive overhead in managing many small tasks, making your computations very slow to run." }, { "code": null, "e": 3858, "s": 3509, "text": "Cross joining large DataFrames with few 100 partitions falls into the latter case, which results in a DataFrame with too many partitions in the order of 10,000. This makes any operations on the cross joined DataFrame very slow. You might encounter the following exception, when running operations on cross joined DataFrame with a lot of partitions:" }, { "code": null, "e": 4039, "s": 3858, "text": "org.apache.spark.SparkException Job aborted due to stage failure: Total size of serialized results of 147936 tasks (1024.0 MB) is bigger than spark.driver.maxResultSize (1024.0 MB)" }, { "code": null, "e": 4471, "s": 4039, "text": "This occurs because Spark is sending status data for each task back to the driver. Since there are lots of partitions (or tasks), this data can often go over the default limit of 1024 MB. Increasing the value of the Spark configuration spark.driver.maxResultSize will make your computation run without throwing the above exception but will not make it any faster. The inherent problem of large number of partitions still persists." }, { "code": null, "e": 5609, "s": 4471, "text": "To make the computation faster, reduce the number of partitions of the input DataFrames before the cross join, so that the resulting cross joined DataFrame doesn’t have too many partitions. As a real world example, I need to cross join two DataFrames df1 and df2 to compute cosine similarity between every combination of the rows from two DataFrames. Both the DataFrames consist of text and an array of doubles of length 500, representing text embeddings. DataFrame df1 consists of about 60,000 rows and DataFrame df2 consists of 130,000 rows. Running count on cross joined DataFrame takes about 6 hrs on AWS Glue with 40 Workers of type G.1X. Re-partitioning df1 and df2 into smaller number of partitions before cross join reduces the time to compute count on cross joined DataFrame to 40 mins! For the purpose of illustration, I will take a small sample of df1 and df2 DataFrames. Cross joining df1 containing 17,000 rows and 200 partitions with df2 containing 15,000 rows and 200 partitions, creates a cross joined DataFrame with 40,000 partitions. Running a count on cross joined DataFrame takes 285,163,427,988 ns i.e 4.75 minutes." }, { "code": null, "e": 5704, "s": 5609, "text": "Following code was executed on AWS Glue running with 40 workers with type G1.X using Spark 2.4" }, { "code": null, "e": 6903, "s": 5704, "text": "scala> df1.count()res73: Long = 17000scala> df1.show(4)+---------------------------+--------------------+| text| text_embedding|+---------------------------+--------------------+|eiffel tower location |[0.4, 0.02, 0.1, ...||pounds kilogram conversion |[0.01, 0.2, 0.1, ...||capital of spain |[0.05, 0.2, 0.2, ...||mount everest height |[0.07, 0.1, 0.1, ...|+---------------------------+--------------------+scala> df1.rdd.partitions.sizeres74: Int = 200scala> df2.count()res75: Long = 15000scala> df2.rdd.partitions.sizeres76: Int = 200scala> df2.show(4)+------------------------------+--------------------+| text| text_embedding|+------------------------------+--------------------+|where is eiffel tower located |[0.3, 0.01, 0.1, ...||how many pounds in a kilogram |[0.02, 0.2, 0.1, ...||what is the capital of spain |[0.03, 0.2, 0.2, ...||how tall is mount everest |[0.06, 0.1, 0.1, ...|+------------------------------+--------------------+scala> val finalDF = df1.crossJoin(df2)scala> finalDF.rdd.partitions.size res77: Int = 40000scala> time {finalDF.count()}Elapsed time: 285163427988nsres78: Long = 255000000" }, { "code": null, "e": 7178, "s": 6903, "text": "If we reduce the number of partitions on df1 and df2 to 40 before executing the cross join, the time to run count on the cross joined DataFrame reduces to 47,178,149,994 ns i.e 47 seconds! We chose 40 partitions to utilize all the parallelism available in 40 worker cluster." }, { "code": null, "e": 7513, "s": 7178, "text": "scala> val df1 = df1.repartition(40)scala> df1.rdd.partitions.size res80: Int = 40scala> val df2 = df2.repartition(40)scala> df2.rdd.partitions.size res81: Int = 40scala> val finalDF = df1.crossJoin(df2)scala> finalDF.rdd.partitions.size res82: Int = 1600scala> time {finalDF.count()}Elapsed time: 47178149994nsres86: Long = 255000000" }, { "code": null, "e": 7670, "s": 7513, "text": "Lowering the number of partitions before cross joining the DataFrames reduces the time to compute count on cross joined DataFrame by 6x on this sample data!" } ]
Construct tree from Inorder and LevelOrder | Practice | GeeksforGeeks
Given inorder and level-order traversals of a Binary Tree, construct the Binary Tree and return the root Node. Input: First line consists of T test cases. First line of every test case consists of N, denoting number of elements is respective arrays. Second and third line consists of arrays containing Inorder and Level-order traversal respectively. Output: Single line output, print the preOrder traversal of array. Constraints: 1<=T<=100 1<=N<=100 Example: Input: 2 3 1 0 2 0 1 2 7 3 1 4 0 5 2 6 0 1 2 3 4 5 6 Output: 0 1 2 0 1 3 4 2 5 6 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": 350, "s": 238, "text": "Given inorder and level-order traversals of a Binary Tree, construct the Binary Tree and return the root Node. " }, { "code": null, "e": 589, "s": 350, "text": "Input:\nFirst line consists of T test cases. First line of every test case consists of N, denoting number of elements is respective arrays. Second and third line consists of arrays containing Inorder and Level-order traversal respectively." }, { "code": null, "e": 656, "s": 589, "text": "Output:\nSingle line output, print the preOrder traversal of array." }, { "code": null, "e": 689, "s": 656, "text": "Constraints:\n1<=T<=100\n1<=N<=100" }, { "code": null, "e": 783, "s": 689, "text": "Example:\nInput:\n2\n3\n1 0 2 \n0 1 2 \n7\n3 1 4 0 5 2 6 \n0 1 2 3 4 5 6 \nOutput:\n0 1 2\n0 1 3 4 2 5 6" }, { "code": null, "e": 929, "s": 783, "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": 965, "s": 929, "text": " Login to access your submissions. " }, { "code": null, "e": 975, "s": 965, "text": "\nProblem\n" }, { "code": null, "e": 985, "s": 975, "text": "\nContest\n" }, { "code": null, "e": 1048, "s": 985, "text": "Reset the IDE using the second button on the top right corner." }, { "code": null, "e": 1196, "s": 1048, "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": 1404, "s": 1196, "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": 1510, "s": 1404, "text": "You can access the hints to get an idea about what is expected of you as well as the final solution code." } ]
Reinforcement Learning in Simulations | by Ben Goldhaber | Towards Data Science
Reinforcement Learning (RL) is a way to teach an agent how to behave in an environment by rewarding it when it does well and penalizing it when it does poorly. Using RL, you can create complex agents that figure out ‘on their own’ optimal strategies to follow in a simulation. These strategies (or policies) can then be applied to real world situations. Reinforcement learning has the potential to transform how we build and use simulations. HASH as a platform is designed to help you leverage advances in the field of ML/RL and apply them directly within your simulations. We’ve created a demonstration in HASH using a simple reinforcement learning algorithm called Q-Learning that agents can use to navigate a two-dimensional environment, avoid obstacles, and get to an end goal. You can follow along in our example simulation (linked and below), or use the Q-Learning behavior library we’ve published to experiment with it in your own RL simulations. The basic structure of a reinforcement learning simulation is an agent decides what actions to take in a given time step in its environment; it executes the action, updating the state of the agent and its surrounding, and receives a reward which can then update the policy the agent uses to select actions. This loop continues until the agent either reaches the goal, hits an obstacle, or until a set number of time steps have passed; once either condition is met the simulation resets and repeats. However the policy the agent is using will be preserved, and updated every episode. After many runs (or episodes) the agent’s policy should converge to an optimal set of actions that are best suited for maximizing its reward. Let’s break down the different parts of the simulation and see how they fit into this RL framework. Gridworld: The 2D environment we’ll create for the agent to operate in is called ‘gridworld’. This is a common testing and demo environment for experimenting with reinforcement learning algorithms. It’s a two dimensional space populated with blocks that represent obstacles or goals. If the agent lands on an obstacle, it’s penalized. If it gets to the goal state, the agent is rewarded. The parameters for the environment are defined in globals.json in the gridworld object. In the initialization file, init.py, the environment is created from these parameters. The agent is initialized with a set of behaviors: [“validate_action.py”, “action.py”, “move.py”, “reward.py”, “update_q.py”, “control.py”] Each behavior represents a part of the reinforcement learning loop. It also contains fields for storing reward information and parameters applicable to the RL update algorithm. agent = { "behaviors": [“validate_action.py”, "action.py", "move.py", "reward.py", "update_q.py", "control.py"], "agent_name": "rl", "q_table": q_table, "actions": actions, "position": [2, 0], "reward": 0, "episode_reward": 0, "episode": 0, "rewards": [], "episodes": [], "epsilon": context.globals()["epsilon"], "learning_rate": context.globals()["learning_rate"], "steps": 1} Validate_actions.py Every timestep the agent can consider taking one of four actions — it can move up, down, right, or left. actions = [ [1, 0], [0, 1], [-1, 0], [0, -1] ] At certain positions in gridworld, some of these actions would take it outside the bounds of our simulation. To prevent that, this behavior filters all possible actions to a subset of valid actions. It then stores these in state[“actions”]. action.py The agent now chooses which action to take based on how well a given action has historically performed in the long run, on average, at that position. The ‘quality’ of an action in a given location is stored in the agent’s q_table; over many runs it will develop an accurate valuation of actions at specific spots. The policy of a Q-Learning agent can be thought of as the collection of values in its q_table (along with how it samples those values) Note: The q_table is an array of arrays; the first level represents locations in the gridworld, the second level represents actions. The value of [location] [action] is a ‘quality’ score. To make this more concrete, consider the scenario where the agent is in (6,8), next to the goal on its right. The optimal action is clearly to take the action (1,0) which will move the agent on to the goal state at (7,8). So the quality value of the action (1,0) at state (6,8) should be high, at least relative to all the other actions it could select from. However, at the start, when the agent has no idea whether an action is good at a specific location, how does it choose which to execute? How does it learn that (1,0) is a good choice? And finally, how do we prevent an agent from prematurely optimizing and choosing an action that might appear good, but is not in fact as good as another possible choice? This is a classic problem in reinforcement learning — and life in general — called the explore-exploit tradeoff. We want the agent to explore enough that we can be confident it has relatively correct q-values for a given action at a given location, but eventually we want the agent to start to choose the best action. With Q-Learning, this tradeoff is handled by a hyperparameter in the simulation called epsilon, which is defined in globals.json and is then stored on the agent as an attribute at the start of the simulation. Every timestep, when choosing an action, the agent randomly generates a number between and 1. If the value is less than the value of epsilon the agent will randomly select one of the four actions; if the value is greater than epsilon, the agent will select the action that has the highest q-value. # If exploiting, select best action from q_table exploit = random.random() > state["epsilon"] if exploit: q_values = state["q_table"][state["q_state"]] state["action"] = context.globals()["actions"][int(argmax(q_values))] # Else select a random action from potential actions else: state["action"] = state["actions"][random.choice(len(state["actions"]))] You can use the HASH optimization engine to automatically optimize hyperparameters to find the set that best selects actions. reward.py After the agent has decided on an action, it can compute the outcome of that action and receive a reward based on the new state of the simulation. In this simulation, there are three potential reward adjustments. If the agent encounters an obstacle, the reward is decreased by the value of obstacle_penalty. If the agent gets to the goal, the reward is increased by the value of the goal_reward. Else, every time step where the agent hasn’t hit an obstacle or a goal, the agent’s cumulative reward decreases by the move_penalty. Adding a cost to moves is important as it incentivizes the agent to find the shortest path to the goal state. update_q.py The heart of the Q-learning algorithm is the q_table and the update function. We already described the q_table - an array of arrays storing scores for actions at locations - and the update function is how the scores are set and modified. After the state is set (i.e. the action has been executed) and the reward received, the agent retrieves the maximum future q_score available from that state, and then uses this in conjunction with any rewards received to set the q_score of the action. The intuition here is that the value of a particular action depends both on the immediate rewards/penalties the agent receives from it, and from how well it opens up future highly valuable actions to take. Actions that may, in the moment, be more costly than another action — for instance moving farther away from the goal state — might still be a higher quality action to take — for instance if it avoids a set of obstacles. The relative value of immediate rewards vs future rewards are determined by the discount_factor hyperparameter — a higher discount_factor represents a preference for rewards in the future over rewards on that timestep. Additionally the learning_rate hyperparameter determines how much of an update to make to the existing q_value. A high learning_rate means it will update more, a low learning rate means it will update less from a score in a specific episode. control.py Control handles the ‘meta’ part of the simulation. Once the agent has reached a stop point, either because it hit an obstacle, found the goal, or ran out of time, we want to reset the agent back to the starting point and adjust the hyperparameters, decaying epsilon and the learning rate. control.py checks if the steps are equal to an episode length or if the agent’s state is done, and if so saves the reward for that episode (useful for plotting the convergence of the agents algorithm), sets the agent back to the start position, and then multiplies the epsilon and learning by a decay value. move.py, control.py Action, Reward, Update, and Control are the general framework common to almost all reinforcement learning simulations. The specific behavior names might change, but the pattern remains the same. But, outside of this design pattern, there are context specific behaviors an agent will want to execute for its given environment. In this simulation, this is move.py, which handles actually taking the action selected by the agent and executing it in the new environment. When we run the simulation, we can see in the 3D viewer the agent moving about and landing on obstacles or the goal, being reset, and starting over. Over hundreds of runs, its q_table values reflect quality scores that, as it begins to exploit more than explore, will guide it more frequently to the goal state while avoiding obstacles. To get a more quantitative measure of how the agent is performing, switch to the analysis view and watch the rewards per episode increasingly converge to a steady state positive value. The speed at which the agent converges to a steady, positive reward state will be determined in large part by the hyperparameters of the simulation. The reward size, penalty size, epsilon, etc. will all affect the behavior of the agent. You can try manually setting different values in global and see what happens, or you can use the HASH optimization engine to select hyperparameters that maximize the reward. To build your own RL simulations with HASH, you can experiment with the library of RL behaviors shared from this simulation. They contain generic versions of the action, reward, and update behaviors — you can use the Q-learning algorithm or implement your own custom algorithm. And while they’re by no means a replacement for the full fledged RL implementations you’ll find in frameworks like Tensorflow or PyTorch, they’re a great way to start experimenting with RL. Over the coming months we’ll be releasing HASH’s long-awaited hEngine, together with specific reinforcement learning features, including support for external frameworks, making it as easy as possible to add powerful learning capabilities to your simulations.
[ { "code": null, "e": 526, "s": 172, "text": "Reinforcement Learning (RL) is a way to teach an agent how to behave in an environment by rewarding it when it does well and penalizing it when it does poorly. Using RL, you can create complex agents that figure out ‘on their own’ optimal strategies to follow in a simulation. These strategies (or policies) can then be applied to real world situations." }, { "code": null, "e": 746, "s": 526, "text": "Reinforcement learning has the potential to transform how we build and use simulations. HASH as a platform is designed to help you leverage advances in the field of ML/RL and apply them directly within your simulations." }, { "code": null, "e": 1126, "s": 746, "text": "We’ve created a demonstration in HASH using a simple reinforcement learning algorithm called Q-Learning that agents can use to navigate a two-dimensional environment, avoid obstacles, and get to an end goal. You can follow along in our example simulation (linked and below), or use the Q-Learning behavior library we’ve published to experiment with it in your own RL simulations." }, { "code": null, "e": 1433, "s": 1126, "text": "The basic structure of a reinforcement learning simulation is an agent decides what actions to take in a given time step in its environment; it executes the action, updating the state of the agent and its surrounding, and receives a reward which can then update the policy the agent uses to select actions." }, { "code": null, "e": 1851, "s": 1433, "text": "This loop continues until the agent either reaches the goal, hits an obstacle, or until a set number of time steps have passed; once either condition is met the simulation resets and repeats. However the policy the agent is using will be preserved, and updated every episode. After many runs (or episodes) the agent’s policy should converge to an optimal set of actions that are best suited for maximizing its reward." }, { "code": null, "e": 1951, "s": 1851, "text": "Let’s break down the different parts of the simulation and see how they fit into this RL framework." }, { "code": null, "e": 2339, "s": 1951, "text": "Gridworld: The 2D environment we’ll create for the agent to operate in is called ‘gridworld’. This is a common testing and demo environment for experimenting with reinforcement learning algorithms. It’s a two dimensional space populated with blocks that represent obstacles or goals. If the agent lands on an obstacle, it’s penalized. If it gets to the goal state, the agent is rewarded." }, { "code": null, "e": 2514, "s": 2339, "text": "The parameters for the environment are defined in globals.json in the gridworld object. In the initialization file, init.py, the environment is created from these parameters." }, { "code": null, "e": 2564, "s": 2514, "text": "The agent is initialized with a set of behaviors:" }, { "code": null, "e": 2653, "s": 2564, "text": "[“validate_action.py”, “action.py”, “move.py”, “reward.py”, “update_q.py”, “control.py”]" }, { "code": null, "e": 2830, "s": 2653, "text": "Each behavior represents a part of the reinforcement learning loop. It also contains fields for storing reward information and parameters applicable to the RL update algorithm." }, { "code": null, "e": 3235, "s": 2830, "text": "agent = { \"behaviors\": [“validate_action.py”, \"action.py\", \"move.py\", \"reward.py\", \"update_q.py\", \"control.py\"], \"agent_name\": \"rl\", \"q_table\": q_table, \"actions\": actions, \"position\": [2, 0], \"reward\": 0, \"episode_reward\": 0, \"episode\": 0, \"rewards\": [], \"episodes\": [], \"epsilon\": context.globals()[\"epsilon\"], \"learning_rate\": context.globals()[\"learning_rate\"], \"steps\": 1}" }, { "code": null, "e": 3255, "s": 3235, "text": "Validate_actions.py" }, { "code": null, "e": 3360, "s": 3255, "text": "Every timestep the agent can consider taking one of four actions — it can move up, down, right, or left." }, { "code": null, "e": 3420, "s": 3360, "text": "actions = [ [1, 0], [0, 1], [-1, 0], [0, -1] ]" }, { "code": null, "e": 3661, "s": 3420, "text": "At certain positions in gridworld, some of these actions would take it outside the bounds of our simulation. To prevent that, this behavior filters all possible actions to a subset of valid actions. It then stores these in state[“actions”]." }, { "code": null, "e": 3671, "s": 3661, "text": "action.py" }, { "code": null, "e": 4120, "s": 3671, "text": "The agent now chooses which action to take based on how well a given action has historically performed in the long run, on average, at that position. The ‘quality’ of an action in a given location is stored in the agent’s q_table; over many runs it will develop an accurate valuation of actions at specific spots. The policy of a Q-Learning agent can be thought of as the collection of values in its q_table (along with how it samples those values)" }, { "code": null, "e": 4308, "s": 4120, "text": "Note: The q_table is an array of arrays; the first level represents locations in the gridworld, the second level represents actions. The value of [location] [action] is a ‘quality’ score." }, { "code": null, "e": 4418, "s": 4308, "text": "To make this more concrete, consider the scenario where the agent is in (6,8), next to the goal on its right." }, { "code": null, "e": 4667, "s": 4418, "text": "The optimal action is clearly to take the action (1,0) which will move the agent on to the goal state at (7,8). So the quality value of the action (1,0) at state (6,8) should be high, at least relative to all the other actions it could select from." }, { "code": null, "e": 5021, "s": 4667, "text": "However, at the start, when the agent has no idea whether an action is good at a specific location, how does it choose which to execute? How does it learn that (1,0) is a good choice? And finally, how do we prevent an agent from prematurely optimizing and choosing an action that might appear good, but is not in fact as good as another possible choice?" }, { "code": null, "e": 5339, "s": 5021, "text": "This is a classic problem in reinforcement learning — and life in general — called the explore-exploit tradeoff. We want the agent to explore enough that we can be confident it has relatively correct q-values for a given action at a given location, but eventually we want the agent to start to choose the best action." }, { "code": null, "e": 5846, "s": 5339, "text": "With Q-Learning, this tradeoff is handled by a hyperparameter in the simulation called epsilon, which is defined in globals.json and is then stored on the agent as an attribute at the start of the simulation. Every timestep, when choosing an action, the agent randomly generates a number between and 1. If the value is less than the value of epsilon the agent will randomly select one of the four actions; if the value is greater than epsilon, the agent will select the action that has the highest q-value." }, { "code": null, "e": 6213, "s": 5846, "text": "# If exploiting, select best action from q_table exploit = random.random() > state[\"epsilon\"] if exploit: q_values = state[\"q_table\"][state[\"q_state\"]] state[\"action\"] = context.globals()[\"actions\"][int(argmax(q_values))] # Else select a random action from potential actions else: state[\"action\"] = state[\"actions\"][random.choice(len(state[\"actions\"]))]" }, { "code": null, "e": 6339, "s": 6213, "text": "You can use the HASH optimization engine to automatically optimize hyperparameters to find the set that best selects actions." }, { "code": null, "e": 6349, "s": 6339, "text": "reward.py" }, { "code": null, "e": 6496, "s": 6349, "text": "After the agent has decided on an action, it can compute the outcome of that action and receive a reward based on the new state of the simulation." }, { "code": null, "e": 6562, "s": 6496, "text": "In this simulation, there are three potential reward adjustments." }, { "code": null, "e": 6657, "s": 6562, "text": "If the agent encounters an obstacle, the reward is decreased by the value of obstacle_penalty." }, { "code": null, "e": 6745, "s": 6657, "text": "If the agent gets to the goal, the reward is increased by the value of the goal_reward." }, { "code": null, "e": 6878, "s": 6745, "text": "Else, every time step where the agent hasn’t hit an obstacle or a goal, the agent’s cumulative reward decreases by the move_penalty." }, { "code": null, "e": 6988, "s": 6878, "text": "Adding a cost to moves is important as it incentivizes the agent to find the shortest path to the goal state." }, { "code": null, "e": 7000, "s": 6988, "text": "update_q.py" }, { "code": null, "e": 7490, "s": 7000, "text": "The heart of the Q-learning algorithm is the q_table and the update function. We already described the q_table - an array of arrays storing scores for actions at locations - and the update function is how the scores are set and modified. After the state is set (i.e. the action has been executed) and the reward received, the agent retrieves the maximum future q_score available from that state, and then uses this in conjunction with any rewards received to set the q_score of the action." }, { "code": null, "e": 7916, "s": 7490, "text": "The intuition here is that the value of a particular action depends both on the immediate rewards/penalties the agent receives from it, and from how well it opens up future highly valuable actions to take. Actions that may, in the moment, be more costly than another action — for instance moving farther away from the goal state — might still be a higher quality action to take — for instance if it avoids a set of obstacles." }, { "code": null, "e": 8377, "s": 7916, "text": "The relative value of immediate rewards vs future rewards are determined by the discount_factor hyperparameter — a higher discount_factor represents a preference for rewards in the future over rewards on that timestep. Additionally the learning_rate hyperparameter determines how much of an update to make to the existing q_value. A high learning_rate means it will update more, a low learning rate means it will update less from a score in a specific episode." }, { "code": null, "e": 8388, "s": 8377, "text": "control.py" }, { "code": null, "e": 8677, "s": 8388, "text": "Control handles the ‘meta’ part of the simulation. Once the agent has reached a stop point, either because it hit an obstacle, found the goal, or ran out of time, we want to reset the agent back to the starting point and adjust the hyperparameters, decaying epsilon and the learning rate." }, { "code": null, "e": 8985, "s": 8677, "text": "control.py checks if the steps are equal to an episode length or if the agent’s state is done, and if so saves the reward for that episode (useful for plotting the convergence of the agents algorithm), sets the agent back to the start position, and then multiplies the epsilon and learning by a decay value." }, { "code": null, "e": 9005, "s": 8985, "text": "move.py, control.py" }, { "code": null, "e": 9200, "s": 9005, "text": "Action, Reward, Update, and Control are the general framework common to almost all reinforcement learning simulations. The specific behavior names might change, but the pattern remains the same." }, { "code": null, "e": 9472, "s": 9200, "text": "But, outside of this design pattern, there are context specific behaviors an agent will want to execute for its given environment. In this simulation, this is move.py, which handles actually taking the action selected by the agent and executing it in the new environment." }, { "code": null, "e": 9809, "s": 9472, "text": "When we run the simulation, we can see in the 3D viewer the agent moving about and landing on obstacles or the goal, being reset, and starting over. Over hundreds of runs, its q_table values reflect quality scores that, as it begins to exploit more than explore, will guide it more frequently to the goal state while avoiding obstacles." }, { "code": null, "e": 9994, "s": 9809, "text": "To get a more quantitative measure of how the agent is performing, switch to the analysis view and watch the rewards per episode increasingly converge to a steady state positive value." }, { "code": null, "e": 10405, "s": 9994, "text": "The speed at which the agent converges to a steady, positive reward state will be determined in large part by the hyperparameters of the simulation. The reward size, penalty size, epsilon, etc. will all affect the behavior of the agent. You can try manually setting different values in global and see what happens, or you can use the HASH optimization engine to select hyperparameters that maximize the reward." }, { "code": null, "e": 10873, "s": 10405, "text": "To build your own RL simulations with HASH, you can experiment with the library of RL behaviors shared from this simulation. They contain generic versions of the action, reward, and update behaviors — you can use the Q-learning algorithm or implement your own custom algorithm. And while they’re by no means a replacement for the full fledged RL implementations you’ll find in frameworks like Tensorflow or PyTorch, they’re a great way to start experimenting with RL." } ]
Introduction to Conda virtual environments | by Zolzaya Luvsandorj | Towards Data Science
Reproducibility is an important characteristic of a good data science project. Many factors from setting random seeds, data versioning to using virtual environments can help improve the reproducibility of data science projects. In this post, we will look at the basics of managing Python virtual environments with Conda. Before we dive into learning commands for managing virtual environments, it may be helpful to familiarise with a few common terms regarding Conda. Conda is a language-agnostic tool for package management and environment management. As a package manager, Conda can install, update and remove packages. As an environment manager, it can manage virtual environments. Anaconda is the most popular Python distribution (i.e way of distributing Python to end users like you and me). By installing Anaconda, you get Miniconda, Anaconda Navigator (i.e. a graphical user interface) and curated selection of packages installed. Miniconda is a mini-scale version of Anaconda. It is also a Python distribution. By installing Miniconda, you get Conda, Python and a small number of packages installed. As we can see, Conda is included in both Anaconda and Miniconda. Pip is a package manager for Python. This means both Conda and Pip can be used to install, update and remove packages in Python. While Pip gives access to a wider range of packages available on the Python Package Index (PyPI), Conda gives access to a relatively smaller range of packages available on its channels. As a result, there are times where a certain package will only be available for installation via Pip. Venv is an environment manager for Python. Both Conda and Venv are great at managing virtual environments (i.e. isolated and independent environments) with different versions of packages. However, one obvious benefit of Conda over Venv is its ease of managing multiple Python versions. In other words, Conda makes it seamless to create virtual environments using different versions of Python. With Venv, we will need to use an additional tool to manage Python versions or install multiple Python versions before creating virtual environments. Now, let’s learn the basics of managing virtual environments with Conda. I encourage you to follow along on your computer as you read to get hands-on experience. If you are following along with the commands in the section, ensure your computer has Conda (version 4.6+) installed either via Anaconda or Miniconda. We can access Conda via Anaconda Prompt on Windows and Terminal on Mac. Let’s start by opening up the relevant command-line interface for your operating system with the following instructions: Windows: Press windows key ➡️ Type Anaconda prompt ➡️ Press enterMac: Press cmd + space bar ➡️ Type Terminal ➡️ Press enter Now, it’s time to create virtual environments! First, let’s check out the list of existing virtual environments: $ conda env list # Option 1$ conda info --envs # Option 2 We have one virtual environment called base. When we install Miniconda or Anaconda, it creates a default environment called base. This is what we are seeing in the output. We will now learn three common ways of creating a virtual environment. A common way to create a virtual environment is to create it from a YAML file: environment.yml or environment.yaml. This file contains specifications of the virtual environment (e.g. name of environment, packages, their versions and Python version). You can see some example YAML files from here and here. If we had such YAML file in the current working directory, we can create a virtual environment from it with one of the commands below: $ conda env create -f environment.yml # Short form$ conda env create --file environment.yml # Long form Now, let’s check out the list of virtual environments again: $ conda env list We now have a new Conda environment called test. The environment that has asterisk indicates the active environment we are in. This means we are still in the base environment. Let’s activate the new environment and check the list of virtual environments again: $ conda activate test$ conda env list We can see the asterisk next to the new virtual environment: test. We can also see the active environment name in () at the beginning of the command line as shown in the top left of the screenshot above. Another way to create virtual environment is to clone an existing environment. With the following command, we clone an environment called test and name the clone as testclone: $ conda create -n testclone --clone test # Short form$ conda create --name testclone --clone test # Long form Once the environment is created, we can activate the newly created environment like before. Sometimes we need to build the environment ourselves. Let’s create an environment using Python version 3.9.7 and call it anothertest: $ conda create -n anothertest python=3.9.7 When prompted, type y and press enter to continue the creation. If we don’t want to be prompted, we can add -y in the command: $ conda create -n anothertest python=3.9.7 -y Let’s activate the environment and check the Python version: $ conda activate anothertest$ python --version We can confirm that the new environment uses Python 3.9.7. When creating Conda environments, we can go up and down Python version. For instance, if my base Python is 3.7.1, I can create an environment with Python 3.5.3 or 3.9.7. If we didn’t specify a Python version: conda create -n anothertest -y, the new environment will use the same Python version as the base Python. Installing packages one at time can lead to dependency conflicts. Conda’s official documentation recommends to install all packages at the same time so that the dependency conflicts are resolved. Hence, we will now install multiple packages at once instead of installing one by one. Here’s an example: $ conda install "numpy>=1.11" nltk==3.6.2 jupyter -y Here are different ways we could specify a version when installing packages: If we don’t specify the version of the packages: conda install numpy nltk jupyter -y, Conda will install the latest version of these packages. By default, conda install will install packages from its defaults channel. There are times where a certain package is not available on this channel but may be available on other Conda channels such as conda-forge, a popular channel that is maintained by the community. We can check the current channels using the command below: $ conda config --show channels To add conda-forge channel and check the current channels again: $ conda config --add channels conda-forge$ conda config --show channels We can see an additional channel: conda-forge. The order in which these channels are displayed shows the channel priority. In this example, conda-forge is the high priority channel. This means when we run conda install package_name, Conda will try to install a package from conda-forge channel and if it’s not available in conda-forge, it will try to install a package from the defaults channel. This change in channels is not specific to an environment, instead it impacts how Conda is configured in general. If you want to remove a conda-forge channel, you can use the command below: $ conda config --remove channels conda-forge If we don’t want to add a channel, but still want to install package that is available in another channel but not in the defaults channel, here’s an alternative command we can use to install package from other channels: $ conda install package_name -c conda-forge -y # Short form$ conda install package_name --channel conda-forge -y # Long form This will not change the channels configuration but will install the package from the desired channel (e.g. conda-forge in this example) for the occasion. If a package is not available across Conda channels, you can install the package from Pip in the active environment using pip install command: $ pip install package_name Now it’s time to learn a few other useful commands to manage virtual environments. Once you are done using the virtual environment, if you want to switch back to the base environment, you can use one of the following to deactivate the environment: $ conda activate # Option 1$ conda deactivate test # Option 2 We can check the specifications of the current environment with: $ conda list This will show environment details such as Python version used, package names installed and their versions. To export the specifications of the current environment into a YAML file into the current directory, we can use one of the commands below: $ conda env export > environment.yml # Option 1$ conda env export -f environment.yml # Option 2 Let’s now remove all the test environments we created as part of this tutorial: $ conda activate # Need to deactivate the environment first$ conda env remove -n test$ conda env remove -n testclone$ conda env remove -n anothertest$ conda env list If you are on Windows, I also recommend to delete the environment folders as well. If you are not sure where to find these folders, conda env list will show the location. For instance, the folders were in this location on my computer: After deleting this, all the test environments will be deleted completely. Now it’s your turn to create a virtual environment for your project! In this post, we covered the basics of Conda virtual environments using the command line. It’s also possible to manage virtual environments using Anaconda Navigator if you want to explore. If you want to learn more about Conda, here is an insightful article by Jake VanderPlas on ‘Conda myths and misconceptions’. Would you like to access more content like this? Medium members get unlimited access to any articles on Medium. If you become a member using my referral link, a portion of your membership fee will directly go to support me. Thank you for reading my article. If you are interested, here are links to some of my other posts: ◼️️ Introduction to Python Virtual Environment for Data Science◼️️ Introduction to Git for Data Science◼️️ Bayes’ Theorem explained◼️️ Comparing Random Forest and Gradient Boosting◼️️ How are decision trees built?◼️️ Pipeline, ColumnTransformer and FeatureUnion explained◼️️ FeatureUnion, ColumnTransformer & Pipeline for preprocessing text data Bye for now 🏃 💨
[ { "code": null, "e": 493, "s": 172, "text": "Reproducibility is an important characteristic of a good data science project. Many factors from setting random seeds, data versioning to using virtual environments can help improve the reproducibility of data science projects. In this post, we will look at the basics of managing Python virtual environments with Conda." }, { "code": null, "e": 640, "s": 493, "text": "Before we dive into learning commands for managing virtual environments, it may be helpful to familiarise with a few common terms regarding Conda." }, { "code": null, "e": 857, "s": 640, "text": "Conda is a language-agnostic tool for package management and environment management. As a package manager, Conda can install, update and remove packages. As an environment manager, it can manage virtual environments." }, { "code": null, "e": 1110, "s": 857, "text": "Anaconda is the most popular Python distribution (i.e way of distributing Python to end users like you and me). By installing Anaconda, you get Miniconda, Anaconda Navigator (i.e. a graphical user interface) and curated selection of packages installed." }, { "code": null, "e": 1280, "s": 1110, "text": "Miniconda is a mini-scale version of Anaconda. It is also a Python distribution. By installing Miniconda, you get Conda, Python and a small number of packages installed." }, { "code": null, "e": 1345, "s": 1280, "text": "As we can see, Conda is included in both Anaconda and Miniconda." }, { "code": null, "e": 1382, "s": 1345, "text": "Pip is a package manager for Python." }, { "code": null, "e": 1762, "s": 1382, "text": "This means both Conda and Pip can be used to install, update and remove packages in Python. While Pip gives access to a wider range of packages available on the Python Package Index (PyPI), Conda gives access to a relatively smaller range of packages available on its channels. As a result, there are times where a certain package will only be available for installation via Pip." }, { "code": null, "e": 1805, "s": 1762, "text": "Venv is an environment manager for Python." }, { "code": null, "e": 2305, "s": 1805, "text": "Both Conda and Venv are great at managing virtual environments (i.e. isolated and independent environments) with different versions of packages. However, one obvious benefit of Conda over Venv is its ease of managing multiple Python versions. In other words, Conda makes it seamless to create virtual environments using different versions of Python. With Venv, we will need to use an additional tool to manage Python versions or install multiple Python versions before creating virtual environments." }, { "code": null, "e": 2467, "s": 2305, "text": "Now, let’s learn the basics of managing virtual environments with Conda. I encourage you to follow along on your computer as you read to get hands-on experience." }, { "code": null, "e": 2618, "s": 2467, "text": "If you are following along with the commands in the section, ensure your computer has Conda (version 4.6+) installed either via Anaconda or Miniconda." }, { "code": null, "e": 2811, "s": 2618, "text": "We can access Conda via Anaconda Prompt on Windows and Terminal on Mac. Let’s start by opening up the relevant command-line interface for your operating system with the following instructions:" }, { "code": null, "e": 2935, "s": 2811, "text": "Windows: Press windows key ➡️ Type Anaconda prompt ➡️ Press enterMac: Press cmd + space bar ➡️ Type Terminal ➡️ Press enter" }, { "code": null, "e": 2982, "s": 2935, "text": "Now, it’s time to create virtual environments!" }, { "code": null, "e": 3048, "s": 2982, "text": "First, let’s check out the list of existing virtual environments:" }, { "code": null, "e": 3106, "s": 3048, "text": "$ conda env list # Option 1$ conda info --envs # Option 2" }, { "code": null, "e": 3278, "s": 3106, "text": "We have one virtual environment called base. When we install Miniconda or Anaconda, it creates a default environment called base. This is what we are seeing in the output." }, { "code": null, "e": 3349, "s": 3278, "text": "We will now learn three common ways of creating a virtual environment." }, { "code": null, "e": 3790, "s": 3349, "text": "A common way to create a virtual environment is to create it from a YAML file: environment.yml or environment.yaml. This file contains specifications of the virtual environment (e.g. name of environment, packages, their versions and Python version). You can see some example YAML files from here and here. If we had such YAML file in the current working directory, we can create a virtual environment from it with one of the commands below:" }, { "code": null, "e": 3894, "s": 3790, "text": "$ conda env create -f environment.yml # Short form$ conda env create --file environment.yml # Long form" }, { "code": null, "e": 3955, "s": 3894, "text": "Now, let’s check out the list of virtual environments again:" }, { "code": null, "e": 3972, "s": 3955, "text": "$ conda env list" }, { "code": null, "e": 4233, "s": 3972, "text": "We now have a new Conda environment called test. The environment that has asterisk indicates the active environment we are in. This means we are still in the base environment. Let’s activate the new environment and check the list of virtual environments again:" }, { "code": null, "e": 4271, "s": 4233, "text": "$ conda activate test$ conda env list" }, { "code": null, "e": 4475, "s": 4271, "text": "We can see the asterisk next to the new virtual environment: test. We can also see the active environment name in () at the beginning of the command line as shown in the top left of the screenshot above." }, { "code": null, "e": 4651, "s": 4475, "text": "Another way to create virtual environment is to clone an existing environment. With the following command, we clone an environment called test and name the clone as testclone:" }, { "code": null, "e": 4761, "s": 4651, "text": "$ conda create -n testclone --clone test # Short form$ conda create --name testclone --clone test # Long form" }, { "code": null, "e": 4853, "s": 4761, "text": "Once the environment is created, we can activate the newly created environment like before." }, { "code": null, "e": 4987, "s": 4853, "text": "Sometimes we need to build the environment ourselves. Let’s create an environment using Python version 3.9.7 and call it anothertest:" }, { "code": null, "e": 5030, "s": 4987, "text": "$ conda create -n anothertest python=3.9.7" }, { "code": null, "e": 5157, "s": 5030, "text": "When prompted, type y and press enter to continue the creation. If we don’t want to be prompted, we can add -y in the command:" }, { "code": null, "e": 5203, "s": 5157, "text": "$ conda create -n anothertest python=3.9.7 -y" }, { "code": null, "e": 5264, "s": 5203, "text": "Let’s activate the environment and check the Python version:" }, { "code": null, "e": 5311, "s": 5264, "text": "$ conda activate anothertest$ python --version" }, { "code": null, "e": 5684, "s": 5311, "text": "We can confirm that the new environment uses Python 3.9.7. When creating Conda environments, we can go up and down Python version. For instance, if my base Python is 3.7.1, I can create an environment with Python 3.5.3 or 3.9.7. If we didn’t specify a Python version: conda create -n anothertest -y, the new environment will use the same Python version as the base Python." }, { "code": null, "e": 5986, "s": 5684, "text": "Installing packages one at time can lead to dependency conflicts. Conda’s official documentation recommends to install all packages at the same time so that the dependency conflicts are resolved. Hence, we will now install multiple packages at once instead of installing one by one. Here’s an example:" }, { "code": null, "e": 6039, "s": 5986, "text": "$ conda install \"numpy>=1.11\" nltk==3.6.2 jupyter -y" }, { "code": null, "e": 6116, "s": 6039, "text": "Here are different ways we could specify a version when installing packages:" }, { "code": null, "e": 6259, "s": 6116, "text": "If we don’t specify the version of the packages: conda install numpy nltk jupyter -y, Conda will install the latest version of these packages." }, { "code": null, "e": 6587, "s": 6259, "text": "By default, conda install will install packages from its defaults channel. There are times where a certain package is not available on this channel but may be available on other Conda channels such as conda-forge, a popular channel that is maintained by the community. We can check the current channels using the command below:" }, { "code": null, "e": 6618, "s": 6587, "text": "$ conda config --show channels" }, { "code": null, "e": 6683, "s": 6618, "text": "To add conda-forge channel and check the current channels again:" }, { "code": null, "e": 6755, "s": 6683, "text": "$ conda config --add channels conda-forge$ conda config --show channels" }, { "code": null, "e": 7341, "s": 6755, "text": "We can see an additional channel: conda-forge. The order in which these channels are displayed shows the channel priority. In this example, conda-forge is the high priority channel. This means when we run conda install package_name, Conda will try to install a package from conda-forge channel and if it’s not available in conda-forge, it will try to install a package from the defaults channel. This change in channels is not specific to an environment, instead it impacts how Conda is configured in general. If you want to remove a conda-forge channel, you can use the command below:" }, { "code": null, "e": 7386, "s": 7341, "text": "$ conda config --remove channels conda-forge" }, { "code": null, "e": 7606, "s": 7386, "text": "If we don’t want to add a channel, but still want to install package that is available in another channel but not in the defaults channel, here’s an alternative command we can use to install package from other channels:" }, { "code": null, "e": 7731, "s": 7606, "text": "$ conda install package_name -c conda-forge -y # Short form$ conda install package_name --channel conda-forge -y # Long form" }, { "code": null, "e": 7886, "s": 7731, "text": "This will not change the channels configuration but will install the package from the desired channel (e.g. conda-forge in this example) for the occasion." }, { "code": null, "e": 8029, "s": 7886, "text": "If a package is not available across Conda channels, you can install the package from Pip in the active environment using pip install command:" }, { "code": null, "e": 8056, "s": 8029, "text": "$ pip install package_name" }, { "code": null, "e": 8139, "s": 8056, "text": "Now it’s time to learn a few other useful commands to manage virtual environments." }, { "code": null, "e": 8304, "s": 8139, "text": "Once you are done using the virtual environment, if you want to switch back to the base environment, you can use one of the following to deactivate the environment:" }, { "code": null, "e": 8366, "s": 8304, "text": "$ conda activate # Option 1$ conda deactivate test # Option 2" }, { "code": null, "e": 8431, "s": 8366, "text": "We can check the specifications of the current environment with:" }, { "code": null, "e": 8444, "s": 8431, "text": "$ conda list" }, { "code": null, "e": 8691, "s": 8444, "text": "This will show environment details such as Python version used, package names installed and their versions. To export the specifications of the current environment into a YAML file into the current directory, we can use one of the commands below:" }, { "code": null, "e": 8787, "s": 8691, "text": "$ conda env export > environment.yml # Option 1$ conda env export -f environment.yml # Option 2" }, { "code": null, "e": 8867, "s": 8787, "text": "Let’s now remove all the test environments we created as part of this tutorial:" }, { "code": null, "e": 9033, "s": 8867, "text": "$ conda activate # Need to deactivate the environment first$ conda env remove -n test$ conda env remove -n testclone$ conda env remove -n anothertest$ conda env list" }, { "code": null, "e": 9268, "s": 9033, "text": "If you are on Windows, I also recommend to delete the environment folders as well. If you are not sure where to find these folders, conda env list will show the location. For instance, the folders were in this location on my computer:" }, { "code": null, "e": 9412, "s": 9268, "text": "After deleting this, all the test environments will be deleted completely. Now it’s your turn to create a virtual environment for your project!" }, { "code": null, "e": 9726, "s": 9412, "text": "In this post, we covered the basics of Conda virtual environments using the command line. It’s also possible to manage virtual environments using Anaconda Navigator if you want to explore. If you want to learn more about Conda, here is an insightful article by Jake VanderPlas on ‘Conda myths and misconceptions’." }, { "code": null, "e": 9950, "s": 9726, "text": "Would you like to access more content like this? Medium members get unlimited access to any articles on Medium. If you become a member using my referral link, a portion of your membership fee will directly go to support me." }, { "code": null, "e": 10049, "s": 9950, "text": "Thank you for reading my article. If you are interested, here are links to some of my other posts:" }, { "code": null, "e": 10395, "s": 10049, "text": "◼️️ Introduction to Python Virtual Environment for Data Science◼️️ Introduction to Git for Data Science◼️️ Bayes’ Theorem explained◼️️ Comparing Random Forest and Gradient Boosting◼️️ How are decision trees built?◼️️ Pipeline, ColumnTransformer and FeatureUnion explained◼️️ FeatureUnion, ColumnTransformer & Pipeline for preprocessing text data" } ]
JOGL - Drawing with GL Lines
In the Previous chapter we have learned how draw a basic line using JOGL. We draw lines by passing a predefined field, Gl_lines to glBegin() method. This chapter provides examples to draw shapes like triangle, rhombus and a house, using glBegin() method and GL_Lines. Let us go through a program to draw a triangle using GL_LINES − import javax.media.opengl.GL2; import javax.media.opengl.GLAutoDrawable; import javax.media.opengl.GLCapabilities; import javax.media.opengl.GLEventListener; import javax.media.opengl.GLProfile; import javax.media.opengl.awt.GLCanvas; import javax.swing.JFrame; public class Triangle implements GLEventListener { @Override public void display(GLAutoDrawable drawable) { final GL2 gl = drawable.getGL().getGL2(); gl.glBegin (GL2.GL_LINES); //drawing the base gl.glBegin (GL2.GL_LINES); gl.glVertex3f(-0.50f, -0.50f, 0); gl.glVertex3f(0.50f, -0.50f, 0); gl.glEnd(); //drawing the right edge gl.glBegin (GL2.GL_LINES); gl.glVertex3f(0f, 0.50f, 0); gl.glVertex3f(-0.50f, -0.50f, 0); gl.glEnd(); //drawing the lft edge gl.glBegin (GL2.GL_LINES); gl.glVertex3f(0f, 0.50f, 0); gl.glVertex3f(0.50f, -0.50f, 0); gl.glEnd(); gl.glFlush(); } @Override public void dispose(GLAutoDrawable arg0) { //method body } @Override public void init(GLAutoDrawable arg0) { // method body } @Override public void reshape(GLAutoDrawable arg0, int arg1, int arg2, int arg3, int arg4) { // method body } public static void main(String[] args) { //getting the capabilities object of GL2 profile final GLProfile profile = GLProfile.get(GLProfile.GL2); GLCapabilities capabilities = new GLCapabilities(profile); // The canvas final GLCanvas glcanvas = new GLCanvas(capabilities); Triangle l = new Triangle(); glcanvas.addGLEventListener(l); glcanvas.setSize(400, 400); //creating frame final JFrame frame = new JFrame ("Triangle"); //adding canvas to frame frame.getContentPane().add(glcanvas); frame.setSize(frame.getContentPane().getPreferredSize()); frame.setVisible(true); }//end of main }//end of classimport javax.media.opengl.GL2; If you compile and execute the above program, the following output is generated. It shows a triangle drawn using GL_LINES of glBegin() method. Let us go through a program to draw a rhombus using GL_LINES − import javax.media.opengl.GL2; import javax.media.opengl.GLAutoDrawable; import javax.media.opengl.GLCapabilities; import javax.media.opengl.GLEventListener; import javax.media.opengl.GLProfile; import javax.media.opengl.awt.GLCanvas; import javax.swing.JFrame; public class Rhombus implements GLEventListener { @Override public void display( GLAutoDrawable drawable ) { final GL2 gl = drawable.getGL().getGL2(); //edge1 gl.glBegin( GL2.GL_LINES ); gl.glVertex3f( 0.0f,0.75f,0 ); gl.glVertex3f( -0.75f,0f,0 ); gl.glEnd(); //edge2 gl.glBegin( GL2.GL_LINES ); gl.glVertex3f( -0.75f,0f,0 ); gl.glVertex3f( 0f,-0.75f, 0 ); gl.glEnd(); //edge3 gl.glBegin( GL2.GL_LINES ); gl.glVertex3f( 0f,-0.75f, 0 ); gl.glVertex3f( 0.75f,0f, 0 ); gl.glEnd(); //edge4 gl.glBegin( GL2.GL_LINES ); gl.glVertex3f( 0.75f,0f, 0 ); gl.glVertex3f( 0.0f,0.75f,0 ); gl.glEnd(); gl.glFlush(); } @Override public void dispose( GLAutoDrawable arg0 ) { //method body } @Override public void init(GLAutoDrawable arg0 ) { // method body } @Override public void reshape( GLAutoDrawable arg0, int arg1, int arg2, int arg3, int arg4 ) { // method body } public static void main( String[] args ) { //getting the capabilities object of GL2 profile final GLProfile profile = GLProfile.get( GLProfile.GL2 ); GLCapabilities capabilities = new GLCapabilities(profile); // The canvas final GLCanvas glcanvas = new GLCanvas( capabilities ); Rhombus rhombus = new Rhombus(); glcanvas.addGLEventListener( rhombus ); glcanvas.setSize( 400, 400 ); //creating frame final JFrame frame = new JFrame ( "Rhombus" ); //adding canvas to frame frame.getContentPane().add( glcanvas ); frame.setSize(frame.getContentPane().getPreferredSize() ); frame.setVisible( true ); } } If you compile and execute the above program, you get the following output. It shows a rhombus generated using GL_LINES of glBegin() method. Let us go through a program to draw a house using GL_LINES − import javax.media.opengl.GL2; import javax.media.opengl.GLAutoDrawable; import javax.media.opengl.GLCapabilities; import javax.media.opengl.GLEventListener; import javax.media.opengl.GLProfile; import javax.media.opengl.awt.GLCanvas; import javax.swing.JFrame; public class House implements GLEventListener { @Override public void display( GLAutoDrawable drawable ) { final GL2 gl = drawable.getGL().getGL2(); //drawing top gl.glBegin ( GL2.GL_LINES ); gl.glVertex3f( -0.3f, 0.3f, 0 ); gl.glVertex3f( 0.3f,0.3f, 0 ); gl.glEnd(); //drawing bottom gl.glBegin( GL2.GL_LINES ); gl.glVertex3f( -0.3f,-0.3f, 0 ); gl.glVertex3f( 0.3f,-0.3f, 0 ); gl.glEnd(); //drawing the right edge gl.glBegin( GL2.GL_LINES ); gl.glVertex3f( -0.3f,0.3f, 0 ); gl.glVertex3f( -0.3f,-0.3f, 0 ); gl.glEnd(); //drawing the left edge gl.glBegin( GL2.GL_LINES ); gl.glVertex3f( 0.3f,0.3f,0 ); gl.glVertex3f( 0.3f,-0.3f,0 ); gl.glEnd(); //building roof //building lft dia gl.glBegin( GL2.GL_LINES ); gl.glVertex3f( 0f,0.6f, 0 ); gl.glVertex3f( -0.3f,0.3f, 0 ); gl.glEnd(); //building rt dia gl.glBegin( GL2.GL_LINES ); gl.glVertex3f( 0f,0.6f, 0 ); gl.glVertex3f( 0.3f,0.3f, 0 ); gl.glEnd(); //building door //drawing top gl.glBegin ( GL2.GL_LINES ); gl.glVertex3f( -0.05f, 0.05f, 0 ); gl.glVertex3f( 0.05f, 0.05f, 0 ); gl.glEnd(); //drawing the left edge gl.glBegin ( GL2.GL_LINES ); gl.glVertex3f( -0.05f, 0.05f, 0 ); gl.glVertex3f( -0.05f, -0.3f, 0 ); gl.glEnd(); //drawing the right edge gl.glBegin ( GL2.GL_LINES ); gl.glVertex3f( 0.05f, 0.05f, 0 ); gl.glVertex3f( 0.05f, -0.3f, 0 ); gl.glEnd(); } @Override public void dispose( GLAutoDrawable arg0 ) { //method body } @Override public void init( GLAutoDrawable arg0 ) { // method body } @Override public void reshape( GLAutoDrawable arg0, int arg1, int arg2, int arg3, int arg4 ) { // method body } public static void main( String[] args ) { //getting the capabilities object of GL2 profile final GLProfile profile = GLProfile.get( GLProfile.GL2 ); GLCapabilities capabilities = new GLCapabilities(profile); // The canvas final GLCanvas glcanvas = new GLCanvas( capabilities ); House house = new House(); glcanvas.addGLEventListener( house ); glcanvas.setSize(400, 400); //creating frame final JFrame frame = new JFrame( "House" ); //adding canvas to frame frame.getContentPane().add( glcanvas ); frame.setSize(frame.getContentPane().getPreferredSize() ); frame.setVisible( true ); }//end of main }//end of class If you compile and execute the above program, you get the following output. It shows a house diagram generated using GL_LINES() method. Print Add Notes Bookmark this page
[ { "code": null, "e": 2168, "s": 2019, "text": "In the Previous chapter we have learned how draw a basic line using JOGL. We draw lines by passing a predefined field, Gl_lines to glBegin() method." }, { "code": null, "e": 2287, "s": 2168, "text": "This chapter provides examples to draw shapes like triangle, rhombus and a house, using glBegin() method and GL_Lines." }, { "code": null, "e": 2351, "s": 2287, "text": "Let us go through a program to draw a triangle using GL_LINES −" }, { "code": null, "e": 4381, "s": 2351, "text": "import javax.media.opengl.GL2;\nimport javax.media.opengl.GLAutoDrawable;\nimport javax.media.opengl.GLCapabilities;\nimport javax.media.opengl.GLEventListener;\nimport javax.media.opengl.GLProfile;\nimport javax.media.opengl.awt.GLCanvas;\n\nimport javax.swing.JFrame;\n\npublic class Triangle implements GLEventListener {\n\n @Override\n public void display(GLAutoDrawable drawable) {\n final GL2 gl = drawable.getGL().getGL2();\n gl.glBegin (GL2.GL_LINES);\n \n //drawing the base\n gl.glBegin (GL2.GL_LINES);\n gl.glVertex3f(-0.50f, -0.50f, 0);\n gl.glVertex3f(0.50f, -0.50f, 0);\n gl.glEnd();\n \n //drawing the right edge\n gl.glBegin (GL2.GL_LINES);\n gl.glVertex3f(0f, 0.50f, 0);\n gl.glVertex3f(-0.50f, -0.50f, 0);\n gl.glEnd();\n \n //drawing the lft edge\n gl.glBegin (GL2.GL_LINES);\n gl.glVertex3f(0f, 0.50f, 0);\n gl.glVertex3f(0.50f, -0.50f, 0);\n gl.glEnd();\n gl.glFlush();\n }\n \n @Override\n public void dispose(GLAutoDrawable arg0) {\n //method body\n }\n \n @Override\n public void init(GLAutoDrawable arg0) {\n // method body\n }\n \n @Override\n public void reshape(GLAutoDrawable arg0, int arg1, int arg2, int arg3, int arg4) {\n // method body\n }\n \n public static void main(String[] args) {\n \n //getting the capabilities object of GL2 profile\n final GLProfile profile = GLProfile.get(GLProfile.GL2);\n GLCapabilities capabilities = new GLCapabilities(profile);\n \n // The canvas\n final GLCanvas glcanvas = new GLCanvas(capabilities);\n Triangle l = new Triangle();\n glcanvas.addGLEventListener(l);\n glcanvas.setSize(400, 400);\n \n //creating frame\n final JFrame frame = new JFrame (\"Triangle\");\n \n //adding canvas to frame\n frame.getContentPane().add(glcanvas);\n \n frame.setSize(frame.getContentPane().getPreferredSize());\n frame.setVisible(true);\n \n }//end of main\n\t\n}//end of classimport javax.media.opengl.GL2;" }, { "code": null, "e": 4524, "s": 4381, "text": "If you compile and execute the above program, the following output is generated.\nIt shows a triangle drawn using GL_LINES of glBegin() method." }, { "code": null, "e": 4587, "s": 4524, "text": "Let us go through a program to draw a rhombus using GL_LINES −" }, { "code": null, "e": 6645, "s": 4587, "text": "import javax.media.opengl.GL2;\nimport javax.media.opengl.GLAutoDrawable;\nimport javax.media.opengl.GLCapabilities;\nimport javax.media.opengl.GLEventListener;\nimport javax.media.opengl.GLProfile;\nimport javax.media.opengl.awt.GLCanvas;\n\nimport javax.swing.JFrame;\n\npublic class Rhombus implements GLEventListener {\n\n @Override\n public void display( GLAutoDrawable drawable ) {\n final GL2 gl = drawable.getGL().getGL2();\n \n //edge1 \n gl.glBegin( GL2.GL_LINES );\n gl.glVertex3f( 0.0f,0.75f,0 );\n gl.glVertex3f( -0.75f,0f,0 );\n gl.glEnd();\n \n //edge2\n gl.glBegin( GL2.GL_LINES );\n gl.glVertex3f( -0.75f,0f,0 );\n gl.glVertex3f( 0f,-0.75f, 0 );\n gl.glEnd();\n \n //edge3\n gl.glBegin( GL2.GL_LINES );\n gl.glVertex3f( 0f,-0.75f, 0 );\n gl.glVertex3f( 0.75f,0f, 0 );\n gl.glEnd();\n \n //edge4\n gl.glBegin( GL2.GL_LINES );\n gl.glVertex3f( 0.75f,0f, 0 );\n gl.glVertex3f( 0.0f,0.75f,0 );\n gl.glEnd();\n gl.glFlush();\n }\n\t\n @Override\n public void dispose( GLAutoDrawable arg0 ) {\n //method body\n }\n\t\n @Override\n public void init(GLAutoDrawable arg0 ) {\n // method body\n }\n\t\n @Override\n public void reshape( GLAutoDrawable arg0, int arg1, int arg2, int arg3, int arg4 ) {\n // method body\n }\n\t\n public static void main( String[] args ) {\n\t\n //getting the capabilities object of GL2 profile\n final GLProfile profile = GLProfile.get( GLProfile.GL2 );\n GLCapabilities capabilities = new GLCapabilities(profile);\n \n // The canvas\n final GLCanvas glcanvas = new GLCanvas( capabilities );\n Rhombus rhombus = new Rhombus();\n glcanvas.addGLEventListener( rhombus );\n glcanvas.setSize( 400, 400 );\n \n //creating frame\n final JFrame frame = new JFrame ( \"Rhombus\" );\n \n //adding canvas to frame\n frame.getContentPane().add( glcanvas );\n frame.setSize(frame.getContentPane().getPreferredSize() );\n frame.setVisible( true );\n }\n\t\n}" }, { "code": null, "e": 6786, "s": 6645, "text": "If you compile and execute the above program, you get the following output. It shows a rhombus generated using GL_LINES of glBegin() method." }, { "code": null, "e": 6847, "s": 6786, "text": "Let us go through a program to draw a house using GL_LINES −" }, { "code": null, "e": 9832, "s": 6847, "text": "import javax.media.opengl.GL2;\nimport javax.media.opengl.GLAutoDrawable;\nimport javax.media.opengl.GLCapabilities;\nimport javax.media.opengl.GLEventListener;\nimport javax.media.opengl.GLProfile;\nimport javax.media.opengl.awt.GLCanvas;\n\nimport javax.swing.JFrame;\n\npublic class House implements GLEventListener {\n\n @Override\n public void display( GLAutoDrawable drawable ) {\n final GL2 gl = drawable.getGL().getGL2();\n \n //drawing top\n gl.glBegin ( GL2.GL_LINES );\n gl.glVertex3f( -0.3f, 0.3f, 0 );\n gl.glVertex3f( 0.3f,0.3f, 0 );\n gl.glEnd();\n \n //drawing bottom\n gl.glBegin( GL2.GL_LINES );\n gl.glVertex3f( -0.3f,-0.3f, 0 );\n gl.glVertex3f( 0.3f,-0.3f, 0 );\n gl.glEnd();\n \n //drawing the right edge\n gl.glBegin( GL2.GL_LINES );\n gl.glVertex3f( -0.3f,0.3f, 0 );\n gl.glVertex3f( -0.3f,-0.3f, 0 );\n gl.glEnd();\n \n //drawing the left edge\n gl.glBegin( GL2.GL_LINES );\n gl.glVertex3f( 0.3f,0.3f,0 );\n gl.glVertex3f( 0.3f,-0.3f,0 );\n gl.glEnd();\n \n //building roof\n //building lft dia\n gl.glBegin( GL2.GL_LINES );\n gl.glVertex3f( 0f,0.6f, 0 );\n gl.glVertex3f( -0.3f,0.3f, 0 );\n gl.glEnd();\n \n //building rt dia\n gl.glBegin( GL2.GL_LINES );\n gl.glVertex3f( 0f,0.6f, 0 );\n gl.glVertex3f( 0.3f,0.3f, 0 );\n gl.glEnd();\n \n //building door\n //drawing top\n gl.glBegin ( GL2.GL_LINES );\n gl.glVertex3f( -0.05f, 0.05f, 0 );\n gl.glVertex3f( 0.05f, 0.05f, 0 );\n gl.glEnd();\n \n //drawing the left edge\n gl.glBegin ( GL2.GL_LINES );\n gl.glVertex3f( -0.05f, 0.05f, 0 );\n gl.glVertex3f( -0.05f, -0.3f, 0 );\n gl.glEnd();\n \n //drawing the right edge\n gl.glBegin ( GL2.GL_LINES );\n gl.glVertex3f( 0.05f, 0.05f, 0 );\n gl.glVertex3f( 0.05f, -0.3f, 0 );\n gl.glEnd();\n }\n \n @Override\n public void dispose( GLAutoDrawable arg0 ) {\n //method body\n }\n \n @Override\n public void init( GLAutoDrawable arg0 ) {\n // method body\n } \n \n @Override\n public void reshape( GLAutoDrawable arg0, int arg1, int arg2, int arg3, int arg4 ) {\n // method body\n }\n\t\n public static void main( String[] args ) {\n \n //getting the capabilities object of GL2 profile\n final GLProfile profile = GLProfile.get( GLProfile.GL2 );\n GLCapabilities capabilities = new GLCapabilities(profile);\n \n // The canvas\n final GLCanvas glcanvas = new GLCanvas( capabilities );\n House house = new House();\n glcanvas.addGLEventListener( house );\n glcanvas.setSize(400, 400);\n \n //creating frame\n final JFrame frame = new JFrame( \"House\" );\n \n //adding canvas to frame\n frame.getContentPane().add( glcanvas );\n frame.setSize(frame.getContentPane().getPreferredSize() );\n frame.setVisible( true );\n \n }//end of main\n\t\n}//end of class" }, { "code": null, "e": 9968, "s": 9832, "text": "If you compile and execute the above program, you get the following output. It shows a house diagram generated using GL_LINES() method." }, { "code": null, "e": 9975, "s": 9968, "text": " Print" }, { "code": null, "e": 9986, "s": 9975, "text": " Add Notes" } ]
Perl nested Loop
A loop can be nested inside of another loop. Perl allows to nest all type of loops to be nested. The syntax for a nested for loop statement in Perl is as follows − for ( init; condition; increment ) { for ( init; condition; increment ) { statement(s); } statement(s); } The syntax for a nested while loop statement in Perl is as follows − while(condition) { while(condition) { statement(s); } statement(s); } The syntax for a nested do...while loop statement in Perl is as follows − do{ statement(s); do{ statement(s); }while( condition ); }while( condition ); The syntax for a nested until loop statement in Perl is as follows − until(condition) { until(condition) { statement(s); } statement(s); } The syntax for a nested foreach loop statement in Perl is as follows − foreach $a (@listA) { foreach $b (@listB) { statement(s); } statement(s); } The following program uses a nested while loop to show the usage − #/usr/local/bin/perl $a = 0; $b = 0; # outer while loop while($a < 3) { $b = 0; # inner while loop while( $b < 3 ) { print "value of a = $a, b = $b\n"; $b = $b + 1; } $a = $a + 1; print "Value of a = $a\n\n"; } This would produce the following result − value of a = 0, b = 0 value of a = 0, b = 1 value of a = 0, b = 2 Value of a = 1 value of a = 1, b = 0 value of a = 1, b = 1 value of a = 1, b = 2 Value of a = 2 value of a = 2, b = 0 value of a = 2, b = 1 value of a = 2, b = 2 Value of a = 3 46 Lectures 4.5 hours Devi Killada 11 Lectures 1.5 hours Harshit Srivastava 30 Lectures 6 hours TELCOMA Global 24 Lectures 2 hours Mohammad Nauman 68 Lectures 7 hours Stone River ELearning 58 Lectures 6.5 hours Stone River ELearning Print Add Notes Bookmark this page
[ { "code": null, "e": 2317, "s": 2220, "text": "A loop can be nested inside of another loop. Perl allows to nest all type of loops to be nested." }, { "code": null, "e": 2384, "s": 2317, "text": "The syntax for a nested for loop statement in Perl is as follows −" }, { "code": null, "e": 2506, "s": 2384, "text": "for ( init; condition; increment ) {\n for ( init; condition; increment ) {\n statement(s);\n }\n statement(s);\n}\n" }, { "code": null, "e": 2575, "s": 2506, "text": "The syntax for a nested while loop statement in Perl is as follows −" }, { "code": null, "e": 2661, "s": 2575, "text": "while(condition) {\n while(condition) {\n statement(s);\n }\n statement(s);\n}\n" }, { "code": null, "e": 2735, "s": 2661, "text": "The syntax for a nested do...while loop statement in Perl is as follows −" }, { "code": null, "e": 2830, "s": 2735, "text": "do{\n statement(s);\n do{\n statement(s);\n }while( condition );\n\n}while( condition );\n" }, { "code": null, "e": 2899, "s": 2830, "text": "The syntax for a nested until loop statement in Perl is as follows −" }, { "code": null, "e": 2985, "s": 2899, "text": "until(condition) {\n until(condition) {\n statement(s);\n }\n statement(s);\n}\n" }, { "code": null, "e": 3056, "s": 2985, "text": "The syntax for a nested foreach loop statement in Perl is as follows −" }, { "code": null, "e": 3148, "s": 3056, "text": "foreach $a (@listA) {\n foreach $b (@listB) {\n statement(s);\n }\n statement(s);\n}\n" }, { "code": null, "e": 3215, "s": 3148, "text": "The following program uses a nested while loop to show the usage −" }, { "code": null, "e": 3461, "s": 3215, "text": "#/usr/local/bin/perl\n \n$a = 0;\n$b = 0;\n\n# outer while loop\nwhile($a < 3) {\n $b = 0;\n # inner while loop\n while( $b < 3 ) {\n print \"value of a = $a, b = $b\\n\";\n $b = $b + 1;\n }\n $a = $a + 1;\n print \"Value of a = $a\\n\\n\";\n}" }, { "code": null, "e": 3503, "s": 3461, "text": "This would produce the following result −" }, { "code": null, "e": 3749, "s": 3503, "text": "value of a = 0, b = 0\nvalue of a = 0, b = 1\nvalue of a = 0, b = 2\nValue of a = 1\n\nvalue of a = 1, b = 0\nvalue of a = 1, b = 1\nvalue of a = 1, b = 2\nValue of a = 2\n\nvalue of a = 2, b = 0\nvalue of a = 2, b = 1\nvalue of a = 2, b = 2\nValue of a = 3\n" }, { "code": null, "e": 3784, "s": 3749, "text": "\n 46 Lectures \n 4.5 hours \n" }, { "code": null, "e": 3798, "s": 3784, "text": " Devi Killada" }, { "code": null, "e": 3833, "s": 3798, "text": "\n 11 Lectures \n 1.5 hours \n" }, { "code": null, "e": 3853, "s": 3833, "text": " Harshit Srivastava" }, { "code": null, "e": 3886, "s": 3853, "text": "\n 30 Lectures \n 6 hours \n" }, { "code": null, "e": 3902, "s": 3886, "text": " TELCOMA Global" }, { "code": null, "e": 3935, "s": 3902, "text": "\n 24 Lectures \n 2 hours \n" }, { "code": null, "e": 3952, "s": 3935, "text": " Mohammad Nauman" }, { "code": null, "e": 3985, "s": 3952, "text": "\n 68 Lectures \n 7 hours \n" }, { "code": null, "e": 4008, "s": 3985, "text": " Stone River ELearning" }, { "code": null, "e": 4043, "s": 4008, "text": "\n 58 Lectures \n 6.5 hours \n" }, { "code": null, "e": 4066, "s": 4043, "text": " Stone River ELearning" }, { "code": null, "e": 4073, "s": 4066, "text": " Print" }, { "code": null, "e": 4084, "s": 4073, "text": " Add Notes" } ]
Maximum sum of nodes in Binary tree such that no two are adjacent
11 Jul, 2022 Given a binary tree with a value associated with each node, we need to choose a subset of these nodes such that the sum of selected nodes is maximum under a constraint that no two chosen nodes in the subset should be directly connected, that is, if we have taken a node in our sum then we can’t take any of its children in consideration and vice versa. Examples: In the above binary tree, chosen nodes are encircled and are not directly connected, and their sum is maximum possible. Recommended: Please solve it on “PRACTICE” first before moving on to the solution. Method 1 We can solve this problem by considering the fact that both node and its children can’t be in sum at the same time, so when we take a node into our sum, we will call recursively for its grandchildren or if we don’t take this node then we will call for all its children nodes and finally we will choose maximum from both of the results. It can be seen easily that the above approach can lead to solving the same subproblem many times, for example in the above diagram node 1 calls node 4 and 5 when its value is chosen and node 3 also calls them when its value is not chosen so these nodes are processed more than once. We can stop solving these nodes more than once by memorizing the result at all nodes. In the below code, a map is used for memorizing the result, which stores the development of the complete subtree rooted at a node in the map so that if it is called again, the value is not calculated again instead stored value from the map is returned directly. Please see the below code for a better understanding. C++ Java Python3 C# Javascript // C++ program to find maximum sum from a subset of// nodes of binary tree#include <bits/stdc++.h>using namespace std; /* A binary tree node structure */struct node{ int data; struct node *left, *right;}; /* Utility function to create a new Binary Tree node */struct node* newNode(int data){ struct node *temp = new struct node; temp->data = data; temp->left = temp->right = NULL; return temp;} // Declaration of methodsint sumOfGrandChildren(node* node);int getMaxSum(node* node);int getMaxSumUtil(node* node, map<struct node*, int>& mp); // method returns maximum sum possible from subtrees rooted// at grandChildrens of node 'node'int sumOfGrandChildren(node* node, map<struct node*, int>& mp){ int sum = 0; // call for children of left child only if it is not NULL if (node->left) sum += getMaxSumUtil(node->left->left, mp) + getMaxSumUtil(node->left->right, mp); // call for children of right child only if it is not NULL if (node->right) sum += getMaxSumUtil(node->right->left, mp) + getMaxSumUtil(node->right->right, mp); return sum;} // Utility method to return maximum sum rooted at node 'node'int getMaxSumUtil(node* node, map<struct node*, int>& mp){ if (node == NULL) return 0; // If node is already processed then return calculated // value from map if (mp.find(node) != mp.end()) return mp[node]; // take current node value and call for all grand children int incl = node->data + sumOfGrandChildren(node, mp); // don't take current node value and call for all children int excl = getMaxSumUtil(node->left, mp) + getMaxSumUtil(node->right, mp); // choose maximum from both above calls and store that in map mp[node] = max(incl, excl); return mp[node];} // Returns maximum sum from subset of nodes// of binary tree under given constraintsint getMaxSum(node* node){ if (node == NULL) return 0; map<struct node*, int> mp; return getMaxSumUtil(node, mp);} // Driver code to test above methodsint main(){ node* root = newNode(1); root->left = newNode(2); root->right = newNode(3); root->right->left = newNode(4); root->right->right = newNode(5); root->left->left = newNode(1); cout << getMaxSum(root) << endl; return 0;} // Java program to find maximum sum from a subset of// nodes of binary treeimport java.util.HashMap;public class FindSumOfNotAdjacentNodes { // method returns maximum sum possible from subtrees rooted // at grandChildrens of node 'node' public static int sumOfGrandChildren(Node node, HashMap<Node,Integer> mp) { int sum = 0; // call for children of left child only if it is not NULL if (node.left!=null) sum += getMaxSumUtil(node.left.left, mp) + getMaxSumUtil(node.left.right, mp); // call for children of right child only if it is not NULL if (node.right!=null) sum += getMaxSumUtil(node.right.left, mp) + getMaxSumUtil(node.right.right, mp); return sum; } // Utility method to return maximum sum rooted at node 'node' public static int getMaxSumUtil(Node node, HashMap<Node,Integer> mp) { if (node == null) return 0; // If node is already processed then return calculated // value from map if(mp.containsKey(node)) return mp.get(node); // take current node value and call for all grand children int incl = node.data + sumOfGrandChildren(node, mp); // don't take current node value and call for all children int excl = getMaxSumUtil(node.left, mp) + getMaxSumUtil(node.right, mp); // choose maximum from both above calls and store that in map mp.put(node,Math.max(incl, excl)); return mp.get(node); } // Returns maximum sum from subset of nodes // of binary tree under given constraints public static int getMaxSum(Node node) { if (node == null) return 0; HashMap<Node,Integer> mp=new HashMap<>(); return getMaxSumUtil(node, mp); } public static void main(String args[]) { Node root = new Node(1); root.left = new Node(2); root.right = new Node(3); root.right.left = new Node(4); root.right.right = new Node(5); root.left.left = new Node(1); System.out.print(getMaxSum(root)); }} /* A binary tree node structure */class Node{ int data; Node left, right; Node(int data) { this.data=data; left=right=null; }};//This code is contributed by Gaurav Tiwari # Python3 program to find# maximum sum from a subset# of nodes of binary tree # A binary tree node structureclass Node: def __init__(self, data): self.data = data self.left = None self.right = None # Utility function to create# a new Binary Tree nodedef newNode(data): temp = Node(data) return temp; # method returns maximum sum# possible from subtrees rooted# at grandChildrens of node 'node'def sumOfGrandChildren(node, mp): sum = 0; # call for children of left # child only if it is not NULL if (node.left): sum += (getMaxSumUtil(node.left.left, mp) + getMaxSumUtil(node.left.right, mp)); # call for children of right # child only if it is not NULL if (node.right): sum += (getMaxSumUtil(node.right.left, mp) + getMaxSumUtil(node.right.right, mp)); return sum; # Utility method to return# maximum sum rooted at node# 'node'def getMaxSumUtil(node, mp): if (node == None): return 0; # If node is already processed # then return calculated # value from map if node in mp: return mp[node]; # take current node value # and call for all grand children incl = (node.data + sumOfGrandChildren(node, mp)); # don't take current node # value and call for all children excl = (getMaxSumUtil(node.left, mp) + getMaxSumUtil(node.right, mp)); # choose maximum from both # above calls and store that # in map mp[node] = max(incl, excl); return mp[node]; # Returns maximum sum from# subset of nodes of binary# tree under given constraintsdef getMaxSum(node): if (node == None): return 0; mp = dict() return getMaxSumUtil(node, mp); # Driver codeif __name__=="__main__": root = newNode(1); root.left = newNode(2); root.right = newNode(3); root.right.left = newNode(4); root.right.right = newNode(5); root.left.left = newNode(1); print(getMaxSum(root)) # This code is contributed by Rutvik_56 // C# program to find maximum sum from a subset of// nodes of binary treeusing System;using System.Collections.Generic; public class FindSumOfNotAdjacentNodes{ // method returns maximum sum // possible from subtrees rooted // at grandChildrens of node 'node' public static int sumOfGrandChildren(Node node, Dictionary<Node,int> mp) { int sum = 0; // call for children of left // child only if it is not NULL if (node.left != null) sum += getMaxSumUtil(node.left.left, mp) + getMaxSumUtil(node.left.right, mp); // call for children of right // child only if it is not NULL if (node.right != null) sum += getMaxSumUtil(node.right.left, mp) + getMaxSumUtil(node.right.right, mp); return sum; } // Utility method to return maximum // sum rooted at node 'node' public static int getMaxSumUtil(Node node, Dictionary<Node,int> mp) { if (node == null) return 0; // If node is already processed then // return calculated value from map if(mp.ContainsKey(node)) return mp[node]; // take current node value and // call for all grand children int incl = node.data + sumOfGrandChildren(node, mp); // don't take current node value and // call for all children int excl = getMaxSumUtil(node.left, mp) + getMaxSumUtil(node.right, mp); // choose maximum from both above // calls and store that in map mp.Add(node,Math.Max(incl, excl)); return mp[node]; } // Returns maximum sum from subset of nodes // of binary tree under given constraints public static int getMaxSum(Node node) { if (node == null) return 0; Dictionary<Node,int> mp=new Dictionary<Node,int>(); return getMaxSumUtil(node, mp); } // Driver code public static void Main(String []args) { Node root = new Node(1); root.left = new Node(2); root.right = new Node(3); root.right.left = new Node(4); root.right.right = new Node(5); root.left.left = new Node(1); Console.Write(getMaxSum(root)); }} /* A binary tree node structure */public class Node{ public int data; public Node left, right; public Node(int data) { this.data=data; left=right=null; }}; // This code has been contributed by 29AjayKumar <script> // Javascript program to find maximum// sum from a subset of nodes of binary treeclass Node{ constructor(data) { this.left = null; this.right = null; this.data = data; }} // Method returns maximum sum possible// from subtrees rooted at grandChildrens// of node 'node'function sumOfGrandChildren(node, mp){ let sum = 0; // Call for children of left child // only if it is not NULL if (node.left!=null) sum += getMaxSumUtil(node.left.left, mp) + getMaxSumUtil(node.left.right, mp); // Call for children of right child // only if it is not NULL if (node.right!=null) sum += getMaxSumUtil(node.right.left, mp) + getMaxSumUtil(node.right.right, mp); return sum;} // Utility method to return maximum// sum rooted at node 'node'function getMaxSumUtil(node, mp){ if (node == null) return 0; // If node is already processed then return // calculated value from map if (mp.has(node)) return mp.get(node); // Take current node value and call for // all grand children let incl = node.data + sumOfGrandChildren(node, mp); // Don't take current node value and call // for all children let excl = getMaxSumUtil(node.left, mp) + getMaxSumUtil(node.right, mp); // Choose maximum from both above // calls and store that in map mp.set(node,Math.max(incl, excl)); return mp.get(node);} // Returns maximum sum from subset of nodes// of binary tree under given constraintsfunction getMaxSum(node){ if (node == null) return 0; let mp = new Map(); return getMaxSumUtil(node, mp);} // Driver codelet root = new Node(1);root.left = new Node(2);root.right = new Node(3);root.right.left = new Node(4);root.right.right = new Node(5);root.left.left = new Node(1); document.write(getMaxSum(root)); // This code is contributed by divyeshrabadiya07 </script> 11 Time complexity: O(n) Auxiliary Space: O(n) This article is contributed by Utkarsh Trivedi. Method 2 (Using pair) Return a pair for each node in the binary tree such that the first of the pair indicates maximum sum when the data of a node is included and the second indicates maximum sum when the data of a particular node is not included. C++ Java Python3 C# Javascript // C++ program to find maximum sum in Binary Tree// such that no two nodes are adjacent.#include<iostream>using namespace std; class Node{public: int data; Node* left, *right; Node(int data) { this->data = data; left = NULL; right = NULL; }}; pair<int, int> maxSumHelper(Node *root){ if (root==NULL) { pair<int, int> sum(0, 0); return sum; } pair<int, int> sum1 = maxSumHelper(root->left); pair<int, int> sum2 = maxSumHelper(root->right); pair<int, int> sum; // This node is included (Left and right children // are not included) sum.first = sum1.second + sum2.second + root->data; // This node is excluded (Either left or right // child is included) sum.second = max(sum1.first, sum1.second) + max(sum2.first, sum2.second); return sum;} int maxSum(Node *root){ pair<int, int> res = maxSumHelper(root); return max(res.first, res.second);} // Driver codeint main(){ Node *root= new Node(10); root->left= new Node(1); root->left->left= new Node(2); root->left->left->left= new Node(1); root->left->right= new Node(3); root->left->right->left= new Node(4); root->left->right->right= new Node(5); cout << maxSum(root); return 0;} // Java program to find maximum sum in Binary Tree// such that no two nodes are adjacent.public class FindSumOfNotAdjacentNodes { public static Pair maxSumHelper(Node root) { if (root==null) { Pair sum=new Pair(0, 0); return sum; } Pair sum1 = maxSumHelper(root.left); Pair sum2 = maxSumHelper(root.right); Pair sum=new Pair(0,0); // This node is included (Left and right children // are not included) sum.first = sum1.second + sum2.second + root.data; // This node is excluded (Either left or right // child is included) sum.second = Math.max(sum1.first, sum1.second) + Math.max(sum2.first, sum2.second); return sum; } // Returns maximum sum from subset of nodes // of binary tree under given constraints public static int maxSum(Node root) { Pair res=maxSumHelper(root); return Math.max(res.first, res.second); } public static void main(String args[]) { Node root= new Node(10); root.left= new Node(1); root.left.left= new Node(2); root.left.left.left= new Node(1); root.left.right= new Node(3); root.left.right.left= new Node(4); root.left.right.right= new Node(5); System.out.print(maxSum(root)); }} /* A binary tree node structure */class Node{ int data; Node left, right; Node(int data) { this.data=data; left=right=null; }}; /* Pair class */class Pair{ int first,second; Pair(int first,int second) { this.first=first; this.second=second; }}//This code is contributed by Gaurav Tiwari # Python3 program to find maximum sum in Binary# Tree such that no two nodes are adjacent. # Binary Tree Node """ utility that allocates a newNodewith the given key """class newNode: # Construct to create a newNode def __init__(self, key): self.data = key self.left = None self.right = None def maxSumHelper(root) : if (root == None): sum = [0, 0] return sum sum1 = maxSumHelper(root.left) sum2 = maxSumHelper(root.right) sum = [0, 0] # This node is included (Left and right # children are not included) sum[0] = sum1[1] + sum2[1] + root.data # This node is excluded (Either left or # right child is included) sum[1] = (max(sum1[0], sum1[1]) + max(sum2[0], sum2[1])) return sum def maxSum(root) : res = maxSumHelper(root) return max(res[0], res[1]) # Driver Codeif __name__ == '__main__': root = newNode(10) root.left = newNode(1) root.left.left = newNode(2) root.left.left.left = newNode(1) root.left.right = newNode(3) root.left.right.left = newNode(4) root.left.right.right = newNode(5) print(maxSum(root)) # This code is contributed by# Shubham Singh(SHUBHAMSINGH10) // C# program to find maximum sum in Binary Tree// such that no two nodes are adjacent.using System; public class FindSumOfNotAdjacentNodes{ public static Pair maxSumHelper(Node root) { Pair sum; if (root == null) { sum=new Pair(0, 0); return sum; } Pair sum1 = maxSumHelper(root.left); Pair sum2 = maxSumHelper(root.right); Pair sum3 = new Pair(0,0); // This node is included (Left and // right children are not included) sum3.first = sum1.second + sum2.second + root.data; // This node is excluded (Either left // or right child is included) sum3.second = Math.Max(sum1.first, sum1.second) + Math.Max(sum2.first, sum2.second); return sum3; } // Returns maximum sum from subset of nodes // of binary tree under given constraints public static int maxSum(Node root) { Pair res=maxSumHelper(root); return Math.Max(res.first, res.second); } // Driver code public static void Main() { Node root = new Node(10); root.left = new Node(1); root.left.left = new Node(2); root.left.left.left = new Node(1); root.left.right = new Node(3); root.left.right.left = new Node(4); root.left.right.right = new Node(5); Console.Write(maxSum(root)); }} /* A binary tree node structure */public class Node{ public int data; public Node left, right; public Node(int data) { this.data = data; left = right = null; }}; /* Pair class */public class Pair{ public int first,second; public Pair(int first,int second) { this.first = first; this.second = second; }} /* This code is contributed PrinciRaj1992 */ <script> // JavaScript program to find maximum sum in Binary Tree// such that no two nodes are adjacent. /* A binary tree node structure */class Node{ constructor(data) { this.data = data; this.left = null; this.right = null; }}; /* Pair class */class Pair{ constructor(first, second) { this.first = first; this.second = second; }} function maxSumHelper(root){ var sum; if (root == null) { sum=new Pair(0, 0); return sum; } var sum1 = maxSumHelper(root.left); var sum2 = maxSumHelper(root.right); var sum3 = new Pair(0,0); // This node is included (Left and // right children are not included) sum3.first = sum1.second + sum2.second + root.data; // This node is excluded (Either left // or right child is included) sum3.second = Math.max(sum1.first, sum1.second) + Math.max(sum2.first, sum2.second); return sum3;}// Returns maximum sum from subset of nodes// of binary tree under given constraintsfunction maxSum(root){ var res=maxSumHelper(root); return Math.max(res.first, res.second);}// Driver codevar root = new Node(10);root.left = new Node(1);root.left.left = new Node(2);root.left.left.left = new Node(1);root.left.right = new Node(3);root.left.right.left = new Node(4);root.left.right.right = new Node(5);document.write(maxSum(root)); </script> 21 Time complexity: O(n) Auxiliary Space: O(n)Thanks to Surbhi Rastogi for suggesting this method. Method 3(Using dynamic programming) Store the maximum sum by including a node or excluding the node in a dp array or unordered map. Recursively calls for grandchildren of nodes if the node is included or calls for neighbours if the node is excluded. C++ Java Python3 C# Javascript // C++ program to find maximum sum in Binary Tree// such that no two nodes are adjacent.#include <bits/stdc++.h>#include <iostream>using namespace std; class Node {public: int data; Node *left, *right; Node(int data) { this->data = data; left = NULL; right = NULL; }};// declare map /dp array as globalunordered_map<Node*, int> umap;int maxSum(Node* root){ // base case if (!root) return 0; // if the max sum from the node is already in // map,return the value if (umap[root]) return umap[root]; // if the current node(root) is included in result // then find maximum sum int inc = root->data; // if left of node exists, add their grandchildren if (root->left) { inc += maxSum(root->left->left) + maxSum(root->left->right); } // if right of node exist,add their grandchildren if (root->right) { inc += maxSum(root->right->left) + maxSum(root->right->right); } // if the current node(root) is excluded, find the // maximum sum int ex = maxSum(root->left) + maxSum(root->right); // store the maximum of including & excluding the node // in map umap[root] = max(inc, ex); return max(inc, ex);} // Driver codeint main(){ Node* root = new Node(10); root->left = new Node(1); root->left->left = new Node(2); root->left->left->left = new Node(1); root->left->right = new Node(3); root->left->right->left = new Node(4); root->left->right->right = new Node(5); cout << maxSum(root); return 0;} /*package whatever //do not write package name here */ import java.io.*;import java.util.*; // Java program for the above approachclass GFG { // Java program to find maximum sum in Binary Tree// such that no two nodes are adjacent. // declare map /dp array as globalstatic HashMap<Node,Integer> umap = new HashMap<>();static int maxSum(Node root){ // base case if (root == null) return 0; // if the max sum from the node is already in // map,return the value if (umap.containsKey(root)) return umap.get(root); // if the current node(root) is included in result // then find maximum sum int inc = root.data; // if left of node exists, add their grandchildren if (root.left != null) { inc += maxSum(root.left.left) + maxSum(root.left.right); } // if right of node exist,add their grandchildren if (root.right != null) { inc += maxSum(root.right.left) + maxSum(root.right.right); } // if the current node(root) is excluded, find the // maximum sum int ex = maxSum(root.left) + maxSum(root.right); // store the maximum of including & excluding the node // in map umap.put(root, Math.max(inc, ex)); return Math.max(inc, ex);} public static void main(String args[]){ Node root = new Node(10); root.left = new Node(1); root.left.left = new Node(2); root.left.left.left = new Node(1); root.left.right = new Node(3); root.left.right.left = new Node(4); root.left.right.right = new Node(5); System.out.println(maxSum(root));} } class Node { public int data; public Node left, right; public Node(int data) { this.data = data; left = null; right = null; }}; // This code is contributed by code_hunt. # Python program to find maximum sum in Binary Tree# such that no two nodes are adjacent.class Node: def __init__(self,data): self.data = data self.left = None self.right = None # declare map /dp array as globalumap = {}def maxSum(root): global umap # base case if (root == None): return 0 # if the max sum from the node is already in # map,return the value if (root in umap): return umap[root] # if the current node(root) is included in result # then find maximum sum inc = root.data # if left of node exists, add their grandchildren if (root.left): inc += maxSum(root.left.left) + maxSum(root.left.right) # if right of node exist,add their grandchildren if (root.right): inc += maxSum(root.right.left) + maxSum(root.right.right) # if the current node(root) is excluded, find the # maximum sum ex = maxSum(root.left) + maxSum(root.right) # store the maximum of including & excluding the node # in map umap[root]=max(inc, ex) return max(inc, ex) # Driver coderoot = Node(10)root.left = Node(1)root.left.left = Node(2)root.left.left.left = Node(1)root.left.right = Node(3)root.left.right.left = Node(4)root.left.right.right = Node(5)print(maxSum(root)) # This code is contributed by shinjanpatra // C# program to find maximum sum in Binary Tree// such that no two nodes are adjacent.using System;using System.Collections.Generic; /* A binary tree node structure */public class Node { public int data; public Node left, right; public Node(int data) { this.data = data; left = right = null; }}; class GFG { // declare map /dp array as global static Dictionary<Node, int> umap = new Dictionary<Node, int>(); static int maxSum(Node root) { // base case if (root == null) return 0; // if the max sum from the node is already in // map,return the value if (umap.ContainsKey(root)) return umap[root]; // if the current node(root) is included in result // then find maximum sum int inc = root.data; // if left of node exists, add their grandchildren if (root.left != null) { inc += maxSum(root.left.left) + maxSum(root.left.right); } // if right of node exist,add their grandchildren if (root.right != null) { inc += maxSum(root.right.left) + maxSum(root.right.right); } // if the current node(root) is excluded, find the // maximum sum int ex = maxSum(root.left) + maxSum(root.right); // store the maximum of including & excluding the // node in map umap.Add(root, Math.Max(inc, ex)); return Math.Max(inc, ex); } // Driver code public static void Main(String[] args) { Node root = new Node(10); root.left = new Node(1); root.left.left = new Node(2); root.left.left.left = new Node(1); root.left.right = new Node(3); root.left.right.left = new Node(4); root.left.right.right = new Node(5); Console.Write(maxSum(root)); }} // This code is contributed by Abhijeet Kumar(abhijeet19403) <script> // JavaScript program to find maximum sum in Binary Tree// such that no two nodes are adjacent.class Node { constructor(data) { this.data = data; this.left = null; this.right = null; }} // declare map /dp array as globallet umap = new Map();function maxSum(root){ // base case if (!root) return 0; // if the max sum from the node is already in // map,return the value if (umap.has(root)) return umap.get(root); // if the current node(root) is included in result // then find maximum sum let inc = root.data; // if left of node exists, add their grandchildren if (root.left) { inc += maxSum(root.left.left) + maxSum(root.left.right); } // if right of node exist,add their grandchildren if (root.right) { inc += maxSum(root.right.left) + maxSum(root.right.right); } // if the current node(root) is excluded, find the // maximum sum let ex = maxSum(root.left) + maxSum(root.right); // store the maximum of including & excluding the node // in map umap.set(root,Math.max(inc, ex)); return Math.max(inc, ex);} // Driver codelet root = new Node(10);root.left = new Node(1);root.left.left = new Node(2);root.left.left.left = new Node(1);root.left.right = new Node(3);root.left.right.left = new Node(4);root.left.right.right = new Node(5);document.write(maxSum(root)); // This code is contributed by shinjanpatra</script> 21 Time complexity: O(n)Auxiliary Space: O(n) This article is contributed by Harsh.<https://auth.geeksforgeeks.org/user/harshchandekar10/profile> Method 4 (Simple tree traversal) For every node, we find the following: Maximum sum of non-adjacent nodes including the node.Maximum sum of non-adjacent nodes excluding the node. Maximum sum of non-adjacent nodes including the node. Maximum sum of non-adjacent nodes excluding the node. Now, we return both the values in the recursive call. The parent node of the previously calculated node gets the maximum sum (including & excluding) the child node. Accordingly, the parent now calculates the maximum sum(including & excluding) and returns. This process continues till root node. Finally, we return the max(sum including root, sum excluding root). Time Complexity: O(n) Space Complexity: O(1) Python3 Javascript class Node: def __init__(self, val): self.data = val self.left = None self.right = None class Solution: def max_sum(self, root): if not root: return 0, 0 no_root_l, root_l = self.max_sum(root.left) no_root_r, root_r = self.max_sum(root.right) root_sum_max = max(root.data, root.data+no_root_l, root.data+no_root_r, root.data+no_root_r+no_root_l) no_root_sum_max = max(root_l, root_r, root_l + root_r, no_root_l+no_root_r, root_l + no_root_r, root_r + no_root_l) return no_root_sum_max, root_sum_max def getMaxSum(self, root): return max(self.max_sum(root)) <script> // JavaScript code to implement the approach class Node{ constructor(val){ this.data = val this.left = null this.right = null }} class Solution{ max_sum(root){ if(root == null) return 0, 0 let no_root_l, root_l = this.max_sum(root.left) let no_root_r, root_r = this.max_sum(root.right) let root_sum_max = Math.max(root.data, root.data+no_root_l, root.data+no_root_r, root.data+no_root_r+no_root_l) let no_root_sum_max = Math.max(root_l, root_r, root_l + root_r, no_root_l+no_root_r, root_l + no_root_r, root_r + no_root_l) return no_root_sum_max, root_sum_max } getMaxSum(root){ return Math.max(this.max_sum(root)) }} // This code is contributed by shinjanpatra </script> This method is contributed by Thatikonda Aditya. Method 5(Using Memoization) Approach: For every node, we can either choose it or leave it and pass on this information to children. Since we are passing on this info of the parent being selected or not, we don’t need to worry about the grandchildren of the node. So for every node, we do the following: If the parent is selected, we don’t select the current node and move on to the children.if the parent is not selected, then we will either select or not select this node; in either case, we pass that info to the children. If the parent is selected, we don’t select the current node and move on to the children. if the parent is not selected, then we will either select or not select this node; in either case, we pass that info to the children. Following is the implementation of the above method: C++ Java Python3 C# // C++ program to find maximum sum from a subset of// non-adjacent nodes of binary tree#include <bits/stdc++.h>using namespace std; /* A binary tree node structure */struct Node{ int data; struct Node *left, *right;}; /* Utility function to create a new Binary Tree node */struct Node *newNode(int data){ struct Node *temp = new struct Node; temp->data = data; temp->left = temp->right = NULL; return temp;} // Delaration of the vector to store the answervector<vector<int>> dp; // Variables and function to index the given Binary tree// This indexing will be used in dpint cnt = 0;Node *temp;Node *giveIndex(Node *root){ if (root == NULL) return NULL; // give the index to the current node and increment the index for next nodes. Node *newNode1 = newNode(cnt++); // Recursively calling right and left subtree newNode1->left = giveIndex(root->left); newNode1->right = giveIndex(root->right); return newNode1;} // Memoization function to store the answerint solve(Node *root, int b, Node *temp){ if (root == NULL) return 0; // If the answer is already calculated return that answer if (dp[temp->data][b] != -1) return dp[temp->data][b]; // Variable to store the answer for the current node. int res; // if the parent is not selected then we can either select ot not select this node. if (b == 0) res = max(root->data + solve(root->right, 1, temp->right) + solve(root->left, 1, temp->left), solve(root->right, 0, temp->right) + solve(root->left, 0, temp->left)); // If parent is selected then we can't select this node. else res = solve(root->right, 0, temp->right) + solve(root->left, 0, temp->left); // return the annswer return dp[temp->data][b] = res;}int getMaxSum(Node *root){ // Initialization of the dp dp = vector<vector<int>>(100, vector<int>(2, -1)); // Calling the indexing function temp = giveIndex(root); // calling the solve function for root with parent not selected int res = solve(root, 0, temp); return res;} // Driver code to test above methodsint main(){ // TEST 1 Node *root = newNode(1); root->left = newNode(2); root->right = newNode(3); root->right->left = newNode(4); root->right->right = newNode(5); root->left->left = newNode(1); cout << getMaxSum(root) << endl; // TEST 2 Node *root2 = newNode(10); root2->left = newNode(1); root2->left->left = newNode(2); root2->left->left->left = newNode(1); root2->left->right = newNode(3); root2->left->right->left = newNode(4); root2->left->right->right = newNode(5); cout << getMaxSum(root2); return 0;}//Code contributed by Anirudh Singh. // Java program to find maximum sum from a subset of// non-adjacent nodes of binary tree import java.util.HashMap; /* A binary tree node structure */class Node { int data; Node left, right; Node(int data) { this.data = data; left = right = null; }}; class gfg { // Delaration of the vector to store the answer static int[][] dp; // Variables and function to index the given Binary tree // This indexing will be used in dp static int cnt = 0; static Node temp; static Node giveIndex(Node root) { if (root == null) return null; // give the index to the current node and increment // the index for next nodes. Node newNode1 = new Node(cnt++); // Recursively calling right and left subtree newNode1.left = giveIndex(root.left); newNode1.right = giveIndex(root.right); return newNode1; } // Memoization function to store the answer static int solve(Node root, int b, Node temp) { if (root == null) return 0; // If the answer is already calculated return that // answer if (dp[temp.data][b] != -1) return dp[temp.data][b]; // Variable to store the answer for the current // node. int res; // if the parent is not selected then we can either // select ot not select this node. if (b == 0) res = Math.max(root.data + solve(root.right, 1, temp.right) + solve(root.left, 1, temp.left), solve(root.right, 0, temp.right) + solve(root.left, 0, temp.left)); // If parent is selected then we can't select this // node. else res = solve(root.right, 0, temp.right) + solve(root.left, 0, temp.left); // return the annswer return dp[temp.data][b] = res; } static int getMaxSum(Node root) { // Initialization of the dp dp = new int[100][2]; for(int i=0;i<100;i++) { dp[i][0] = -1; dp[i][1] = -1; } // Calling the indexing function temp = giveIndex(root); // calling the solve function for root with parent // not selected int res = solve(root, 0, temp); return res; } public static void main(String args[]) { // TEST 1 Node root = new Node(1); root.left = new Node(2); root.right = new Node(3); root.right.left = new Node(4); root.right.right = new Node(5); root.left.left = new Node(1); System.out.println(getMaxSum(root)); // TEST 2 Node root2 = new Node(10); root2.left = new Node(1); root2.left.left = new Node(2); root2.left.left.left = new Node(1); root2.left.right = new Node(3); root2.left.right.left = new Node(4); root2.left.right.right = new Node(5); System.out.print(getMaxSum(root2)); }} // This code is contributed by Abhijeet Kumar(abhijeet19403) # Python3 program to find maximum sum from a subset of# non-adjacent nodes of binary tree # A binary tree node structureclass newNode: def __init__(self, data): self.data = data self.left = None self.right = None dp = [[]] # Variables and function to index the given Binary tree# This indexing will be used in dpcnt = 0temp = newNode(0)def giveIndex(root): if (root == None): return None # give the index to the current node and increment the index for next nodes. global cnt cnt += 1 newNode1 = newNode(cnt) # Recursively calling right and left subtree newNode1.left = giveIndex(root.left) newNode1.right = giveIndex(root.right) return newNode1 # Memoization function to store the answerdef solve(root, b, temp): if (root == None): return 0 # If the answer is already calculated return that answer if (dp[temp.data][b] != -1): return dp[temp.data][b] # Variable to store the answer for the current node. res = 0 # if the parent is not selected then we can either select ot not select this node. if (b == 0): res = max(root.data + solve(root.right, 1, temp.right) + solve(root.left, 1, temp.left), solve(root.right, 0, temp.right) + solve(root.left, 0, temp.left)) # If parent is selected then we can't select this node. else: res = solve(root.right, 0, temp.right) + solve(root.left, 0, temp.left) # return the annswer dp[temp.data][b] = res return res def getMaxSum(root): # Initialization of the dp global dp dp = [[-1 for x in range(2)] for x in range(100)] # Calling the indexing function temp = giveIndex(root) # calling the solve function for root with parent not selected res = solve(root, 0, temp) return res # Driver codeif __name__=="__main__": # TEST 1 root = newNode(1) root.left = newNode(2) root.right = newNode(3) root.right.left = newNode(4) root.right.right = newNode(5) root.left.left = newNode(1) print(getMaxSum(root)) # TEST 2 root2 = newNode(10) root2.left = newNode(1) root2.left.left = newNode(2) root2.left.left.left = newNode(1) root2.left.right = newNode(3) root2.left.right.left = newNode(4) root2.left.right.right = newNode(5) print(getMaxSum(root2)) # This code is contributed by Abhijeet Kumar(abhijeet19403) // C# program to find maximum sum from a subset of// non-adjacent nodes of binary tree using System;using System.Collections.Generic; /* A binary tree node structure */public class Node{ public int data; public Node left, right; public Node(int data) { this.data=data; left=right=null; }}; class gfg{ // Delaration of the vector to store the answer static int[,] dp; // Variables and function to index the given Binary tree // This indexing will be used in dp static int cnt = 0; static Node temp; static Node giveIndex(Node root) { if (root == null) return null; // give the index to the current node and increment // the index for next nodes. Node newNode1 = new Node(cnt++); // Recursively calling right and left subtree newNode1.left = giveIndex(root.left); newNode1.right = giveIndex(root.right); return newNode1; } // Memoization function to store the answer static int solve(Node root, int b, Node temp) { if (root == null) return 0; // If the answer is already calculated return that // answer if (dp[temp.data,b] != -1) return dp[temp.data,b]; // Variable to store the answer for the current // node. int res; // if the parent is not selected then we can either // select ot not select this node. if (b == 0) res = Math.Max(root.data + solve(root.right, 1, temp.right) + solve(root.left, 1, temp.left), solve(root.right, 0, temp.right) + solve(root.left, 0, temp.left)); // If parent is selected then we can't select this // node. else res = solve(root.right, 0, temp.right) + solve(root.left, 0, temp.left); // return the annswer return dp[temp.data,b] = res; } static int getMaxSum(Node root) { // Initialization of the dp dp = new int[100,2]; for(int i=0;i<100;i++) { dp[i,0] = -1; dp[i,1] = -1; } // Calling the indexing function temp = giveIndex(root); // calling the solve function for root with parent // not selected int res = solve(root, 0, temp); return res; } // Driver code public static void Main(String []args) { // TEST 1 Node root = new Node(1); root.left = new Node(2); root.right = new Node(3); root.right.left = new Node(4); root.right.right = new Node(5); root.left.left = new Node(1); Console.WriteLine(getMaxSum(root)); // TEST 2 Node root2 = new Node(10); root2.left = new Node(1); root2.left.left = new Node(2); root2.left.left.left = new Node(1); root2.left.right = new Node(3); root2.left.right.left = new Node(4); root2.left.right.right = new Node(5); Console.Write(getMaxSum(root2)); }} // This code has been contributed by Abhijeet Kumar(abhijeet19403) 11 21 Time Complexity: O(N) Space Complexity: O(N) This method and implementation is contributed by Anirudh Singh. If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to review-team@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks. Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above. Sai Krishna Chowrigari _Gaurav_Tiwari SHUBHAMSINGH10 princiraj1992 29AjayKumar rutvik_56 reapedjuggler itsok divyeshrabadiya07 ganesh227 harshchandekar10 taditya3007 anand00525 germanshephered48 saurabh1990aror clintra shinjanpatra anirudhsingh11 abhijeet19403 Tree Tree Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 52, "s": 24, "text": "\n11 Jul, 2022" }, { "code": null, "e": 406, "s": 52, "text": "Given a binary tree with a value associated with each node, we need to choose a subset of these nodes such that the sum of selected nodes is maximum under a constraint that no two chosen nodes in the subset should be directly connected, that is, if we have taken a node in our sum then we can’t take any of its children in consideration and vice versa. " }, { "code": null, "e": 418, "s": 406, "text": "Examples: " }, { "code": null, "e": 539, "s": 418, "text": "In the above binary tree, chosen nodes are encircled \nand are not directly connected, and their sum is\nmaximum possible." }, { "code": null, "e": 622, "s": 539, "text": "Recommended: Please solve it on “PRACTICE” first before moving on to the solution." }, { "code": null, "e": 1599, "s": 622, "text": "Method 1 We can solve this problem by considering the fact that both node and its children can’t be in sum at the same time, so when we take a node into our sum, we will call recursively for its grandchildren or if we don’t take this node then we will call for all its children nodes and finally we will choose maximum from both of the results. It can be seen easily that the above approach can lead to solving the same subproblem many times, for example in the above diagram node 1 calls node 4 and 5 when its value is chosen and node 3 also calls them when its value is not chosen so these nodes are processed more than once. We can stop solving these nodes more than once by memorizing the result at all nodes. In the below code, a map is used for memorizing the result, which stores the development of the complete subtree rooted at a node in the map so that if it is called again, the value is not calculated again instead stored value from the map is returned directly. " }, { "code": null, "e": 1653, "s": 1599, "text": "Please see the below code for a better understanding." }, { "code": null, "e": 1657, "s": 1653, "text": "C++" }, { "code": null, "e": 1662, "s": 1657, "text": "Java" }, { "code": null, "e": 1670, "s": 1662, "text": "Python3" }, { "code": null, "e": 1673, "s": 1670, "text": "C#" }, { "code": null, "e": 1684, "s": 1673, "text": "Javascript" }, { "code": "// C++ program to find maximum sum from a subset of// nodes of binary tree#include <bits/stdc++.h>using namespace std; /* A binary tree node structure */struct node{ int data; struct node *left, *right;}; /* Utility function to create a new Binary Tree node */struct node* newNode(int data){ struct node *temp = new struct node; temp->data = data; temp->left = temp->right = NULL; return temp;} // Declaration of methodsint sumOfGrandChildren(node* node);int getMaxSum(node* node);int getMaxSumUtil(node* node, map<struct node*, int>& mp); // method returns maximum sum possible from subtrees rooted// at grandChildrens of node 'node'int sumOfGrandChildren(node* node, map<struct node*, int>& mp){ int sum = 0; // call for children of left child only if it is not NULL if (node->left) sum += getMaxSumUtil(node->left->left, mp) + getMaxSumUtil(node->left->right, mp); // call for children of right child only if it is not NULL if (node->right) sum += getMaxSumUtil(node->right->left, mp) + getMaxSumUtil(node->right->right, mp); return sum;} // Utility method to return maximum sum rooted at node 'node'int getMaxSumUtil(node* node, map<struct node*, int>& mp){ if (node == NULL) return 0; // If node is already processed then return calculated // value from map if (mp.find(node) != mp.end()) return mp[node]; // take current node value and call for all grand children int incl = node->data + sumOfGrandChildren(node, mp); // don't take current node value and call for all children int excl = getMaxSumUtil(node->left, mp) + getMaxSumUtil(node->right, mp); // choose maximum from both above calls and store that in map mp[node] = max(incl, excl); return mp[node];} // Returns maximum sum from subset of nodes// of binary tree under given constraintsint getMaxSum(node* node){ if (node == NULL) return 0; map<struct node*, int> mp; return getMaxSumUtil(node, mp);} // Driver code to test above methodsint main(){ node* root = newNode(1); root->left = newNode(2); root->right = newNode(3); root->right->left = newNode(4); root->right->right = newNode(5); root->left->left = newNode(1); cout << getMaxSum(root) << endl; return 0;}", "e": 4009, "s": 1684, "text": null }, { "code": "// Java program to find maximum sum from a subset of// nodes of binary treeimport java.util.HashMap;public class FindSumOfNotAdjacentNodes { // method returns maximum sum possible from subtrees rooted // at grandChildrens of node 'node' public static int sumOfGrandChildren(Node node, HashMap<Node,Integer> mp) { int sum = 0; // call for children of left child only if it is not NULL if (node.left!=null) sum += getMaxSumUtil(node.left.left, mp) + getMaxSumUtil(node.left.right, mp); // call for children of right child only if it is not NULL if (node.right!=null) sum += getMaxSumUtil(node.right.left, mp) + getMaxSumUtil(node.right.right, mp); return sum; } // Utility method to return maximum sum rooted at node 'node' public static int getMaxSumUtil(Node node, HashMap<Node,Integer> mp) { if (node == null) return 0; // If node is already processed then return calculated // value from map if(mp.containsKey(node)) return mp.get(node); // take current node value and call for all grand children int incl = node.data + sumOfGrandChildren(node, mp); // don't take current node value and call for all children int excl = getMaxSumUtil(node.left, mp) + getMaxSumUtil(node.right, mp); // choose maximum from both above calls and store that in map mp.put(node,Math.max(incl, excl)); return mp.get(node); } // Returns maximum sum from subset of nodes // of binary tree under given constraints public static int getMaxSum(Node node) { if (node == null) return 0; HashMap<Node,Integer> mp=new HashMap<>(); return getMaxSumUtil(node, mp); } public static void main(String args[]) { Node root = new Node(1); root.left = new Node(2); root.right = new Node(3); root.right.left = new Node(4); root.right.right = new Node(5); root.left.left = new Node(1); System.out.print(getMaxSum(root)); }} /* A binary tree node structure */class Node{ int data; Node left, right; Node(int data) { this.data=data; left=right=null; }};//This code is contributed by Gaurav Tiwari", "e": 6373, "s": 4009, "text": null }, { "code": "# Python3 program to find# maximum sum from a subset# of nodes of binary tree # A binary tree node structureclass Node: def __init__(self, data): self.data = data self.left = None self.right = None # Utility function to create# a new Binary Tree nodedef newNode(data): temp = Node(data) return temp; # method returns maximum sum# possible from subtrees rooted# at grandChildrens of node 'node'def sumOfGrandChildren(node, mp): sum = 0; # call for children of left # child only if it is not NULL if (node.left): sum += (getMaxSumUtil(node.left.left, mp) + getMaxSumUtil(node.left.right, mp)); # call for children of right # child only if it is not NULL if (node.right): sum += (getMaxSumUtil(node.right.left, mp) + getMaxSumUtil(node.right.right, mp)); return sum; # Utility method to return# maximum sum rooted at node# 'node'def getMaxSumUtil(node, mp): if (node == None): return 0; # If node is already processed # then return calculated # value from map if node in mp: return mp[node]; # take current node value # and call for all grand children incl = (node.data + sumOfGrandChildren(node, mp)); # don't take current node # value and call for all children excl = (getMaxSumUtil(node.left, mp) + getMaxSumUtil(node.right, mp)); # choose maximum from both # above calls and store that # in map mp[node] = max(incl, excl); return mp[node]; # Returns maximum sum from# subset of nodes of binary# tree under given constraintsdef getMaxSum(node): if (node == None): return 0; mp = dict() return getMaxSumUtil(node, mp); # Driver codeif __name__==\"__main__\": root = newNode(1); root.left = newNode(2); root.right = newNode(3); root.right.left = newNode(4); root.right.right = newNode(5); root.left.left = newNode(1); print(getMaxSum(root)) # This code is contributed by Rutvik_56", "e": 8410, "s": 6373, "text": null }, { "code": "// C# program to find maximum sum from a subset of// nodes of binary treeusing System;using System.Collections.Generic; public class FindSumOfNotAdjacentNodes{ // method returns maximum sum // possible from subtrees rooted // at grandChildrens of node 'node' public static int sumOfGrandChildren(Node node, Dictionary<Node,int> mp) { int sum = 0; // call for children of left // child only if it is not NULL if (node.left != null) sum += getMaxSumUtil(node.left.left, mp) + getMaxSumUtil(node.left.right, mp); // call for children of right // child only if it is not NULL if (node.right != null) sum += getMaxSumUtil(node.right.left, mp) + getMaxSumUtil(node.right.right, mp); return sum; } // Utility method to return maximum // sum rooted at node 'node' public static int getMaxSumUtil(Node node, Dictionary<Node,int> mp) { if (node == null) return 0; // If node is already processed then // return calculated value from map if(mp.ContainsKey(node)) return mp[node]; // take current node value and // call for all grand children int incl = node.data + sumOfGrandChildren(node, mp); // don't take current node value and // call for all children int excl = getMaxSumUtil(node.left, mp) + getMaxSumUtil(node.right, mp); // choose maximum from both above // calls and store that in map mp.Add(node,Math.Max(incl, excl)); return mp[node]; } // Returns maximum sum from subset of nodes // of binary tree under given constraints public static int getMaxSum(Node node) { if (node == null) return 0; Dictionary<Node,int> mp=new Dictionary<Node,int>(); return getMaxSumUtil(node, mp); } // Driver code public static void Main(String []args) { Node root = new Node(1); root.left = new Node(2); root.right = new Node(3); root.right.left = new Node(4); root.right.right = new Node(5); root.left.left = new Node(1); Console.Write(getMaxSum(root)); }} /* A binary tree node structure */public class Node{ public int data; public Node left, right; public Node(int data) { this.data=data; left=right=null; }}; // This code has been contributed by 29AjayKumar", "e": 10964, "s": 8410, "text": null }, { "code": "<script> // Javascript program to find maximum// sum from a subset of nodes of binary treeclass Node{ constructor(data) { this.left = null; this.right = null; this.data = data; }} // Method returns maximum sum possible// from subtrees rooted at grandChildrens// of node 'node'function sumOfGrandChildren(node, mp){ let sum = 0; // Call for children of left child // only if it is not NULL if (node.left!=null) sum += getMaxSumUtil(node.left.left, mp) + getMaxSumUtil(node.left.right, mp); // Call for children of right child // only if it is not NULL if (node.right!=null) sum += getMaxSumUtil(node.right.left, mp) + getMaxSumUtil(node.right.right, mp); return sum;} // Utility method to return maximum// sum rooted at node 'node'function getMaxSumUtil(node, mp){ if (node == null) return 0; // If node is already processed then return // calculated value from map if (mp.has(node)) return mp.get(node); // Take current node value and call for // all grand children let incl = node.data + sumOfGrandChildren(node, mp); // Don't take current node value and call // for all children let excl = getMaxSumUtil(node.left, mp) + getMaxSumUtil(node.right, mp); // Choose maximum from both above // calls and store that in map mp.set(node,Math.max(incl, excl)); return mp.get(node);} // Returns maximum sum from subset of nodes// of binary tree under given constraintsfunction getMaxSum(node){ if (node == null) return 0; let mp = new Map(); return getMaxSumUtil(node, mp);} // Driver codelet root = new Node(1);root.left = new Node(2);root.right = new Node(3);root.right.left = new Node(4);root.right.right = new Node(5);root.left.left = new Node(1); document.write(getMaxSum(root)); // This code is contributed by divyeshrabadiya07 </script>", "e": 12905, "s": 10964, "text": null }, { "code": null, "e": 12908, "s": 12905, "text": "11" }, { "code": null, "e": 12930, "s": 12908, "text": "Time complexity: O(n)" }, { "code": null, "e": 12952, "s": 12930, "text": "Auxiliary Space: O(n)" }, { "code": null, "e": 13000, "s": 12952, "text": "This article is contributed by Utkarsh Trivedi." }, { "code": null, "e": 13249, "s": 13000, "text": "Method 2 (Using pair) Return a pair for each node in the binary tree such that the first of the pair indicates maximum sum when the data of a node is included and the second indicates maximum sum when the data of a particular node is not included. " }, { "code": null, "e": 13253, "s": 13249, "text": "C++" }, { "code": null, "e": 13258, "s": 13253, "text": "Java" }, { "code": null, "e": 13266, "s": 13258, "text": "Python3" }, { "code": null, "e": 13269, "s": 13266, "text": "C#" }, { "code": null, "e": 13280, "s": 13269, "text": "Javascript" }, { "code": "// C++ program to find maximum sum in Binary Tree// such that no two nodes are adjacent.#include<iostream>using namespace std; class Node{public: int data; Node* left, *right; Node(int data) { this->data = data; left = NULL; right = NULL; }}; pair<int, int> maxSumHelper(Node *root){ if (root==NULL) { pair<int, int> sum(0, 0); return sum; } pair<int, int> sum1 = maxSumHelper(root->left); pair<int, int> sum2 = maxSumHelper(root->right); pair<int, int> sum; // This node is included (Left and right children // are not included) sum.first = sum1.second + sum2.second + root->data; // This node is excluded (Either left or right // child is included) sum.second = max(sum1.first, sum1.second) + max(sum2.first, sum2.second); return sum;} int maxSum(Node *root){ pair<int, int> res = maxSumHelper(root); return max(res.first, res.second);} // Driver codeint main(){ Node *root= new Node(10); root->left= new Node(1); root->left->left= new Node(2); root->left->left->left= new Node(1); root->left->right= new Node(3); root->left->right->left= new Node(4); root->left->right->right= new Node(5); cout << maxSum(root); return 0;}", "e": 14547, "s": 13280, "text": null }, { "code": "// Java program to find maximum sum in Binary Tree// such that no two nodes are adjacent.public class FindSumOfNotAdjacentNodes { public static Pair maxSumHelper(Node root) { if (root==null) { Pair sum=new Pair(0, 0); return sum; } Pair sum1 = maxSumHelper(root.left); Pair sum2 = maxSumHelper(root.right); Pair sum=new Pair(0,0); // This node is included (Left and right children // are not included) sum.first = sum1.second + sum2.second + root.data; // This node is excluded (Either left or right // child is included) sum.second = Math.max(sum1.first, sum1.second) + Math.max(sum2.first, sum2.second); return sum; } // Returns maximum sum from subset of nodes // of binary tree under given constraints public static int maxSum(Node root) { Pair res=maxSumHelper(root); return Math.max(res.first, res.second); } public static void main(String args[]) { Node root= new Node(10); root.left= new Node(1); root.left.left= new Node(2); root.left.left.left= new Node(1); root.left.right= new Node(3); root.left.right.left= new Node(4); root.left.right.right= new Node(5); System.out.print(maxSum(root)); }} /* A binary tree node structure */class Node{ int data; Node left, right; Node(int data) { this.data=data; left=right=null; }}; /* Pair class */class Pair{ int first,second; Pair(int first,int second) { this.first=first; this.second=second; }}//This code is contributed by Gaurav Tiwari", "e": 16238, "s": 14547, "text": null }, { "code": "# Python3 program to find maximum sum in Binary# Tree such that no two nodes are adjacent. # Binary Tree Node \"\"\" utility that allocates a newNodewith the given key \"\"\"class newNode: # Construct to create a newNode def __init__(self, key): self.data = key self.left = None self.right = None def maxSumHelper(root) : if (root == None): sum = [0, 0] return sum sum1 = maxSumHelper(root.left) sum2 = maxSumHelper(root.right) sum = [0, 0] # This node is included (Left and right # children are not included) sum[0] = sum1[1] + sum2[1] + root.data # This node is excluded (Either left or # right child is included) sum[1] = (max(sum1[0], sum1[1]) + max(sum2[0], sum2[1])) return sum def maxSum(root) : res = maxSumHelper(root) return max(res[0], res[1]) # Driver Codeif __name__ == '__main__': root = newNode(10) root.left = newNode(1) root.left.left = newNode(2) root.left.left.left = newNode(1) root.left.right = newNode(3) root.left.right.left = newNode(4) root.left.right.right = newNode(5) print(maxSum(root)) # This code is contributed by# Shubham Singh(SHUBHAMSINGH10)", "e": 17442, "s": 16238, "text": null }, { "code": "// C# program to find maximum sum in Binary Tree// such that no two nodes are adjacent.using System; public class FindSumOfNotAdjacentNodes{ public static Pair maxSumHelper(Node root) { Pair sum; if (root == null) { sum=new Pair(0, 0); return sum; } Pair sum1 = maxSumHelper(root.left); Pair sum2 = maxSumHelper(root.right); Pair sum3 = new Pair(0,0); // This node is included (Left and // right children are not included) sum3.first = sum1.second + sum2.second + root.data; // This node is excluded (Either left // or right child is included) sum3.second = Math.Max(sum1.first, sum1.second) + Math.Max(sum2.first, sum2.second); return sum3; } // Returns maximum sum from subset of nodes // of binary tree under given constraints public static int maxSum(Node root) { Pair res=maxSumHelper(root); return Math.Max(res.first, res.second); } // Driver code public static void Main() { Node root = new Node(10); root.left = new Node(1); root.left.left = new Node(2); root.left.left.left = new Node(1); root.left.right = new Node(3); root.left.right.left = new Node(4); root.left.right.right = new Node(5); Console.Write(maxSum(root)); }} /* A binary tree node structure */public class Node{ public int data; public Node left, right; public Node(int data) { this.data = data; left = right = null; }}; /* Pair class */public class Pair{ public int first,second; public Pair(int first,int second) { this.first = first; this.second = second; }} /* This code is contributed PrinciRaj1992 */", "e": 19242, "s": 17442, "text": null }, { "code": "<script> // JavaScript program to find maximum sum in Binary Tree// such that no two nodes are adjacent. /* A binary tree node structure */class Node{ constructor(data) { this.data = data; this.left = null; this.right = null; }}; /* Pair class */class Pair{ constructor(first, second) { this.first = first; this.second = second; }} function maxSumHelper(root){ var sum; if (root == null) { sum=new Pair(0, 0); return sum; } var sum1 = maxSumHelper(root.left); var sum2 = maxSumHelper(root.right); var sum3 = new Pair(0,0); // This node is included (Left and // right children are not included) sum3.first = sum1.second + sum2.second + root.data; // This node is excluded (Either left // or right child is included) sum3.second = Math.max(sum1.first, sum1.second) + Math.max(sum2.first, sum2.second); return sum3;}// Returns maximum sum from subset of nodes// of binary tree under given constraintsfunction maxSum(root){ var res=maxSumHelper(root); return Math.max(res.first, res.second);}// Driver codevar root = new Node(10);root.left = new Node(1);root.left.left = new Node(2);root.left.left.left = new Node(1);root.left.right = new Node(3);root.left.right.left = new Node(4);root.left.right.right = new Node(5);document.write(maxSum(root)); </script>", "e": 20630, "s": 19242, "text": null }, { "code": null, "e": 20633, "s": 20630, "text": "21" }, { "code": null, "e": 20655, "s": 20633, "text": "Time complexity: O(n)" }, { "code": null, "e": 20729, "s": 20655, "text": "Auxiliary Space: O(n)Thanks to Surbhi Rastogi for suggesting this method." }, { "code": null, "e": 20765, "s": 20729, "text": "Method 3(Using dynamic programming)" }, { "code": null, "e": 20979, "s": 20765, "text": "Store the maximum sum by including a node or excluding the node in a dp array or unordered map. Recursively calls for grandchildren of nodes if the node is included or calls for neighbours if the node is excluded." }, { "code": null, "e": 20983, "s": 20979, "text": "C++" }, { "code": null, "e": 20988, "s": 20983, "text": "Java" }, { "code": null, "e": 20996, "s": 20988, "text": "Python3" }, { "code": null, "e": 20999, "s": 20996, "text": "C#" }, { "code": null, "e": 21010, "s": 20999, "text": "Javascript" }, { "code": "// C++ program to find maximum sum in Binary Tree// such that no two nodes are adjacent.#include <bits/stdc++.h>#include <iostream>using namespace std; class Node {public: int data; Node *left, *right; Node(int data) { this->data = data; left = NULL; right = NULL; }};// declare map /dp array as globalunordered_map<Node*, int> umap;int maxSum(Node* root){ // base case if (!root) return 0; // if the max sum from the node is already in // map,return the value if (umap[root]) return umap[root]; // if the current node(root) is included in result // then find maximum sum int inc = root->data; // if left of node exists, add their grandchildren if (root->left) { inc += maxSum(root->left->left) + maxSum(root->left->right); } // if right of node exist,add their grandchildren if (root->right) { inc += maxSum(root->right->left) + maxSum(root->right->right); } // if the current node(root) is excluded, find the // maximum sum int ex = maxSum(root->left) + maxSum(root->right); // store the maximum of including & excluding the node // in map umap[root] = max(inc, ex); return max(inc, ex);} // Driver codeint main(){ Node* root = new Node(10); root->left = new Node(1); root->left->left = new Node(2); root->left->left->left = new Node(1); root->left->right = new Node(3); root->left->right->left = new Node(4); root->left->right->right = new Node(5); cout << maxSum(root); return 0;}", "e": 22583, "s": 21010, "text": null }, { "code": "/*package whatever //do not write package name here */ import java.io.*;import java.util.*; // Java program for the above approachclass GFG { // Java program to find maximum sum in Binary Tree// such that no two nodes are adjacent. // declare map /dp array as globalstatic HashMap<Node,Integer> umap = new HashMap<>();static int maxSum(Node root){ // base case if (root == null) return 0; // if the max sum from the node is already in // map,return the value if (umap.containsKey(root)) return umap.get(root); // if the current node(root) is included in result // then find maximum sum int inc = root.data; // if left of node exists, add their grandchildren if (root.left != null) { inc += maxSum(root.left.left) + maxSum(root.left.right); } // if right of node exist,add their grandchildren if (root.right != null) { inc += maxSum(root.right.left) + maxSum(root.right.right); } // if the current node(root) is excluded, find the // maximum sum int ex = maxSum(root.left) + maxSum(root.right); // store the maximum of including & excluding the node // in map umap.put(root, Math.max(inc, ex)); return Math.max(inc, ex);} public static void main(String args[]){ Node root = new Node(10); root.left = new Node(1); root.left.left = new Node(2); root.left.left.left = new Node(1); root.left.right = new Node(3); root.left.right.left = new Node(4); root.left.right.right = new Node(5); System.out.println(maxSum(root));} } class Node { public int data; public Node left, right; public Node(int data) { this.data = data; left = null; right = null; }}; // This code is contributed by code_hunt.", "e": 24350, "s": 22583, "text": null }, { "code": "# Python program to find maximum sum in Binary Tree# such that no two nodes are adjacent.class Node: def __init__(self,data): self.data = data self.left = None self.right = None # declare map /dp array as globalumap = {}def maxSum(root): global umap # base case if (root == None): return 0 # if the max sum from the node is already in # map,return the value if (root in umap): return umap[root] # if the current node(root) is included in result # then find maximum sum inc = root.data # if left of node exists, add their grandchildren if (root.left): inc += maxSum(root.left.left) + maxSum(root.left.right) # if right of node exist,add their grandchildren if (root.right): inc += maxSum(root.right.left) + maxSum(root.right.right) # if the current node(root) is excluded, find the # maximum sum ex = maxSum(root.left) + maxSum(root.right) # store the maximum of including & excluding the node # in map umap[root]=max(inc, ex) return max(inc, ex) # Driver coderoot = Node(10)root.left = Node(1)root.left.left = Node(2)root.left.left.left = Node(1)root.left.right = Node(3)root.left.right.left = Node(4)root.left.right.right = Node(5)print(maxSum(root)) # This code is contributed by shinjanpatra", "e": 25670, "s": 24350, "text": null }, { "code": "// C# program to find maximum sum in Binary Tree// such that no two nodes are adjacent.using System;using System.Collections.Generic; /* A binary tree node structure */public class Node { public int data; public Node left, right; public Node(int data) { this.data = data; left = right = null; }}; class GFG { // declare map /dp array as global static Dictionary<Node, int> umap = new Dictionary<Node, int>(); static int maxSum(Node root) { // base case if (root == null) return 0; // if the max sum from the node is already in // map,return the value if (umap.ContainsKey(root)) return umap[root]; // if the current node(root) is included in result // then find maximum sum int inc = root.data; // if left of node exists, add their grandchildren if (root.left != null) { inc += maxSum(root.left.left) + maxSum(root.left.right); } // if right of node exist,add their grandchildren if (root.right != null) { inc += maxSum(root.right.left) + maxSum(root.right.right); } // if the current node(root) is excluded, find the // maximum sum int ex = maxSum(root.left) + maxSum(root.right); // store the maximum of including & excluding the // node in map umap.Add(root, Math.Max(inc, ex)); return Math.Max(inc, ex); } // Driver code public static void Main(String[] args) { Node root = new Node(10); root.left = new Node(1); root.left.left = new Node(2); root.left.left.left = new Node(1); root.left.right = new Node(3); root.left.right.left = new Node(4); root.left.right.right = new Node(5); Console.Write(maxSum(root)); }} // This code is contributed by Abhijeet Kumar(abhijeet19403)", "e": 27602, "s": 25670, "text": null }, { "code": "<script> // JavaScript program to find maximum sum in Binary Tree// such that no two nodes are adjacent.class Node { constructor(data) { this.data = data; this.left = null; this.right = null; }} // declare map /dp array as globallet umap = new Map();function maxSum(root){ // base case if (!root) return 0; // if the max sum from the node is already in // map,return the value if (umap.has(root)) return umap.get(root); // if the current node(root) is included in result // then find maximum sum let inc = root.data; // if left of node exists, add their grandchildren if (root.left) { inc += maxSum(root.left.left) + maxSum(root.left.right); } // if right of node exist,add their grandchildren if (root.right) { inc += maxSum(root.right.left) + maxSum(root.right.right); } // if the current node(root) is excluded, find the // maximum sum let ex = maxSum(root.left) + maxSum(root.right); // store the maximum of including & excluding the node // in map umap.set(root,Math.max(inc, ex)); return Math.max(inc, ex);} // Driver codelet root = new Node(10);root.left = new Node(1);root.left.left = new Node(2);root.left.left.left = new Node(1);root.left.right = new Node(3);root.left.right.left = new Node(4);root.left.right.right = new Node(5);document.write(maxSum(root)); // This code is contributed by shinjanpatra</script>", "e": 29073, "s": 27602, "text": null }, { "code": null, "e": 29076, "s": 29073, "text": "21" }, { "code": null, "e": 29119, "s": 29076, "text": "Time complexity: O(n)Auxiliary Space: O(n)" }, { "code": null, "e": 29219, "s": 29119, "text": "This article is contributed by Harsh.<https://auth.geeksforgeeks.org/user/harshchandekar10/profile>" }, { "code": null, "e": 29252, "s": 29219, "text": "Method 4 (Simple tree traversal)" }, { "code": null, "e": 29291, "s": 29252, "text": "For every node, we find the following:" }, { "code": null, "e": 29398, "s": 29291, "text": "Maximum sum of non-adjacent nodes including the node.Maximum sum of non-adjacent nodes excluding the node." }, { "code": null, "e": 29452, "s": 29398, "text": "Maximum sum of non-adjacent nodes including the node." }, { "code": null, "e": 29506, "s": 29452, "text": "Maximum sum of non-adjacent nodes excluding the node." }, { "code": null, "e": 29869, "s": 29506, "text": "Now, we return both the values in the recursive call. The parent node of the previously calculated node gets the maximum sum (including & excluding) the child node. Accordingly, the parent now calculates the maximum sum(including & excluding) and returns. This process continues till root node. Finally, we return the max(sum including root, sum excluding root)." }, { "code": null, "e": 29891, "s": 29869, "text": "Time Complexity: O(n)" }, { "code": null, "e": 29914, "s": 29891, "text": "Space Complexity: O(1)" }, { "code": null, "e": 29922, "s": 29914, "text": "Python3" }, { "code": null, "e": 29933, "s": 29922, "text": "Javascript" }, { "code": "class Node: def __init__(self, val): self.data = val self.left = None self.right = None class Solution: def max_sum(self, root): if not root: return 0, 0 no_root_l, root_l = self.max_sum(root.left) no_root_r, root_r = self.max_sum(root.right) root_sum_max = max(root.data, root.data+no_root_l, root.data+no_root_r, root.data+no_root_r+no_root_l) no_root_sum_max = max(root_l, root_r, root_l + root_r, no_root_l+no_root_r, root_l + no_root_r, root_r + no_root_l) return no_root_sum_max, root_sum_max def getMaxSum(self, root): return max(self.max_sum(root))", "e": 30641, "s": 29933, "text": null }, { "code": "<script> // JavaScript code to implement the approach class Node{ constructor(val){ this.data = val this.left = null this.right = null }} class Solution{ max_sum(root){ if(root == null) return 0, 0 let no_root_l, root_l = this.max_sum(root.left) let no_root_r, root_r = this.max_sum(root.right) let root_sum_max = Math.max(root.data, root.data+no_root_l, root.data+no_root_r, root.data+no_root_r+no_root_l) let no_root_sum_max = Math.max(root_l, root_r, root_l + root_r, no_root_l+no_root_r, root_l + no_root_r, root_r + no_root_l) return no_root_sum_max, root_sum_max } getMaxSum(root){ return Math.max(this.max_sum(root)) }} // This code is contributed by shinjanpatra </script>", "e": 31477, "s": 30641, "text": null }, { "code": null, "e": 31526, "s": 31477, "text": "This method is contributed by Thatikonda Aditya." }, { "code": null, "e": 31554, "s": 31526, "text": "Method 5(Using Memoization)" }, { "code": null, "e": 31790, "s": 31554, "text": "Approach: For every node, we can either choose it or leave it and pass on this information to children. Since we are passing on this info of the parent being selected or not, we don’t need to worry about the grandchildren of the node. " }, { "code": null, "e": 31830, "s": 31790, "text": "So for every node, we do the following:" }, { "code": null, "e": 32052, "s": 31830, "text": "If the parent is selected, we don’t select the current node and move on to the children.if the parent is not selected, then we will either select or not select this node; in either case, we pass that info to the children." }, { "code": null, "e": 32141, "s": 32052, "text": "If the parent is selected, we don’t select the current node and move on to the children." }, { "code": null, "e": 32275, "s": 32141, "text": "if the parent is not selected, then we will either select or not select this node; in either case, we pass that info to the children." }, { "code": null, "e": 32328, "s": 32275, "text": "Following is the implementation of the above method:" }, { "code": null, "e": 32332, "s": 32328, "text": "C++" }, { "code": null, "e": 32337, "s": 32332, "text": "Java" }, { "code": null, "e": 32345, "s": 32337, "text": "Python3" }, { "code": null, "e": 32348, "s": 32345, "text": "C#" }, { "code": "// C++ program to find maximum sum from a subset of// non-adjacent nodes of binary tree#include <bits/stdc++.h>using namespace std; /* A binary tree node structure */struct Node{ int data; struct Node *left, *right;}; /* Utility function to create a new Binary Tree node */struct Node *newNode(int data){ struct Node *temp = new struct Node; temp->data = data; temp->left = temp->right = NULL; return temp;} // Delaration of the vector to store the answervector<vector<int>> dp; // Variables and function to index the given Binary tree// This indexing will be used in dpint cnt = 0;Node *temp;Node *giveIndex(Node *root){ if (root == NULL) return NULL; // give the index to the current node and increment the index for next nodes. Node *newNode1 = newNode(cnt++); // Recursively calling right and left subtree newNode1->left = giveIndex(root->left); newNode1->right = giveIndex(root->right); return newNode1;} // Memoization function to store the answerint solve(Node *root, int b, Node *temp){ if (root == NULL) return 0; // If the answer is already calculated return that answer if (dp[temp->data][b] != -1) return dp[temp->data][b]; // Variable to store the answer for the current node. int res; // if the parent is not selected then we can either select ot not select this node. if (b == 0) res = max(root->data + solve(root->right, 1, temp->right) + solve(root->left, 1, temp->left), solve(root->right, 0, temp->right) + solve(root->left, 0, temp->left)); // If parent is selected then we can't select this node. else res = solve(root->right, 0, temp->right) + solve(root->left, 0, temp->left); // return the annswer return dp[temp->data][b] = res;}int getMaxSum(Node *root){ // Initialization of the dp dp = vector<vector<int>>(100, vector<int>(2, -1)); // Calling the indexing function temp = giveIndex(root); // calling the solve function for root with parent not selected int res = solve(root, 0, temp); return res;} // Driver code to test above methodsint main(){ // TEST 1 Node *root = newNode(1); root->left = newNode(2); root->right = newNode(3); root->right->left = newNode(4); root->right->right = newNode(5); root->left->left = newNode(1); cout << getMaxSum(root) << endl; // TEST 2 Node *root2 = newNode(10); root2->left = newNode(1); root2->left->left = newNode(2); root2->left->left->left = newNode(1); root2->left->right = newNode(3); root2->left->right->left = newNode(4); root2->left->right->right = newNode(5); cout << getMaxSum(root2); return 0;}//Code contributed by Anirudh Singh.", "e": 35046, "s": 32348, "text": null }, { "code": "// Java program to find maximum sum from a subset of// non-adjacent nodes of binary tree import java.util.HashMap; /* A binary tree node structure */class Node { int data; Node left, right; Node(int data) { this.data = data; left = right = null; }}; class gfg { // Delaration of the vector to store the answer static int[][] dp; // Variables and function to index the given Binary tree // This indexing will be used in dp static int cnt = 0; static Node temp; static Node giveIndex(Node root) { if (root == null) return null; // give the index to the current node and increment // the index for next nodes. Node newNode1 = new Node(cnt++); // Recursively calling right and left subtree newNode1.left = giveIndex(root.left); newNode1.right = giveIndex(root.right); return newNode1; } // Memoization function to store the answer static int solve(Node root, int b, Node temp) { if (root == null) return 0; // If the answer is already calculated return that // answer if (dp[temp.data][b] != -1) return dp[temp.data][b]; // Variable to store the answer for the current // node. int res; // if the parent is not selected then we can either // select ot not select this node. if (b == 0) res = Math.max(root.data + solve(root.right, 1, temp.right) + solve(root.left, 1, temp.left), solve(root.right, 0, temp.right) + solve(root.left, 0, temp.left)); // If parent is selected then we can't select this // node. else res = solve(root.right, 0, temp.right) + solve(root.left, 0, temp.left); // return the annswer return dp[temp.data][b] = res; } static int getMaxSum(Node root) { // Initialization of the dp dp = new int[100][2]; for(int i=0;i<100;i++) { dp[i][0] = -1; dp[i][1] = -1; } // Calling the indexing function temp = giveIndex(root); // calling the solve function for root with parent // not selected int res = solve(root, 0, temp); return res; } public static void main(String args[]) { // TEST 1 Node root = new Node(1); root.left = new Node(2); root.right = new Node(3); root.right.left = new Node(4); root.right.right = new Node(5); root.left.left = new Node(1); System.out.println(getMaxSum(root)); // TEST 2 Node root2 = new Node(10); root2.left = new Node(1); root2.left.left = new Node(2); root2.left.left.left = new Node(1); root2.left.right = new Node(3); root2.left.right.left = new Node(4); root2.left.right.right = new Node(5); System.out.print(getMaxSum(root2)); }} // This code is contributed by Abhijeet Kumar(abhijeet19403)", "e": 38091, "s": 35046, "text": null }, { "code": "# Python3 program to find maximum sum from a subset of# non-adjacent nodes of binary tree # A binary tree node structureclass newNode: def __init__(self, data): self.data = data self.left = None self.right = None dp = [[]] # Variables and function to index the given Binary tree# This indexing will be used in dpcnt = 0temp = newNode(0)def giveIndex(root): if (root == None): return None # give the index to the current node and increment the index for next nodes. global cnt cnt += 1 newNode1 = newNode(cnt) # Recursively calling right and left subtree newNode1.left = giveIndex(root.left) newNode1.right = giveIndex(root.right) return newNode1 # Memoization function to store the answerdef solve(root, b, temp): if (root == None): return 0 # If the answer is already calculated return that answer if (dp[temp.data][b] != -1): return dp[temp.data][b] # Variable to store the answer for the current node. res = 0 # if the parent is not selected then we can either select ot not select this node. if (b == 0): res = max(root.data + solve(root.right, 1, temp.right) + solve(root.left, 1, temp.left), solve(root.right, 0, temp.right) + solve(root.left, 0, temp.left)) # If parent is selected then we can't select this node. else: res = solve(root.right, 0, temp.right) + solve(root.left, 0, temp.left) # return the annswer dp[temp.data][b] = res return res def getMaxSum(root): # Initialization of the dp global dp dp = [[-1 for x in range(2)] for x in range(100)] # Calling the indexing function temp = giveIndex(root) # calling the solve function for root with parent not selected res = solve(root, 0, temp) return res # Driver codeif __name__==\"__main__\": # TEST 1 root = newNode(1) root.left = newNode(2) root.right = newNode(3) root.right.left = newNode(4) root.right.right = newNode(5) root.left.left = newNode(1) print(getMaxSum(root)) # TEST 2 root2 = newNode(10) root2.left = newNode(1) root2.left.left = newNode(2) root2.left.left.left = newNode(1) root2.left.right = newNode(3) root2.left.right.left = newNode(4) root2.left.right.right = newNode(5) print(getMaxSum(root2)) # This code is contributed by Abhijeet Kumar(abhijeet19403)", "e": 40460, "s": 38091, "text": null }, { "code": "// C# program to find maximum sum from a subset of// non-adjacent nodes of binary tree using System;using System.Collections.Generic; /* A binary tree node structure */public class Node{ public int data; public Node left, right; public Node(int data) { this.data=data; left=right=null; }}; class gfg{ // Delaration of the vector to store the answer static int[,] dp; // Variables and function to index the given Binary tree // This indexing will be used in dp static int cnt = 0; static Node temp; static Node giveIndex(Node root) { if (root == null) return null; // give the index to the current node and increment // the index for next nodes. Node newNode1 = new Node(cnt++); // Recursively calling right and left subtree newNode1.left = giveIndex(root.left); newNode1.right = giveIndex(root.right); return newNode1; } // Memoization function to store the answer static int solve(Node root, int b, Node temp) { if (root == null) return 0; // If the answer is already calculated return that // answer if (dp[temp.data,b] != -1) return dp[temp.data,b]; // Variable to store the answer for the current // node. int res; // if the parent is not selected then we can either // select ot not select this node. if (b == 0) res = Math.Max(root.data + solve(root.right, 1, temp.right) + solve(root.left, 1, temp.left), solve(root.right, 0, temp.right) + solve(root.left, 0, temp.left)); // If parent is selected then we can't select this // node. else res = solve(root.right, 0, temp.right) + solve(root.left, 0, temp.left); // return the annswer return dp[temp.data,b] = res; } static int getMaxSum(Node root) { // Initialization of the dp dp = new int[100,2]; for(int i=0;i<100;i++) { dp[i,0] = -1; dp[i,1] = -1; } // Calling the indexing function temp = giveIndex(root); // calling the solve function for root with parent // not selected int res = solve(root, 0, temp); return res; } // Driver code public static void Main(String []args) { // TEST 1 Node root = new Node(1); root.left = new Node(2); root.right = new Node(3); root.right.left = new Node(4); root.right.right = new Node(5); root.left.left = new Node(1); Console.WriteLine(getMaxSum(root)); // TEST 2 Node root2 = new Node(10); root2.left = new Node(1); root2.left.left = new Node(2); root2.left.left.left = new Node(1); root2.left.right = new Node(3); root2.left.right.left = new Node(4); root2.left.right.right = new Node(5); Console.Write(getMaxSum(root2)); }} // This code has been contributed by Abhijeet Kumar(abhijeet19403)", "e": 43559, "s": 40460, "text": null }, { "code": null, "e": 43565, "s": 43559, "text": "11\n21" }, { "code": null, "e": 43587, "s": 43565, "text": "Time Complexity: O(N)" }, { "code": null, "e": 43610, "s": 43587, "text": "Space Complexity: O(N)" }, { "code": null, "e": 43674, "s": 43610, "text": "This method and implementation is contributed by Anirudh Singh." }, { "code": null, "e": 43925, "s": 43674, "text": "If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to review-team@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks." }, { "code": null, "e": 44050, "s": 43925, "text": "Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above." }, { "code": null, "e": 44075, "s": 44052, "text": "Sai Krishna Chowrigari" }, { "code": null, "e": 44090, "s": 44075, "text": "_Gaurav_Tiwari" }, { "code": null, "e": 44105, "s": 44090, "text": "SHUBHAMSINGH10" }, { "code": null, "e": 44119, "s": 44105, "text": "princiraj1992" }, { "code": null, "e": 44131, "s": 44119, "text": "29AjayKumar" }, { "code": null, "e": 44141, "s": 44131, "text": "rutvik_56" }, { "code": null, "e": 44155, "s": 44141, "text": "reapedjuggler" }, { "code": null, "e": 44161, "s": 44155, "text": "itsok" }, { "code": null, "e": 44179, "s": 44161, "text": "divyeshrabadiya07" }, { "code": null, "e": 44189, "s": 44179, "text": "ganesh227" }, { "code": null, "e": 44206, "s": 44189, "text": "harshchandekar10" }, { "code": null, "e": 44218, "s": 44206, "text": "taditya3007" }, { "code": null, "e": 44229, "s": 44218, "text": "anand00525" }, { "code": null, "e": 44247, "s": 44229, "text": "germanshephered48" }, { "code": null, "e": 44263, "s": 44247, "text": "saurabh1990aror" }, { "code": null, "e": 44271, "s": 44263, "text": "clintra" }, { "code": null, "e": 44284, "s": 44271, "text": "shinjanpatra" }, { "code": null, "e": 44299, "s": 44284, "text": "anirudhsingh11" }, { "code": null, "e": 44313, "s": 44299, "text": "abhijeet19403" }, { "code": null, "e": 44318, "s": 44313, "text": "Tree" }, { "code": null, "e": 44323, "s": 44318, "text": "Tree" } ]