- Trending Categories
Data Structure
Networking
RDBMS
Operating System
Java
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
- Related Articles
- Find k maximum elements of array in original order in C++
- Equalize an array using array elements only in C++
- Find all distinct subset (or subsequence) sums of an array in C++
- Construct an array from GCDs of consecutive elements in given array in C++
- Find elements of array using XOR of consecutive elements in C++
- Rank of All Elements in an Array using C++
- Divide every element of one array by other array elements in C++ Program
- Find pairs in array whose sums already exist in array in C++
- Return the sum of two consecutive elements from the original array in JavaScript
- How to filter an array from all elements of another array – JavaScript?
- How to find the sum of elements of an Array using STL in C++?
- C++ Program to Access Elements of an Array Using Pointer
- Construct an array from XOR of all elements of array except element at same index in C++
- Find Duplicates of array using bit array in C++
- Print n smallest elements from given array in their original order
