/***************************************************************************************************************** SAS file name: all_sums.sas File location: __________________________________________________________________________________________________________________ Purpose: To demonstrate how to generate all possible sums of N numbers in SAS. Author: Peter Clemmensen Creation Date: 29/12/2020 This program supports the blog post "Generate All Possible Sums in SAS" on SASnrd.com *****************************************************************************************************************/ /* Example data */ data have; input x @@; datalines; 1 2 3 4 5 ; /* Proc Summary */ data _null_; if 0 then set have nobs=n; call symputx('nobs',n); stop; run; %put nobs = &nobs.; data temp; array a {&nobs.}; do i = 1 to &nobs.; set have; a[i] = x; end; run; proc summary data = temp chartype descendtypes completetypes; class a:; var a:; output out = temp2 sum = / ways; run; data want; set temp2(drop = _TYPE_ _FREQ_ where = (_WAY_)); s = sum(of a:); run; /* Data Step */ data _null_; if 0 then set have nobs=n; call symputx('nobs',n); stop; run; %put nobs = &nobs.; data want; array aa {&nobs.}; do i = 1 to &nobs.; set have; aa[i] = x; end; do i = 2 ** &nobs. - 1 to 1 by -1; s = put(i, binary&nobs..); sum = 0; do k = 1 to &nobs.; coef = char(s, k); sum + coef * aa[k]; end; output; end; format i binary5.; keep aa: i sum; run; /* Data Step - Binary Logic */ data _null_; if 0 then set have nobs=n; call symputx('nobs', n - 1); stop; run; %put nobs=&nobs; data want; array bi {0 : &nobs.} _temporary_; array aa {0 : &nobs.}; do i = 0 to &nobs.; set have; aa[i] = x; bi[i] = 2 ** i; end; do i = 2 ** (&nobs. + 1) - 1 to 1 by -1; sum = 0; do j = 0 to &nobs.; coef = (band(i, bi[j]) > 0); sum + coef * aa[&nobs. - j]; end; output; end; format i binary5.; keep aa: i sum; run;