I also had a little fund with this. Still not sure what the purpose of the method is but I’m assuming getting the State of an array of booleans. Maybe even, well I don’t know. When I get stuck with what should be a simple combinations of boolean, I go back to ancient methods and draw a picture! The picture is a Decision Logic Table (DLT) or Truth Table.
Basically if you have an array of N booleans, there are:
2**N combinations
An array with 2 booleans has 2**2 or 4 combinations of 2 variables
a yynn
b ynyn
An array with 3 booleans has 2**3 or 8 combinations of 3 variables
a yyyynnnn
b yynnyynn
c ynynynyn
An array with 5 booleans has 2**5 or 32 combinations of 5 variables
a yyyyyyyyyyyyyyyynnnnnnnnnnnnnnnn
b yyyyyyyynnnnnnnnyyyyyyyynnnnnnnn
c yyyynnnnyyyynnnnyyyynnnnyyyynnnn
d yynnyynnyynnyynnyynnyynnyynnyynn
e ynynynynynynynynynynynynynynynyn
Your really don’t want to write and IF statement with 32 combinations! Your example output seemed to be doing some shortcut with OR conditions. Below is a short class I threw together (I did have to go find some old stuff I had written about DLTs [http://stevealex.us/code/2010/08/10/AFOLDS-DAD-DUEL.html]) that return all possible options (not using OR)
class Truth
def give_me_the_truth(array)
return array of arrays by size of input array
indexes = array.count
combos = 2 ** indexes
truth = Array.new(indexes,Array.new)
indexes.times do |v|
half = (2 ** (indexes - (v-1))/2)
pick = Array.new(half/2,true)+ Array.new(half/2,false)
(combos/half).times do |c|
truth[v] += pick
end
end
truth
end
def the_whole_truth(array)
returns an array of arrays by size of all possibilites (states?)
whole = give_me_the_truth(array).transpose
end
def nothing_but_the_truth(array)
returns the index (state?) of a query
nothing = the_whole_truth(array).index(array)
end
end
Truth.new.give_me_the_truth([true,false,true])
=> [[true, true, true, true, false, false, false, false], [true, true, false, false, true, true, false, false], [true, false, true, false, true, false, true, false]]
Gives the possible combination in three arrays (if you need a hash just map it)
Truth.new.the_whole_truth([true,false,true])
=> [[true, true, true], [true, true, false], [true, false, true], [true, false, false], [false, true, true], [false, true, false], [false, false, true], [false, false, false]]
Give the 8 possible conditions as a transposed array.
Truth.new.nothing_but_the_truth([true,false,true])
=> 2
Gives an index into were that array is in the whole truth array.
Not sure if it has any use,
Steve