Can you make this shorter, more elegant, and more julia-esque

Hi
Can you make this code more elegant

flag1 = (0,1)
flag2 = (0,1)
flag3 = (0,1)
flag4 = (0,1)
flag5 = (0,1)

for i1 in flag1
    for i2 in flag2
        for i3 in flag3
            for i4  in flag4 
                for i5 in flag5
                    println("$i1 , $i2, $i3, $i4, $i5")
                end
            end
        end
    end
end

Back ground information, I was writing a case statement for a sql query
that check 5 flags (each flag is boolean, yes or no, 1 or 0)
And based on the combination of the 5 flags I decide the record final status
I wanted to make sure that my SQL Case covered all cases
Since I have 5 flags then its 2 to the power of 5 case, 32 cases
I was about the type the 32 cases in excel and go through them one by one to see if I missed any
I then decided to write those few line to help me (since I am learning Julia anyway on the side)

This obviously look, not so elegant, and that is only because I am nice to me :slight_smile:
But it works, I copied the output to excel and it helped me make sure I covered all the cases
And provided nice docs for the query

well, first you don’t need 5 (0,1), they are the same thing, and then, you can put them in just one line:

for a∈(0,1),b∈(0,1),c∈(0,1)

if you are willing to use Combinatorics.jl

julia> Iterators.flatten(permutations.(with_replacement_combinations([0,1], 5)) .|> unique) |> collect
32-element Array{Array{Int64,1},1}:
 [0, 0, 0, 0, 0]
 [0, 0, 0, 0, 1]
 [0, 0, 0, 1, 0]
 [0, 0, 1, 0, 0]
 [0, 1, 0, 0, 0]
 [1, 0, 0, 0, 0]
 [0, 0, 0, 1, 1]
 [0, 0, 1, 0, 1]
 [0, 0, 1, 1, 0]
 [0, 1, 0, 0, 1]
 [0, 1, 0, 1, 0]
 [0, 1, 1, 0, 0]
 [1, 0, 0, 0, 1]
 ⋮
 [1, 0, 0, 1, 1]
 [1, 0, 1, 0, 1]
 [1, 0, 1, 1, 0]
 [1, 1, 0, 0, 1]
 [1, 1, 0, 1, 0]
 [1, 1, 1, 0, 0]
 [0, 1, 1, 1, 1]
 [1, 0, 1, 1, 1]
 [1, 1, 0, 1, 1]
 [1, 1, 1, 0, 1]
 [1, 1, 1, 1, 0]
 [1, 1, 1, 1, 1]
1 Like

Input

foreach(println, Iterators.product(Iterators.repeated((0, 1), 5)...))

Output

(0, 0, 0, 0, 0)
(1, 0, 0, 0, 0)
(0, 1, 0, 0, 0)
(1, 1, 0, 0, 0)
(0, 0, 1, 0, 0)
(1, 0, 1, 0, 0)
(0, 1, 1, 0, 0)
(1, 1, 1, 0, 0)
(0, 0, 0, 1, 0)
(1, 0, 0, 1, 0)
(0, 1, 0, 1, 0)
(1, 1, 0, 1, 0)
(0, 0, 1, 1, 0)
(1, 0, 1, 1, 0)
(0, 1, 1, 1, 0)
(1, 1, 1, 1, 0)
(0, 0, 0, 0, 1)
(1, 0, 0, 0, 1)
(0, 1, 0, 0, 1)
(1, 1, 0, 0, 1)
(0, 0, 1, 0, 1)
(1, 0, 1, 0, 1)
(0, 1, 1, 0, 1)
(1, 1, 1, 0, 1)
(0, 0, 0, 1, 1)
(1, 0, 0, 1, 1)
(0, 1, 0, 1, 1)
(1, 1, 0, 1, 1)
(0, 0, 1, 1, 1)
(1, 0, 1, 1, 1)
(0, 1, 1, 1, 1)
(1, 1, 1, 1, 1)
4 Likes

Cool, but will need to remove the braces ( and ) from each line
From my code I do a

julia script.jl  >> file1.csv

and open it in excel :slight_smile:

Ok, here’s a small modification that writes the result as a CSV file:

using DelimitedFiles   # This is a standard library module.

writedlm(
    "test.csv",
    Iterators.product(Iterators.repeated((0, 1), 5)...),
    ','
)
4 Likes