0
$\begingroup$

My question is the same as this but with a catch: How many substrings of length m can be formed from a string of length n?

To find the number of possible substrings of length C in a parent string of length P I can use this formula:

$$P - C + 1$$

For example, for a parent string of length $5$ and a substring of length $3$, there are $5 - 3 + 1 = 3$ different positions the substring can take in its parent.

The catch:
The problem is, if we ask this formula how many substrings of length 3 fit in a parent string of length 1, we get $1 - 3 + 1 = -1$, instead of the expected $0$.

Is there a simple function that will give $0$ when $P < C$ without using an if statement?

$\endgroup$

2 Answers 2

1
$\begingroup$

So, you want $\max(P-C+1,0)$? In general $$\max(x,y)=\frac{x+y+|x-y|}2.$$ Therefore $$\max(P-C+1,0)=\frac{P-C+1+|P-C+1|}2.$$

But really, there is nothing wrong with case-by-case definitions!

$\endgroup$
1
$\begingroup$

You can, but it will generally involve cheating by using a function that has some kind of implicit "if" in it. For example, we could use the Heaviside step function which is defined as:

$$H(x) = \begin{cases} 1 & \mbox{if } x \gt 0 \\ \frac{1}{2} & \mbox{if } x = 0 \\ 0 & \mbox{if } x \lt 0\end{cases}$$

So you just multiply your value $S$ by $H(S)$, so that for negative values it becomes 0.

You can do the same thing with absolute values by noting that

$$x + \left|x\right| = \begin{cases} 2x & \mbox{if } x \geq 0 \\ 0 & \mbox{if } x \lt 0\end{cases}$$

So you just take your expression, add its absolute value, and divide by two, giving $\frac{1}{2}\left(P - C + 1 + \left|P - C + 1\right|\right)$.

$\endgroup$

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .