Advertisement
Guest User

Untitled

a guest
Jun 26th, 2017
52
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.78 KB | None | 0 0
  1. /// <summary>
  2. /// Maps an integer value from between one range of integers to another.
  3. /// </summary>
  4. /// <param name="value">The value to map.</param>
  5. /// <param name="existingLowerBound">The lower bound of the starting range, inclusive.</param>
  6. /// <param name="existingUpperBound">The upper bound of the starting range, inclusive.</param>
  7. /// <param name="newLowerBound">The lower bound of the end range, inclusive.</param>
  8. /// <param name="newUpperBound">The upper bound of the end range, inclusive.</param>
  9. /// <param name="roundingMode">The <see cref="System.MidpointRounding"/> mode used to round non-integer results.</param>
  10. static int MapIntegerRange(int value, int existingLowerBound, int existingUpperBound, int newLowerBound, int newUpperBound, MidpointRounding roundingMode = MidpointRounding.ToEven)
  11. {
  12. if (existingUpperBound <= existingLowerBound) { throw new ArgumentOutOfRangeException(nameof(existingUpperBound), "Existing upper bound must be greater than the existing lower bound."); }
  13. if (newUpperBound <= newLowerBound) { throw new ArgumentOutOfRangeException(nameof(newUpperBound), "New upper bound must be greater than the new lower bound.");
  14.  
  15. if (value < existingLowerBound) { throw new ArgumentOutOfRangeException(nameof(value), "Value must be greater than or equal to the existing lower bound."); }
  16. if (value > existingUpperBound) { throw new ArgumentOutOfRangeException(nameof(value), "Value must be less than or equal to the existing upper bound."); }
  17.  
  18. if (existingLowerBound == newLowerBound && existingUpperBound == newUpperBound) { return value; }
  19.  
  20. float ratio = (float)(value - existingLowerBound) / (float)(existingUpperBound - existingLowerBound);
  21. float result = (ratio * (newUpperBound - newLowerBound)) + newLowerBound;
  22. return (int)Math.Round(result, roundingMode);
  23. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement