Mas*_*ler 2 delphi algorithm set
有没有办法提取集合中的最高(或最低)值?例如,如果我有以下"字节集":
[0, 1, 2, 4, 5, 28, 199]
Run Code Online (Sandbox Code Playgroud)
我可以运行任何功能并返回199作为结果?
编辑:有一个明显的暴力解决方案涉及for..in循环.如果可能的话,我想找到一个比这更好的方法.
Rob*_*edy 14
循环确实是正式的正确方法.
type
TSetType = set of TEnumType;
function HighestMember(const s: TSetType): TEnumType;
begin
for Result := High(Result) downto Low(Result) do
if Result in s then
exit;
raise Exception.Create('empty sets have no highest member');
end;
Run Code Online (Sandbox Code Playgroud)
任何其他类型的解决方案都需要使用类型转换或汇编程序,这两种方法都会迫使您失去类型安全性 - 它们会"超出语言",可以这么说.
如果你可以保证你的集合不超过32个可能的元素,那么集合可以用普通整数覆盖,你的问题等同于要求在32位整数中设置最高位的位置.之前有人问过这个,差不多:
如果你对集合类型没有32个元素的限制,那么你有Delphi的256个元素的限制,任何bit-twiddling解决方案都需要处理32 字节的输入.
| 归档时间: |
|
| 查看次数: |
4866 次 |
| 最近记录: |