Skip to content

Instantly share code, notes, and snippets.

@Arkoniak
Last active December 8, 2019 20:06
Show Gist options
  • Save Arkoniak/794031165120932f0cd23488a74bfcee to your computer and use it in GitHub Desktop.
Save Arkoniak/794031165120932f0cd23488a74bfcee to your computer and use it in GitHub Desktop.
Permutations iterator
struct PermIter{T}
v::Vector{T}
infinite::Bool
end
function Base.iterate(iter::PermIter{T}, state = ones(Int, length(iter.v))) where T
if state[end] == 2 return nothing end
v = iter.v
elem = Vector{T}(undef, length(iter.v))
for (i, ind) in enumerate(state)
elem[i] = v[ind]
v = vcat(v[1:(ind - 1)], v[(ind + 1):end])
end
for i in length(iter.v):-1:1
if state[i] == length(iter.v) - i + 1
state[i] = 1
else
state[i] += 1
break
end
end
if !(iter.infinite) && (sum(state) == length(iter.v)) state[end] = 2 end
return (elem, state)
end
permutations(v::Vector{T}, inf = false) where T = PermIter(v, inf)
## Usage
for x in permutations(['a', 'b', 'c', 'd'])
println(join(x))
end
for (i, x) in enumerate(permutations(['a', 'b', 'c', 'd'], true))
println(join(x))
if i == 40 break end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment