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;
|
2019-03-06 04:09:00 +00:00
|
|
|
|
2021-09-03 00:12:48 +01:00
|
|
|
fn popcountdi2Naive(a: i64) i32 {
|
|
|
|
var x = a;
|
2019-03-06 04:09:00 +00:00
|
|
|
var r: i32 = 0;
|
2023-06-22 18:46:56 +01:00
|
|
|
while (x != 0) : (x = @as(i64, @bitCast(@as(u64, @bitCast(x)) >> 1))) {
|
|
|
|
r += @as(i32, @intCast(x & 1));
|
2019-03-06 04:09:00 +00:00
|
|
|
}
|
|
|
|
return r;
|
|
|
|
}
|
|
|
|
|
2021-05-06 07:32:29 +01:00
|
|
|
fn test__popcountdi2(a: i64) !void {
|
2021-09-03 00:12:48 +01:00
|
|
|
const x = popcount.__popcountdi2(a);
|
|
|
|
const expected = popcountdi2Naive(a);
|
|
|
|
try testing.expectEqual(expected, x);
|
2019-03-06 04:09:00 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
test "popcountdi2" {
|
2021-05-06 07:32:29 +01:00
|
|
|
try test__popcountdi2(0);
|
|
|
|
try test__popcountdi2(1);
|
|
|
|
try test__popcountdi2(2);
|
2023-06-22 18:46:56 +01:00
|
|
|
try test__popcountdi2(@as(i64, @bitCast(@as(u64, 0xffffffff_fffffffd))));
|
|
|
|
try test__popcountdi2(@as(i64, @bitCast(@as(u64, 0xffffffff_fffffffe))));
|
|
|
|
try test__popcountdi2(@as(i64, @bitCast(@as(u64, 0xffffffff_ffffffff))));
|
2021-09-03 00:12:48 +01:00
|
|
|
|
2022-01-07 05:06:06 +00:00
|
|
|
const RndGen = std.rand.DefaultPrng;
|
2021-09-03 00:12:48 +01:00
|
|
|
var rnd = RndGen.init(42);
|
|
|
|
var i: u32 = 0;
|
|
|
|
while (i < 10_000) : (i += 1) {
|
|
|
|
var rand_num = rnd.random().int(i64);
|
|
|
|
try test__popcountdi2(rand_num);
|
|
|
|
}
|
2019-03-06 04:09:00 +00:00
|
|
|
}
|