Reputation: 874
I try to split a string to an array of equal-length substrings and the first thing I do is to calculate how many substrings there would be. While I wrote it myself I used the first expression down below. When I checked an answer given by someone else I saw the second one, which is not very obvious to me. Actually I couldn't figure out why they produce the same result though I could verify with concrete examples. So how do you prove they are equivalent in terms of generating the same result?
int groups = s.length() % subLen == 0 ? s.length() / subLen : s.length() / subLen + 1;
int groups = (s.length() + subLen - 1) / subLen;
Upvotes: 0
Views: 116
Reputation: 874
First let's think about the actual context of the problem, that is , dividing a string, suppose its length is a
, into a group of substrings whose lengths are equal, suppose that length is b
, and then we know the range of a and b should be a >= b >= 1
. If c
is the result of the integer division a / b
, which always rounds down, and if d
is the result of the normal division a / b
, and if d
is an integer, a + (b - 1)
would have no effect on making c
bigger because only a + b
can increase c
by 1. But why does it have to be b - 1
instead of b - 2
or b - 3
etc? Because the minimum of b
is 1 and if in b - ?
the ?
is bigger than 1 there's a chance that b - ?
is negative, which means there's a chance that c
would be reduced at least by 1 because a
could be reduced at least by 1. If d
is not an integer, then we know d == c * b + r
where r
is the remainder and (1) 1 <= r <= b - 1
. So (a + b - 1) / b
could be written as (c * b + r + b - 1) / b
. According to (1) we have b <= r + b - 1 <= 2 * (b - 1)
, and then have b <= r + b - 1 < 2 * b
, and then have (c + 1) * b <= a + b - 1 < (c + 2) * b
, and then c + 1 <= (a + b - 1) / b < c + 2
, which means c
would be increased by 1 exactly when normal division a / b
is not an integer.
Upvotes: 0
Reputation: 2058
Try to substitute s.length()
with different values and see how the two calculations arrive at their respective result.
In essence, your version considers two cases that are handled differently and is doing the 'rounding up' explicitly in its second code branch.
The second version adds sublen-1
to the original string length so that the rounding down / truncation of the integer division arrives at the desired result for all given values of s.length()
.
Upvotes: 1