Vectors of length N with elements from another vector (with repetition)

Viewed 203

Is there any easy way to generate an array of permutations of length N, drawn from k values? Example:

N = 2
k = [[0 0], [0 1], [1 0], [1 1]]
Permutations = [
    [[0 0], [0 0]],
    [[0 0], [0 1]],
    [[0 0], [1 0]],
    [[0 0], [1 1]],
    [[0 1], [0 0]],
    [[0 1], [0 1]],
    [[0 1], [1 0]],
    [[0 1], [1 1]],
    ...
]

An important note here: If possible, I'd like the result to be arrays all the way down (the product function in the Iterators package generates tuples)

If it helps, the Haskell equivalent would be: replicateM 2 [[0, 0], [0, 1], [1, 0], [1, 1]]

Just in case there's a more idiomatic way to achieve what I'm trying to do, here's the function I'm writing:

function generate_states(length)
    # "tuples" contains what I want, but it needs a lot of transformation to 
    # be usable later
    tuples = [collect(t) for t in
              product([product(0:1, 0:1) for _ in 1:length]...)]
    states = collect(distinct(imap(x -> kron([[i...] for i in x]...), tuples)))
    return states
end

Which works, and does what I want, but ideally I'd like it to look something like this:

function generate_states(length)
    arrays = replicateM(3, Array[[0 0], [0 1], [1 0], [1 1]])
    states = collect(distinct(imap(x -> kron(x...), arrays)))
    return states
end
2 Answers
Related