I'm a little disappointed in myself for giving this question so much thought, but that being said, I'm going to go out on a limb and say there is no general solution for all n > 0
that either doesn't use an if
statement, or doesn't use some other kind of trickery to simulate one. I'll gladly eat my words if someone demonstrates me wrong.
For each tree, the obvious and correct solution is:
cut = max(height - limit, 0);
which is equivalent to:
if ( height - limit > 0 ) {
cut = height - limit;
} else {
cut = 0;
}
or alternatively:
if ( height > limit ) {
cut = height - limit;
} else {
cut = 0;
}
The simplest way (other than using a max()
function) to simulate this without actually explicitly using an if
statement is:
cut = (height - limit) * (height > limit);
since height > limit
will evaluate to 1
or 0
at the right times.
You can also simulate it with a while
loop as so:
cut = 0;
while ( height > limit ) {
cut = height - limit;
break;
}
and using a ternary operator is the most blatant way to claim to not use an if
. There may be other tricks messing with bits, but the story is the same.
It's possible to modify any of these methods to employ the modulo operator as the question asks, but all that achieves is making a simpler algorithm more complex.
I suspect the method in abelenky's answer is the one that's being sought and probably the best overall solution to the question, here, even though it only works for 0 < n < 2 * limit
.
ternary
statements? – Rooted(Tree1 - 11) + (Tree3 - 11)
. We omitTree2
because it is<= 11
. – Carpern = tree - (tree % limit)
will only work for tree excesses less than the limit. – Heinrikif
is the correct tool. Other things are silly games that are not very helpful for actually learning anything. – Lanneretif
is not allowed. What aboutwhile
orfor
statements? – Crust