Hi guys, I have a very special question/request.
Basically, I would like to have a function that when you give a array size, it return all possible combination of bool with an array of this size (So I mean combination of true and false basically)
For example you give to the function: I would like a bolean array with size 3, return me a full list of combination of bolean possible.
Like:
Array of size 3 ?
Return:
[true, true, true] [false,false,false] [true,false,true] [false,true,false] …etc
Let me know if it is not clear.
Any idea about the approach I should use, or maybe a function I can already use/call ?
Out of curiosity what’s the use case for this? .
[true, false].repeated_permutations(4)
6 Likes
I am surprise a guy full of wisdom like you don’t have idea when to use this !
Definitely one case I think directly is when you would like to make a brute force cli for example .
But in my case it’s something else. It’s to optimise the dependency calculation process by providing precalculated fragment to the package manager
Because every package have options can be enabled or disabled, so it change the dependencies
I have another question , maybe stupid.
Now if I have for example an array of bool like this:
[true,false,true]
Is there any function that can give me a uniq identifier of this combination as string ?
For example in this case :
“101”
Basically , I would like to identify every different case by an identifier. Do you get what I mean again ?
But I need the fastest way
mavu
February 22, 2025, 10:47pm
7
[true,false,true].map(&.to_unsafe).join
2 Likes
Sunrise
February 23, 2025, 8:25am
8
Actually, you could input the array size, and directly get an array containing all the combinations represented as bit strings as following:
def bitsary(length : Int32)
(0..2 ** length - 1).to_a { |e| e.to_s(2, precision: length) }
end
bitsary 3 # => ["000", "001", "010", "011", "100", "101", "110", "111"]
2 Likes