Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- /// <summary>
- /// Maps an integer value from between one range of integers to another.
- /// </summary>
- /// <param name="value">The value to map.</param>
- /// <param name="existingLowerBound">The lower bound of the starting range, inclusive.</param>
- /// <param name="existingUpperBound">The upper bound of the starting range, inclusive.</param>
- /// <param name="newLowerBound">The lower bound of the end range, inclusive.</param>
- /// <param name="newUpperBound">The upper bound of the end range, inclusive.</param>
- /// <param name="roundingMode">The <see cref="System.MidpointRounding"/> mode used to round non-integer results.</param>
- static int MapIntegerRange(int value, int existingLowerBound, int existingUpperBound, int newLowerBound, int newUpperBound, MidpointRounding roundingMode = MidpointRounding.ToEven)
- {
- if (existingUpperBound <= existingLowerBound) { throw new ArgumentOutOfRangeException(nameof(existingUpperBound), "Existing upper bound must be greater than the existing lower bound."); }
- if (newUpperBound <= newLowerBound) { throw new ArgumentOutOfRangeException(nameof(newUpperBound), "New upper bound must be greater than the new lower bound.");
- if (value < existingLowerBound) { throw new ArgumentOutOfRangeException(nameof(value), "Value must be greater than or equal to the existing lower bound."); }
- if (value > existingUpperBound) { throw new ArgumentOutOfRangeException(nameof(value), "Value must be less than or equal to the existing upper bound."); }
- if (existingLowerBound == newLowerBound && existingUpperBound == newUpperBound) { return value; }
- float ratio = (float)(value - existingLowerBound) / (float)(existingUpperBound - existingLowerBound);
- float result = (ratio * (newUpperBound - newLowerBound)) + newLowerBound;
- return (int)Math.Round(result, roundingMode);
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement