2022-01-07 05:06:06 +00:00
|
|
|
const std = @import("std");
|
2021-09-03 00:12:48 +01:00
|
|
|
const popcount = @import("popcount.zig");
|
2022-01-07 05:06:06 +00:00
|
|
|
const testing = std.testing;
|
2021-09-03 00:12:48 +01:00
|
|
|
|
|
|
|
fn popcountsi2Naive(a: i32) i32 {
|
|
|
|
var x = a;
|
|
|
|
var r: i32 = 0;
|
2023-06-22 18:46:56 +01:00
|
|
|
while (x != 0) : (x = @as(i32, @bitCast(@as(u32, @bitCast(x)) >> 1))) {
|
|
|
|
r += @as(i32, @intCast(x & 1));
|
2021-09-03 00:12:48 +01:00
|
|
|
}
|
|
|
|
return r;
|
|
|
|
}
|
|
|
|
|
|
|
|
fn test__popcountsi2(a: i32) !void {
|
|
|
|
const x = popcount.__popcountsi2(a);
|
|
|
|
const expected = popcountsi2Naive(a);
|
|
|
|
try testing.expectEqual(expected, x);
|
|
|
|
}
|
|
|
|
|
|
|
|
test "popcountsi2" {
|
|
|
|
try test__popcountsi2(0);
|
|
|
|
try test__popcountsi2(1);
|
|
|
|
try test__popcountsi2(2);
|
2023-06-22 18:46:56 +01:00
|
|
|
try test__popcountsi2(@as(i32, @bitCast(@as(u32, 0xfffffffd))));
|
|
|
|
try test__popcountsi2(@as(i32, @bitCast(@as(u32, 0xfffffffe))));
|
|
|
|
try test__popcountsi2(@as(i32, @bitCast(@as(u32, 0xffffffff))));
|
2021-09-03 00:12:48 +01:00
|
|
|
|
2024-02-08 14:21:35 +00:00
|
|
|
const RndGen = std.Random.DefaultPrng;
|
2021-09-03 00:12:48 +01:00
|
|
|
var rnd = RndGen.init(42);
|
|
|
|
var i: u32 = 0;
|
|
|
|
while (i < 10_000) : (i += 1) {
|
2023-11-10 05:27:17 +00:00
|
|
|
const rand_num = rnd.random().int(i32);
|
2021-09-03 00:12:48 +01:00
|
|
|
try test__popcountsi2(rand_num);
|
|
|
|
}
|
|
|
|
}
|