Skip to content

Commit d59c28a

Browse files
Add Floor numeric algorithm (#493)
1 parent 5239e71 commit d59c28a

File tree

3 files changed

+51
-0
lines changed

3 files changed

+51
-0
lines changed
+27
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,27 @@
1+
using System;
2+
using System.Numerics;
3+
using Algorithms.Numeric;
4+
using NUnit.Framework;
5+
6+
namespace Algorithms.Tests.Numeric;
7+
8+
public static class FloorTests
9+
{
10+
[TestCase(0.0, 0)]
11+
[TestCase(1.1, 1)]
12+
[TestCase(1.9, 1)]
13+
[TestCase(1.0, 1)]
14+
[TestCase(-1.1, -2)]
15+
[TestCase(-1.9, -2)]
16+
[TestCase(-1.0, -1)]
17+
[TestCase(1000000000.1, 1000000000)]
18+
[TestCase(1, 1)]
19+
public static void GetsFloorVal<T>(T inputNum, T expected) where T : INumber<T>
20+
{
21+
// Act
22+
var result = Floor.FloorVal(inputNum);
23+
24+
// Assert
25+
Assert.That(result, Is.EqualTo(expected));
26+
}
27+
}

Algorithms/Numeric/Floor.cs

+23
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,23 @@
1+
using System;
2+
using System.Numerics;
3+
4+
namespace Algorithms.Numeric;
5+
6+
/// <summary>
7+
/// Perform floor operation on a number.
8+
/// </summary>
9+
public static class Floor
10+
{
11+
/// <summary>
12+
/// Returns the largest integer less than or equal to the number.
13+
/// </summary>
14+
/// <typeparam name="T">Type of number.</typeparam>
15+
/// <param name="inputNum">Number to find the floor of.</param>
16+
/// <returns>Floor value of the number.</returns>
17+
public static T FloorVal<T>(T inputNum) where T : INumber<T>
18+
{
19+
T intPart = T.CreateChecked(Convert.ToInt32(inputNum));
20+
21+
return inputNum < intPart ? intPart - T.One : intPart;
22+
}
23+
}

README.md

+1
Original file line numberDiff line numberDiff line change
@@ -75,6 +75,7 @@ find more than one implementation for the same objective but using different alg
7575
* [Decomposition](./Algorithms/Numeric/Decomposition)
7676
* [LU Decomposition](./Algorithms/Numeric/Decomposition/LU.cs)
7777
* [Thin Singular Vector Decomposition](./Algorithms/Numeric/Decomposition/ThinSVD.cs)
78+
* [Floor](./Algorithms/Floor.cs)
7879
* [Greatest Common Divisor](./Algorithms/Numeric/GreatestCommonDivisor)
7980
* [Euclidean GCD](./Algorithms/Numeric/GreatestCommonDivisor/EuclideanGreatestCommonDivisorFinder.cs)
8081
* [Binary GCD](./Algorithms/Numeric/GreatestCommonDivisor/BinaryGreatestCommonDivisorFinder.cs)

0 commit comments

Comments
 (0)