Skip to content

Commit

Permalink
feat: Gray Code
Browse files Browse the repository at this point in the history
  • Loading branch information
jirikostiha committed Jun 5, 2023
1 parent fda0ca1 commit bd765ce
Show file tree
Hide file tree
Showing 2 changed files with 63 additions and 0 deletions.
19 changes: 19 additions & 0 deletions src/code/SMath/BinaryIntegerExtension.cs
Original file line number Diff line number Diff line change
Expand Up @@ -24,5 +24,24 @@ public static N HammingDistanceTo<N>(this N number, N otherNumber)

return setBits;
}

public static N ToGrayCode<N>(this N number)
where N : IBinaryInteger<N>, IUnsignedNumber<N>
=> number ^ (number >> 1);

public static N FromGrayCode<N>(this N gray)
where N : IBinaryInteger<N>, IUnsignedNumber<N>
{
var n = gray;
var result = n;

while (n > N.Zero)
{
n >>= 1;
result ^= n;
}

return result;
}
}
}
44 changes: 44 additions & 0 deletions src/quality/SMath__Tests/BinaryIntegerExtensionTests.cs
Original file line number Diff line number Diff line change
Expand Up @@ -31,5 +31,49 @@ public void HammingDistance_Byte(byte n1, byte n2, byte distance)
{
Assert.Equal(distance, n1.HammingDistanceTo(n2));
}

[Theory]
[InlineData(1, 1)]
[InlineData(2, 3)]
[InlineData(3, 2)]
[InlineData(7, 4)]
[InlineData(15, 8)]
public void ToGrayCode_Byte(byte number, byte gray)
{
Assert.Equal(gray, number.ToGrayCode());
}

[Theory]
[InlineData(1, 1)]
[InlineData(2, 3)]
[InlineData(3, 2)]
[InlineData(7, 4)]
[InlineData(15, 8)]
public void ToGrayCode_Int(uint number, uint gray)
{
Assert.Equal(gray, number.ToGrayCode());
}

[Theory]
[InlineData(1, 1)]
[InlineData(3, 2)]
[InlineData(2, 3)]
[InlineData(4, 7)]
[InlineData(8, 15)]
public void FromGrayCode_Byte(byte gray, byte number)
{
Assert.Equal(number, gray.FromGrayCode());
}

[Theory]
[InlineData(1, 1)]
[InlineData(3, 2)]
[InlineData(2, 3)]
[InlineData(4, 7)]
[InlineData(8, 15)]
public void FromGrayCode_Int(uint gray, uint number)
{
Assert.Equal(number, gray.FromGrayCode());
}
}
}

0 comments on commit bd765ce

Please sign in to comment.