Skip to contents

Constructs an iterator generates all permutations of an iterable object. By default, full-length permutations are generated. If m is specified, successive m length permutations are instead generated.

Usage

ipermutations(object, m = NULL)

Arguments

object

vector

m

length of permutations. By default, full-length permutations are generated.

Value

iterator that generates all permutations of object

Details

The implementation is loosely based on that of Python's itertools.

Examples

it <- ipermutations(1:3)

nextOr(it, NA) # c(1, 2, 3)
#> [1] 1 2 3
nextOr(it, NA) # c(1, 3, 2)
#> [1] 1 3 2
nextOr(it, NA) # c(3, 1, 2)
#> [1] 2 1 3
nextOr(it, NA) # c(3, 2, 1)
#> [1] 2 3 1
nextOr(it, NA) # c(2, 3, 1)
#> [1] 3 1 2
nextOr(it, NA) # c(2, 1, 3)
#> [1] 3 2 1

it2 <- ipermutations(letters[1:4])
# 24 = 4! permutations of the letters a, b, c, and d
as.list(it2)
#> [[1]]
#> [1] "a" "b" "c" "d"
#> 
#> [[2]]
#> [1] "a" "b" "d" "c"
#> 
#> [[3]]
#> [1] "a" "c" "b" "d"
#> 
#> [[4]]
#> [1] "a" "c" "d" "b"
#> 
#> [[5]]
#> [1] "a" "d" "b" "c"
#> 
#> [[6]]
#> [1] "a" "d" "c" "b"
#> 
#> [[7]]
#> [1] "b" "a" "c" "d"
#> 
#> [[8]]
#> [1] "b" "a" "d" "c"
#> 
#> [[9]]
#> [1] "b" "c" "a" "d"
#> 
#> [[10]]
#> [1] "b" "c" "d" "a"
#> 
#> [[11]]
#> [1] "b" "d" "a" "c"
#> 
#> [[12]]
#> [1] "b" "d" "c" "a"
#> 
#> [[13]]
#> [1] "c" "a" "b" "d"
#> 
#> [[14]]
#> [1] "c" "a" "d" "b"
#> 
#> [[15]]
#> [1] "c" "b" "a" "d"
#> 
#> [[16]]
#> [1] "c" "b" "d" "a"
#> 
#> [[17]]
#> [1] "c" "d" "a" "b"
#> 
#> [[18]]
#> [1] "c" "d" "b" "a"
#> 
#> [[19]]
#> [1] "d" "a" "b" "c"
#> 
#> [[20]]
#> [1] "d" "a" "c" "b"
#> 
#> [[21]]
#> [1] "d" "b" "a" "c"
#> 
#> [[22]]
#> [1] "d" "b" "c" "a"
#> 
#> [[23]]
#> [1] "d" "c" "a" "b"
#> 
#> [[24]]
#> [1] "d" "c" "b" "a"
#>