{ POPCOUNT FOR SETS
Copyright (c) 2025 Thaddy de Koning, DeepSeek
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to
deal in the Software without restriction, including without limitation the
rights to use, copy, modify, merge, publish, distribute, sublicense, and/or
sell copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
IN THE SOFTWARE.
}
{$mode delphi}{$Q+}{$R+}
{$modeswitch implicitfunctionspecialization}
{$packset 1}
uses
SysUtils;
type
// Helper function for bit counting in a byte (DeepSeek)
function BytePopCount(b: Byte): Integer; inline;
const
NibbleBits: array[0..15] of Byte = (
0, 1, 1, 2, 1, 2, 2, 3,
1, 2, 2, 3, 2, 3, 3, 4
);
begin
Result := NibbleBits[b and $0F] + NibbleBits[b shr 4];
end;
// Safe set element counter
function SetCount<T>(aSet: T): Integer; inline;
var
p: PByte;
i: Integer;
begin
if GetTypeKind(T) <> tkSet then
raise ESetException.Create(rsNotaSet);
Result := 0;
p := @aSet;
for i := 0 to SizeOf(T) - 1 do
begin
Result := Result + BytePopCount(p^);
Inc(p);
end;
end;
type
range = 0..255;
var
s: set of range;
i: Integer;
begin
s := [];
try
for i in range do
begin
Include(s, i);
WriteLn('Size in bytes: ', SizeOf(s):2, ' Elements: ', SetCount(s):2);
end;
except
on E: Exception do
WriteLn('Error: ', E.Message);
end;
readln;
end.