# [R] combinatorial programming problem

From: Kjetil Brinchmann Halvorsen <kjetilbrinchmannhalvorsen_at_gmail.com>
Date: Sat 27 May 2006 - 02:58:48 EST

Hola!

There is one programming problem I haven't solved, making an inverse of the index function indx() --- se code below. It could for instance return the original k indexes in strictly increasing order, to make indx() formally invertible.

Any ideas?

Kjetil

Code:

# Implementing an S3 class for symarrays with array rank r for dimension
# [k, k, ..., k] with k>=r repeated r times. We do not store the diagonal.

# Storage requirement is given by {r, k}= choose(k, r)
# where r=array rank, k=maximum index

symarray <- function(data=NA, dims=c(1,1)){

```      r <- dims
k <- dims
if(r > k) stop("symarray needs dimension larger than array rank")
len <- choose(k, r)
out <- data[1:len]
attr(out, "dims") <- dims
class(out) <- "symarray"
out
```

}

# Index calculation:

indx <- function(inds, k){

r <- length(inds)
if(r==1) return(inds) else {

```       if(inds==1) {
return( indx(inds[-1]-1, k-1 ) ) } else {
return( indx(c(inds-1, seq(from=k-r+2, by=1, to=k)), k) +
indx( inds[-1]-inds, k-inds ))
}
```

}
} # end indx

# Methods for assignment and indexing:

"[.symarray" <- function(x, inds, drop=FALSE){

```         dims <- attr(x, "dims")
k <- dims
inds <- indx(inds, k)
res <- NextMethod("[", x)
res
```

}

"[<-.symarray" <- function(x, inds, value){

```     dims <- attr(x, "dims")
k <- dims
inds <- indx(inds, k)
res <- NextMethod("[<-", x)
res
```

}

R-help@stat.math.ethz.ch mailing list