Permutations of Boolean values in ruby hash -
i need implement function gets array symbols parameters [:a :b :c]
, , returns array contains possible permutations of boolean values mapped symbols in hash
like
[{a: true, b: true, c: true}, {a: false, b: true, c: true}, {a: true, b: false, c: true}, {a: true, b: true, c: false}, {a: true, b: false, c: false}, {a: false, b: false, c: true}, {a: false, b: true, c: false}, {a: false, b: false, c: false}]
what elegant way implement such thing in ruby?
i use repeated_permutation
task:
[true, false].repeated_permutation(3) .map { |a, b, c| { a: a, b: b, c: c } } #=> [{:a=>true, :b=>true, :c=>true}, # {:a=>true, :b=>true, :c=>false}, # {:a=>true, :b=>false, :c=>true}, # {:a=>true, :b=>false, :c=>false}, # {:a=>false, :b=>true, :c=>true}, # {:a=>false, :b=>true, :c=>false}, # {:a=>false, :b=>false, :c=>true}, # {:a=>false, :b=>false, :c=>false}]
or array of keys:
keys = %i(a b c) [true, false].repeated_permutation(keys.size) .map { |values| keys.zip(values).to_h }
Comments
Post a Comment