
- C++ Basics
- C++ Home
- C++ Overview
- C++ Environment Setup
- C++ Basic Syntax
- C++ Comments
- C++ Data Types
- C++ Variable Types
- C++ Variable Scope
- C++ Constants/Literals
- C++ Modifier Types
- C++ Storage Classes
- C++ Operators
- C++ Loop Types
- C++ Decision Making
- C++ Functions
- C++ Numbers
- C++ Arrays
- C++ Strings
- C++ Pointers
- C++ References
- C++ Date & Time
- C++ Basic Input/Output
- C++ Data Structures
- C++ Object Oriented
- C++ Classes & Objects
- C++ Inheritance
- C++ Overloading
- C++ Polymorphism
- C++ Abstraction
- C++ Encapsulation
- C++ Interfaces
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 < size of A, update (increase i by 1), do: for initialize j := 0, when j < i, update (increase j by 1), do: if |A[i] - A[j]| <= d, then: (increase ans by 1) return ans * 2
Example
Let us see the following implementation to get better understanding −
#include <bits/stdc++.h> using namespace std; int solve(vector<int> A, int d){ int ans = 0; for (int i = 1; i < A.size(); i++) for (int j = 0; j < i; j++) if (abs(A[i] - A[j]) <= d) ans++; return ans * 2; } int main(){ vector<int> A = { 10, 20, 50, 60, 65 }; int d = 10; cout << solve(A, d) << endl; }
Input
{ 10, 20, 50, 60, 65 }, 10
Output
6
- Related Articles
- Count ways to form minimum product triplets in C++
- C++ program to find indices of soldiers who can form reconnaissance unit
- Count possible ways to construct buildings
- Count ways to reach the n’th stair
- C++ code to count operations to make array sorted
- C++ code to count days to complete reading book
- C++ code to count volume of given text
- C++ code to count who have declined invitation
- C++ code to count number of unread chapters
- C++ code to find maximum fruit count to make compote
- Count number of ways to jump to reach end in C++
- C++ code to count maximum groups can be made
- C++ code to count maximum banknotes bank can gather
- C++ code to count order collected when client calls
- C++ code to count local extrema of given array

Advertisements