[R] All nonnegative integer solution

Peter Dalgaard P.Dalgaard at biostat.ku.dk
Mon Nov 19 16:02:51 CET 2007


Robin Hankin wrote:
> Hello Amin
>
> The partitions library does this.
>
> If N=4 and k=3:
>
>  > library(partitions)
>  > blockparts(rep(4,3),4)
>
> [1,] 4 3 2 1 0 3 2 1 0 2 1 0 1 0 0
> [2,] 0 1 2 3 4 0 1 2 3 0 1 2 0 1 0
> [3,] 0 0 0 0 0 1 1 1 1 2 2 2 3 3 4
>  >
>
> The solutions are enumerated in the columns.
>
> HTH
>
>
> rksh
>
>   
Nice. You can also do it with a straightforward piece of recursive
programming:

splitsum <- function(N,k)
   if (k==1) N else
      do.call(rbind, lapply(0:N, function(i) cbind(i,splitsum(N-i, k-1))))

> splitsum(4,3)
      i i
 [1,] 0 0 4
 [2,] 0 1 3
 [3,] 0 2 2
 [4,] 0 3 1
 [5,] 0 4 0
 [6,] 1 0 3
 [7,] 1 1 2
 [8,] 1 2 1
 [9,] 1 3 0
[10,] 2 0 2
[11,] 2 1 1
[12,] 2 2 0
[13,] 3 0 1
[14,] 3 1 0
[15,] 4 0 0

Or (I think there was an old Stats 1 combinatorics exercise to a similar
effect)

> splitsum2 <- function(N,k)
t(apply(rbind(0,combn(N+k-1,k-1),N+k),2,diff)-1)
> splitsum2(4,3)
      [,1] [,2] [,3]
 [1,]    0    0    4
 [2,]    0    1    3
 [3,]    0    2    2
 [4,]    0    3    1
 [5,]    0    4    0
 [6,]    1    0    3
 [7,]    1    1    2
 [8,]    1    2    1
 [9,]    1    3    0
[10,]    2    0    2
[11,]    2    1    1
[12,]    2    2    0
[13,]    3    0    1
[14,]    3    1    0
[15,]    4    0    0

Exercise for the reader: Explain!
>
>
>
> On 19 Nov 2007, at 09:57, aminzoll at ece.tamu.edu wrote:
>
>   
>> Dear all,
>> Is there any method in R to find all possible nonnegative integer
>> solutions to the linear equation with unit coefficients as follow:
>> X1+X2+...+Xk=N
>> Thank you,
>> Amin Zollanvari
>>
>>     


-- 
   O__  ---- Peter Dalgaard             Øster Farimagsgade 5, Entr.B
  c/ /'_ --- Dept. of Biostatistics     PO Box 2099, 1014 Cph. K
 (*) \(*) -- University of Copenhagen   Denmark          Ph:  (+45) 35327918
~~~~~~~~~~ - (p.dalgaard at biostat.ku.dk)                  FAX: (+45) 35327907



More information about the R-help mailing list