Create a formula from a set of number ranges

303 Views Asked by At

I'm not sure what what to call what I would like help creating so please bear with me.

Basically I have a program which assigns you a number of points(a competition point not a point on a graph or anything) depending on how quickly you answer a query. This is how it looks:

Response Time in Hours | Points Awarded
0 | 10 Points
1-6 | 8 Points
6-12 | 6 Points
12-18 | 4 Points
18-24 | 2 Points
24+ | 0 Points

This can be achieved by making multiple if queries but that could end up being a strain on the server. I would like to know if there is a formula that I could just multiply the response time by which could give me a result in that range? Is this even possible?

Thanks in advance for any help.

1

There are 1 best solutions below

5
On BEST ANSWER

Yes. The trick is to use the ceiling function. Let $x=$ response time. Then we can determine the points awarded by using the piecewise function: $$ f(x)=\begin{cases} 10-2\left\lceil\dfrac{x}{6}\right\rceil & \text{if }0\leq x\leq24 \\ 0 & \text{if }x>24 \end{cases}$$

In Python, you could implement this as something like:

import math
def awardPoints(x):
    """
     PRE: x is the (positive) response time in hours.
    POST: Returns the points to be awarded.
    """
    if x <  0: return -1  # ERROR: x must be positive.
    if x > 24: return 0   # We don't want to award negative points.

    # Else, we know that 0 <= x <= 24.
    return 10 - 2*math.ceil(x / 6.0)