How to add each element of an array with other elements of the same array?

Suppose I have an array

a[3]={1,3,8} 

I want the output to have an array containing the numbers obtained by adding numbers from array a, as well as elements of array a. those.

 b[0]=1 b[1]=3 b[2]=8 b[3]=4 //(1+3) b[4]=9 //(1+8) b[5]=11 //(3+8) b[6]=12 //(1+3+8) 

How to do it?

+4
source share
2 answers

So, you want to generate all possible subsets of a set of numbers and list their sum.

First you want to list all the subsets. Since the set containing the elements of N contains 2 ^ N subsets, you can simply do this by iterating through natural numbers from 0 to 1 << (sizeof(arr) / sizeof(arr[0])) and processing the binary representation of the number as follows way: if a specific bit is set at position k , then the element k th is in the currently created subset, otherwise it is not.

Then you must add all the selected elements together and save the result in the next slot of another array (size 2 ^ N , obviously).

 #define COUNT(a) (sizeof(a) / sizeof(a[0])) #include <limits.h> // for CHAR_BIT unsigned a[3] = { 1, 3, 8 }; unsigned sums[1 << COUNT(a)] = { 0 }; for (unsigned i = 0; i < COUNT(sums); i++) { for (unsigned j = 0; j < sizeof(i) * CHAR_BIT; j++) { if ((i >> j) & 1) { sums[i] += a[j]; } } } for (unsigned i = 0; i < COUNT(sums); i++) { printf("%d\n", sums[i]); } 
+3
source

I would do it like this:

 b[0] = 0; //This is not listed in the question, but should be included in the result IMHO. for(long i = 0; i < elementsA; i++) { long preexistingElements = 1 << i; long curElement = a[i]; for(long j = 0; j < preexistingElements; j++) { b[j + preexistingElements] = b[j] + curElement; } } 

This algorithm is linear in size of the array of results, since each element is calculated at a constant cost.

If you really have to exclude zero and want to compile an array of results, expand the algorithm around so that b is filled on the back with a zero element as the last element.

0
source

Source: https://habr.com/ru/post/1484071/


All Articles