How to count all distinct pairs from array with specific difference between them in C#

1 Answer

0 votes
using System;

class Program
{
     static int countPairsWithSpecificDifference(int []arr, int difference) { 
        int count = 0; 
        int size = arr.Length; 
        
        for (int i = 0; i < size; i++) {  
            for (int j = i + 1; j < size; j++) {
                if (arr[i] - arr[j] == difference || arr[j] - arr[i] == difference) {
                    count++; 
                }
            }
        } 
          
        return count; 
    } 
    static void Main() {
        int []arr = {25, 16, 8, 12, 20, 17, 0, 4, 21, 26}; 
        int difference = 4; 
        
        // 7 pairs with difference 4: {25, 21}, {16, 12}, {16, 20}, {8, 12}, {8, 4}, {17, 21} {0, 4} 

        Console.WriteLine(countPairsWithSpecificDifference(arr, difference)); 
    }
}



/*
run:
   
7
   
*/

 



answered Dec 1, 2021 by avibootz
...