
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Number of Anomalies in an Array in C++
In this tutorial, we are going to write a program that finds the number of anomalies in the given array.
A number is an anomaly in the given array if the absolute difference between the number and all other numbers is greater than the given number k. Let's see an example.
Input
arr = [3, 1, 5, 7] k = 1
Output
4
The absolute difference between all numbers with others is greater than k.
Algorithm
Initialise the array.
-
Iterate over the array.
-
Take the element and iterate over the array.
Find the absolute difference between the two numbers.
If no absolute difference is less than or equal to k than increment the count of anomalies.
-
Implementation
Following is the implementation of the above algorithm in C++
#include <bits/stdc++.h> using namespace std; int getAnomaliesCount(int arr[], int n, int k) { int count = 0; for (int i = 0; i < n; i++) { int j; for (j = 0; j < n; j++) { if (i != j && abs(arr[i] - arr[j]) <= k) { break; } } if (j == n) { count++; } } return count; } int main() { int arr[] = {3, 1, 5, 7}, k = 1; int n = 4; cout << getAnomaliesCount(arr, n, k) << endl; return 0; }
Output
If you run the above code, then you will get the following result.
4
Advertisements