我正在尝试编写一个函数,它将在输入和返回数组的数组上采用数组,包含所有可能的输入数组子集(没有空元素的幂集).例如对于输入:[1,2,3],结果将是[[1],[2],[3],[1,2],[2,3]].
- 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
- TotalCombinations: Integer;
- TotalItems: Integer;
- Combination: Integer;
- SourceItem: Integer;
- ResultItem: Integer;
- Bit,Bits: Integer;
- begin
- TotalItems := Length(Ids);
- // Total number of combination for array of n items = 2 ^ n.
- TotalCombinations := 1 shl TotalItems;
- SetLength(Result,TotalCombinations);
- for Combination := 0 to TotalCombinations - 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 TotalItems - 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 TotalItems - 1 do
- if Combination and (1 shl SourceItem) <> 0 then
- begin
- Result[Combination][ResultItem] := Ids[SourceItem];
- Inc(ResultItem);
- end;
- end;
- end;