- Trending Categories
Data Structure
Networking
RDBMS
Operating System
Java
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
Physics
Chemistry
Biology
Mathematics
English
Economics
Psychology
Social Studies
Fashion Studies
Legal Studies
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Number of groups of magnets formed from N magnets in C++
The digit 1 represent positive pole whereas 0 represents negative pole.
The magnet will have both poles as 10 or 01. A group can be formed with the magnets that attracts each other. The magnets with different pole facing each other will be in the same group.
Here, you are given N number of magnets. You need to find out number of groups can be formed with them.
Whenever there are two different magnets side by side, there forms a new group. In that case increment the count of the groups.
Let's see an example.
Input
magnets = ["10", "01", "01", "01", "10", "01"]
Output
4
There are 4 magnets that attract each other side by side in the given array. They are "10", "01", "10", "01".
Algorithm
- Initialise the array with magnets.
- Initialise the count to 1 as we are taking pairs.
- Write a loop that iterates from 1 index to the end of the array.
- If the current magnet is not equal to the previous one, then increment the count.
- Return the count.
Implementation
Following is the implementation of the above algorithm in C++
#include <bits/stdc++.h> using namespace std; int getMangetGroupsCount(string magnets[], int n) { int count = 1; for (int i = 1; i < n; i++) { if (magnets[i] != magnets[i - 1]) { count++; } } return count; } int main() { string magnets[] = { "10", "01", "01", "01", "10", "01" }; int n = 6; cout << getMangetGroupsCount(magnets, n) << endl; return 0; }
Output
If you run the above code, then you will get the following result.
4
- Related Articles
- Discovery of Magnets
- What are magnets?
- Rare Earth Magnets
- Studying the Behaviour of Permanent Magnets
- Where can we find magnets and how can we know what is rock and magnets because some magnets are like rocks?
- Maximum number of 3-person teams formed from two groups in C++
- How does the magnets work?
- C++ program to find number of groups can be formed from set of programmers
- Write 10 objects from your surrounding in which magnets are used.
- Why magnets attract or repel each other?
- The figure given below shows the magnetic field between two magnets:(i) Copy the diagram and label the other poles of the magnets.(ii) Which is the weaker magnet?"\n
- Do magnets get attracted to nonmetals or only metals?
- Program to find minimum number of groups in communication towers in C++?\n
- How many types of artificial magnets are there (on the basis of shapes)? Name any two.
- Find the Number of Triangles Formed from a Set of Points on Three Lines using C++\n
