parityti2_test.zig (1078B) - Raw
1 const std = @import("std"); 2 const parity = @import("parity.zig"); 3 const testing = std.testing; 4 5 fn parityti2Naive(a: i128) i32 { 6 var x: u128 = @bitCast(a); 7 var has_parity: bool = false; 8 while (x > 0) { 9 has_parity = !has_parity; 10 x = x & (x - 1); 11 } 12 return @intCast(@intFromBool(has_parity)); 13 } 14 15 fn test__parityti2(a: i128) !void { 16 const x = parity.__parityti2(a); 17 const expected: i128 = parityti2Naive(a); 18 try testing.expectEqual(expected, x); 19 } 20 21 test "parityti2" { 22 try test__parityti2(0); 23 try test__parityti2(1); 24 try test__parityti2(2); 25 try test__parityti2(@bitCast(@as(u128, 0xffffffff_ffffffff_ffffffff_fffffffd))); 26 try test__parityti2(@bitCast(@as(u128, 0xffffffff_ffffffff_ffffffff_fffffffe))); 27 try test__parityti2(@bitCast(@as(u128, 0xffffffff_ffffffff_ffffffff_ffffffff))); 28 29 const RndGen = std.Random.DefaultPrng; 30 var rnd = RndGen.init(42); 31 var i: u32 = 0; 32 while (i < 10_000) : (i += 1) { 33 const rand_num = rnd.random().int(i128); 34 try test__parityti2(rand_num); 35 } 36 }