德尔福阵列的电源组

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

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

  1. def list_powerset(lst):
  2. result = [[]]
  3. for x in lst:
  4. result += [subset + [x] for subset in result]
  5. result.pop(0)
  6. return result

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

解决方法

  1. type
  2. TIdArray = array of Integer;
  3. TPowerSet = array of TIdArray;
  4.  
  5. function PowerSet(Ids: TIdArray): TPowerSet;
  6. // Implementation loosely based on the explanation on
  7. // http://www.mathsisfun.com/sets/power-set.html
  8. var
  9. TotalCombinations: Integer;
  10. TotalItems: Integer;
  11. Combination: Integer;
  12. SourceItem: Integer;
  13. ResultItem: Integer;
  14. Bit,Bits: Integer;
  15. begin
  16. TotalItems := Length(Ids);
  17.  
  18. // Total number of combination for array of n items = 2 ^ n.
  19. TotalCombinations := 1 shl TotalItems;
  20.  
  21. SetLength(Result,TotalCombinations);
  22.  
  23. for Combination := 0 to TotalCombinations - 1 do
  24. begin
  25. // The Combination variable contains a bitmask that tells us which items
  26. // to take from the array to construct the current combination.
  27. // Disadvantage is that because of this method,the input array may contain
  28. // at most 32 items.
  29.  
  30. // Count the number of bits set in Combination. This is the number of items
  31. // we need to allocate for this combination.
  32. Bits := 0;
  33. for Bit := 0 to TotalItems - 1 do
  34. if Combination and (1 shl Bit) <> 0 then
  35. Inc(Bits);
  36.  
  37. // Allocate the items.
  38. SetLength(Result[Combination],Bits);
  39.  
  40. // Copy the right items to the current result item.
  41. ResultItem := 0;
  42.  
  43. for SourceItem := 0 to TotalItems - 1 do
  44. if Combination and (1 shl SourceItem) <> 0 then
  45. begin
  46. Result[Combination][ResultItem] := Ids[SourceItem];
  47. Inc(ResultItem);
  48. end;
  49. end;
  50.  
  51. end;

猜你在找的Delphi相关文章