permutations

permutations(array)

Generate all permutations of an indexable object. Because the number of permutations can be very large, this function returns an iterator object. Use collect(permutations(array)) to get an array of all permutations.

Examples

  1. Generate permutations of an array:

    julia> collect(permutations([1, 2, 3]))
    6-element Array{Tuple{Int64,Int64,Int64},1}:
    (1, 2, 3)
    (1, 3, 2)
    (2, 1, 3)
    (2, 3, 1)
    (3, 1, 2)
    (3, 2, 1)

    This example generates all permutations of the array [1, 2, 3] and collects them into an array.

  2. Generate permutations of a string:

    julia> collect(permutations("abc"))
    6-element Array{Tuple{Char,Char,Char},1}:
    ('a', 'b', 'c')
    ('a', 'c', 'b')
    ('b', 'a', 'c')
    ('b', 'c', 'a')
    ('c', 'a', 'b')
    ('c', 'b', 'a')

    It generates all permutations of the characters in the string "abc".

  3. Generate permutations of a range:
    julia> collect(permutations(1:3))
    6-element Array{Tuple{Int64,Int64,Int64},1}:
    (1, 2, 3)
    (1, 3, 2)
    (2, 1, 3)
    (2, 3, 1)
    (3, 1, 2)
    (3, 2, 1)

    This example generates all permutations of the range 1:3.

Common mistake example:

julia> collect(permutations([1, 2, 2]))
ERROR: ArgumentError: duplicate elements in permutation input

In this example, the input array [1, 2, 2] contains duplicate elements. The permutations function does not allow duplicate elements in the input. Ensure that the input to permutations is unique to avoid such errors.

See Also

Array, broadcast, cat, combinations, conj!, digits!, fieldnames, fill, fill!, last, length, maximum, minimum, ones, parent, parentindexes, partitions, permutations, pointer, pointer_to_array, promote_shape, rand!, reshape, scale, similar, sum, sum_kbn, takebuf_array, transpose!, vec, zeros,

User Contributed Notes

Add a Note

The format of note supported is markdown, use triple backtick to start and end a code block.

*Required Field
Details

Checking you are not a robot: