Delphi   发布时间:2022-04-11  发布网站:大佬教程  code.js-code.com
大佬教程收集整理的这篇文章主要介绍了德尔福阵列的电源组大佬教程大佬觉得挺不错的,现在分享给大家,也给大家做个参考。
我正在尝试编写一个函数,它将在输入和返回数组的数组上采用数组,包含所有可能的输入数组子集(没有空元素的幂集).例如对于输入:[1,2,3],结果将是[[1],[2],[3],[1,2],[2,3]].

这个函数在python中完成了这个工作

def list_powerset(lst):
    result = [[]]
    for x in lst:
        result += [subset + [x] for subset in result]
    result.pop(0)
    return result

但我正在寻找在Delphi中实现它.这有可能以这种方式实现,还是应该寻找其他东西?

解决方法

type
  TIdArray = array of Integer;
  TPowerSet = array of TIdArray;

function PowerSet(Ids: TIdArray): TPowerSet;
// Implementation loosely based on the explanation on
// http://www.mathsisfun.com/sets/power-set.html
var
  @R_388_10586@lCombinations: Integer;
  @R_388_10586@lItems: Integer;
  Combination: Integer;
  sourceItem: Integer;
  ResultItem: Integer;
  Bit,Bits: Integer;
begin
  @R_388_10586@lItems := Length(Ids);

  // @R_388_10586@l number of combination for array of n items = 2 ^ n.
  @R_388_10586@lCombinations := 1 shl @R_388_10586@lItems;

  SetLength(Result,@R_388_10586@lCombinations);

  for Combination := 0 to @R_388_10586@lCombinations - 1 do
  begin
    // The Combination variable contains a bitmask that tells us which items
    // to take from the array to construct the current combination.
    // Disadvantage is that because of this method,the input array may contain
    // at most 32 items.

    // Count the number of bits set in Combination. This is the number of items
    // we need to allocate for this combination.
    Bits := 0;
    for Bit := 0 to @R_388_10586@lItems - 1 do
      if Combination and (1 shl Bit) <> 0 then
        Inc(Bits);

    // Allocate the items.
    SetLength(result[Combination],Bits);

    // Copy the right items to the current result item.
    ResultItem := 0;

    for sourceItem := 0 to @R_388_10586@lItems - 1 do
      if Combination and (1 shl sourceItem) <> 0 then
      begin
        result[Combination][ResultItem] := Ids[sourceItem];
        Inc(ResultItem);
      end;
  end;

end;

大佬总结

以上是大佬教程为你收集整理的德尔福阵列的电源组全部内容,希望文章能够帮你解决德尔福阵列的电源组所遇到的程序开发问题。

如果觉得大佬教程网站内容还不错,欢迎将大佬教程推荐给程序员好友。

本图文内容来源于网友网络收集整理提供,作为学习参考使用,版权属于原作者。
如您有任何意见或建议可联系处理。小编QQ:384754419,请注明来意。