A question from a job interview: math function that returns the number of positive numbers.

238 Views Asked by At

Describe a mathemathical function that receives 5 parameters, And returns the number of positive numbers.

$f(x_1,x_2,x_3,x_4,x_5)\to 5,4,3,2,1,0$ - according to the number of positive numbers.

Unfortunally i didn't have success on beating this one. And although i didn't get the job, I'm quite intrigued by the answer on this one. Anyone got any idea?

2

There are 2 best solutions below

0
On BEST ANSWER

$f(x_1,x_2,x_3,x_4,x_5)$ = the number of positive numbers amongst the $x_i$

is a perfectly reasonable description of a math function that returns the number of positive numbers amongst the five parameters.

If I define

$$ g(x) = \begin{cases} 0 & x \leq 0 \\ 1 & x > 0 \end{cases} $$

then

$$f(x_1, x_2, x_3, x_4, x_5) = \sum_{i=1}^5 g(x_i) $$

is another reasonable description. And so forth.

For many purposes, these sorts of simple descriptions are much better than any alternative; don't bother looking for more "clever" descriptions unless you actually need to. And then, you should do your best to be very clear about just what you need from a description, so that you don't make trouble for yourself by overlooking other easy things.

Incidentally, the Iverson bracket gives a simple way to write $g$:

$$f(x_1, x_2, x_3, x_4, x_5) = \sum_{i=1}^5 [x_i > 0] $$

1
On

$$f(x_{1}, ..., x_{5}) = \sum_{i=1}^{5} g(x_{i})$$

where we defined $g(x) = \frac{|x| + x}{2x}$ if $x \neq 0$, 0 otherwise.

The function $g$ takes the value $1$ if and only if $x$ is stricly greater than 0, for in this case $x+|x| = 2x$. When $x\leq 0$, $|x| -x$ =0.

Hence, $f$ counts the number of positive numbers among the $x_{i}$'s.

edit : did I get the job ? :)