📜  计算相同元素的连续对

📅  最后修改于: 2021-04-29 12:13:24             🧑  作者: Mango

给定数组arr [] ,任务是计算由连续元素形成的对的数量,其中一对中的两个元素都相同。

例子:

方法:初始化count = 0并将数组从arr [0]遍历到arr [n – 2] 。如果当前元素等于数组中的下一个元素,则增加计数。最后打印计数

下面是上述方法的实现:

C++
// C++ implementation of the approach
#include 
using namespace std;
  
// Function to return the count of consecutive
// elements in the array which are equal
int countCon(int ar[], int n)
{
    int cnt = 0;
  
    for (int i = 0; i < n - 1; i++) {
  
        // If consecutive elements are same
        if (ar[i] == ar[i + 1])
            cnt++;
    }
    return cnt;
}
  
// Driver code
int main()
{
    int ar[] = { 1, 2, 2, 3, 4, 4, 5, 5, 5, 5 };
    int n = sizeof(ar) / sizeof(ar[0]);
    cout << countCon(ar, n);
  
    return 0;
}


Java
// Java implementation of the approach 
public class GfG
{
  
    // Function to return the count of consecutive 
    // elements in the array which are equal 
    static int countCon(int ar[], int n) 
    { 
        int cnt = 0; 
      
        for (int i = 0; i < n - 1; i++) 
        { 
      
            // If consecutive elements are same 
            if (ar[i] == ar[i + 1]) 
                cnt++; 
        } 
        return cnt; 
    } 
      
    // Driver Code
    public static void main(String []args){
          
        int ar[] = { 1, 2, 2, 3, 4, 4, 5, 5, 5, 5 }; 
        int n = ar.length; 
        System.out.println(countCon(ar, n));
    }
}
  
// This code is contributed by Rituraj Jain


Python3
# Python3 implementation of the approach
  
# Function to return the count of consecutive
# elements in the array which are equal
def countCon(ar, n):
    cnt = 0
  
    for i in range(n - 1):
  
        # If consecutive elements are same
        if (ar[i] == ar[i + 1]):
            cnt += 1
      
    return cnt
  
# Driver code
ar = [1, 2, 2, 3, 4,
      4, 5, 5, 5, 5]
n = len(ar)
print(countCon(ar, n))
  
# This code is contributed by mohit kumar


C#
// C# implementation of the approach 
using System;
  
class GfG
{
  
    // Function to return the count of consecutive 
    // elements in the array which are equal 
    static int countCon(int[] ar, int n) 
    { 
        int cnt = 0; 
      
        for (int i = 0; i < n - 1; i++) 
        { 
      
            // If consecutive elements are same 
            if (ar[i] == ar[i + 1]) 
                cnt++; 
        } 
        return cnt; 
    } 
      
    // Driver Code
    public static void Main()
    {
          
        int[] ar = { 1, 2, 2, 3, 4, 4, 5, 5, 5, 5 }; 
        int n = ar.Length; 
        Console.WriteLine(countCon(ar, n));
    }
}
  
// This code is contributed by Code_Mech.


PHP


输出:
5