This function returns the next permuation of the multiset if there is one. initMC called before nextPerm can be called.

nextPerm(mcObj, n = 1)

Arguments

mcObj

an S3 object of class mc which must be created with initMC

n

the number of permutations to return. Asking for several at a time is much faster than calling nextPerm repeatedly, while still only holding n permutations in memory.

Value

If n is 1, either a vector with the next permutation of the multiset or FALSE when all permutations have been returned. Because a permutation always has at least two elements, isFALSE(nextPerm(m)) detects the end even when the multiset is logical.

If n is greater than 1, a matrix whose rows are the next n permutations, with fewer rows when fewer than n are left, or FALSE when all permutations have been returned.

Calling allPerm does not change the position of nextPerm.

See also

Author

James M. Curran

Examples


x = c(1,1,2,2)
m1 = initMC(x)

for(i in 1:6){
  cat(paste(paste(nextPerm(m1),collapse=","),"\n"))
}
#> 2,2,1,1 
#> 1,2,2,1 
#> 2,1,2,1 
#> 1,2,1,2 
#> 1,1,2,2 
#> 2,1,1,2 

## an example with letters
x = letters[1:4]
m2 = initMC(x)
nextPerm(m2)
#> [1] "d" "c" "b" "a"
nextPerm(m2)
#> [1] "a" "d" "c" "b"
## and so on

## process all 3,628,800 permutations of 1:10 in batches of 100,000,
## without ever holding them all in memory
m3 = initMC(1:10)
nFixed = 0
while(!isFALSE(p <- nextPerm(m3, 100000))){
  nFixed = nFixed + sum(p[, 1] == 1)
}
nFixed ## the permutations that start with 1, i.e. 9!
#> [1] 362880