- Data Structure
- Networking
- RDBMS
- Operating System
- Java
- MS Excel
- iOS
- HTML
- CSS
- Android
- Python
- C Programming
- C++
- C#
- MongoDB
- MySQL
- Javascript
- PHP
- Physics
- Chemistry
- Biology
- Mathematics
- English
- Economics
- Psychology
- Social Studies
- Fashion Studies
- Legal Studies
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Find original array from encrypted array (An array of sums of other elements) using C++.
Let us consider we have an array of integers, that array is encrypted array, Suppose the array is A = [10, 14, 12, 13, 11], the original array is B = [5, 1, 3, 2, 4], we can see that each element at index I of A follows this rule: A[i] = sum of all elements at position j in B[j], where I ≠ j. Our task is to find an original array from the encrypted one.
The task is based on arithmetic observation. Suppose the array is of size 4, original array B has four elements B = [a, b, c, d], so A will be like A[b+c+d, a+c+d, a+b+d, a+b+c], if we add all of the elements of B, we will get sum = b+c+d+a+c+d+a+b+d+a+b+c = 3*(a+b+c+d). So the sum of elements of B will be sum/3, now if we see the elements of B will be [sum – A[0], sum – A[1], sum – A[2], sum – A[3]]
Example
#include<iostream> using namespace std; void showOrigianlArray(int arr[], int n) { int sum = 0; for (int i=0; i<n; i++) sum += arr[i]; sum = sum/(n-1); for (int i=0; i<n; i++) cout << (sum - arr[i]) << " "; } int main() { int arr[] = {10, 14, 12, 13, 11}; int n = sizeof(arr) / sizeof(arr[0]); showOrigianlArray(arr, n); }
Output
5 1 3 2 4
To Continue Learning Please Login
Login with Google