使用Ruby或Javascript为A,B,C生成唯一的组合

时间:2018-04-20 07:40:14

标签: javascript arrays ruby combinations permutation

我有三组:

Group A = 4
Group B = 8
Group C = 11

对于每个组,如果我添加其他项目,例如:

Group A = 4;
Group A Additional = 2;

Group B = 8;
Group B Additional = 3;

Group C = 10;
Group C Additional = 3;

我需要根据可用的组数添加附加内容。 例如:

A = 4
AA = 6 (4 + 2)
AAA = 8 (4 + 2 + 2) here I have A and 2 additional items

B = 8
BB = 11 (8 + 3)
BBB = 14 (8 + 3 + 3)

Same for C...

我需要使用正确的值生成这些组的所有可能组合。

这应该是结果:

A, AA, AAA
B, BA, BAA, BB, BBA, BBB
C, CA, CAA, CB, CBA, CBB, CC, CCA, CCB, CCC

如果AAA为8(4 + 2 + 2)且BBB = 14(8 + 3 + 3) 我想要:

CBA to be 22 (10 + 8 + 4)
CBB to be (10 + 8 + 8)

等等。

这是我到目前为止所做的。

items = [
  { :group => "A", :value=> 4, :add => 2 },
  { :group => "B", :value=> 8, :add => 3 },
  { :group => "C", :value=> 10, :add => 3 },
]

def process(items)
  array = []

  items.each_with_index do |item, index|
  counter = 0
    (1..3).each do |vari|
      el = item[:group] * vari

      if vari == 1 
        value = item[:value]
      else 
        value = item[:value] + (item[:add] * counter)
      end

      puts "#{el}:  #{value}"

      array.push(el)
      counter = counter + 1
    end
  end
  array
end

它只适用于 A,AA,AAA B,BB,BBB C,CC,CCC

输出:

A:  4
AA:  6
AAA:  8
B:  8
BB:  11
BBB:  14
C:  10
CC:  13
CCC:  16

任何人都可以帮助完成脚本吗?

2 个答案:

答案 0 :(得分:1)

您可以通过为下一次调用函数获取索引来使用递归方法。

此解决方案采用虚拟项目来获得单个或双重组合。

function c(array, size) {

    function iter(i, p) {
        var temp = p.join('');
        if (i >= array.length) {
            return;
        }
        if (p.length === size) {
            temp && result.push(temp);
            return;
        }
        iter(i + 1, p);
        iter(i, p.concat(array[i]));
    }

    var result = [];
    iter(0, []);
    return result;
}

var values = { A: { value: 4, add: 2 }, B: { value: 8, add: 3 }, C: { value: 10, add: 3 } },
    combinations = c(['C', 'B', 'A', ''], 3),
    result = combinations.map(s => [...s].reduce(
        (r, k, i, a) => r + values[k][['value', 'add'][+(k === a[i - 1])]],
        0
    ));

console.log(combinations);
console.log(result);
.as-console-wrapper { max-height: 100% !important; top: 0; }

答案 1 :(得分:0)

出于好奇,红宝石:

w = {:a=>[4, 2], :b=>[8, 3], :c=>[10, 3], nil =>[0, 0]}
[1, 2, 3].flat_map do |count|
  %i[a b c].repeated_combination(count).map do |a, b, c|
    [
      [a, b, c].join.upcase,
      a == b ? 
        w[a].first + (b == c ? w[a].last * 2 : w[a].last + w[c].first) :
        [w[a], w[b], w[c]].map(&:first).reduce(:+)
    ]
  end
end.to_h

#⇒ {"A"=>4, "B"=>8, "C"=>10,
#   "AA"=>6, "AB"=>12, "AC"=>14, "BB"=>11, "BC"=>18, "CC"=>13,
#   "AAA"=>8, "AAB"=>14, "AAC"=>16, "ABB"=>20, "ABC"=>22,
#      "ACC"=>24, "BBB"=>14, "BBC"=>21, "BCC"=>28, "CCC"=>16}