C++ code to count ways to form reconnaissance units

Suppose we have an array A with n elements, and another number d. According to the regulations of Dreamland's army, a reconnaissance unit should have exactly two soldiers. Since these two soldiers shouldn't differ much, their heights can differ by at most d centimeters. There are n soldiers whose heights are stored in the array A. Some soldiers are of the same height. We have to find how many ways exist to form a reconnaissance unit from these n soldiers.

So, if the input is like A = [10, 20, 50, 60, 65]; d = 10, then the output will be 6, because (10, 20), (20, 10), (50, 60), (60, 50), (60, 65), (65, 60) are the possible units.

Steps

To solve this, we will follow these steps −

ans := 0
for initialize i := 1, when i 

Example

Let us see the following implementation to get better understanding −

#include 
using namespace std;
int solve(vector A, int d){
   int ans = 0;
   for (int i = 1; i  A = { 10, 20, 50, 60, 65 };
   int d = 10;
   cout 

Input

{ 10, 20, 50, 60, 65 }, 10

Output

6
Updated on: 2022-03-30T13:02:19+05:30

265 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements