gpt4 book ai didi

delphi - Delphi中数组的幂集

转载 作者:行者123 更新时间:2023-12-03 14:47:54 25 4
gpt4 key购买 nike

我正在尝试编写一个函数,该函数将在输入上获取一个数组并返回数组数组,其中包含输入数组的所有可能的子集(没有空元素的幂集)。例如,输入:[1, 2, 3] 结果将是 [[1], [2], [3], [1, 2], [1, 3] , [2, 3], [1, 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
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;

关于delphi - Delphi中数组的幂集,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13018641/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com