Number of groups of magnets formed from N magnets in C++

C++Server Side ProgrammingProgramming

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
raja
Published on 03-Jul-2021 05:17:30

Advertisements