实质上,我希望循环说增加i和j一,如果i = n,则停止递增i,如果m> n则继续递增j,或者如果 n> m ,则停止递增j
可能看起来微不足道,但我很好奇。
解决方案天真地,我们想要做一些事情: (int i = 0,j = 0; i <= n || j <= m; i =数学公式.min(n,i + 1),j = Math.min(m,j + 1))
...但这不会终止,因为 i 的最大值是 n ,最大值对于 j 是 m ,其中之一将始终为真。
如果你愿意让( n<我们可以这样写:) i 在 n + 1 > for(int i = 0,j = 0; i <= n || j <= m; i = Math.min (n + 1,i + 1),j = Math.min(m + 1,j + 1))只有当你想保持( n 为了让循环终止,我们希望增加一个超过其最大值的较大的数字,以便达到终止标准。既然我们知道 i <= n 和 j <= m 中的至少一个将始终为真,那么让我们专注于使 始终为真,并将终止条件改为 在 n < m , i 会在 j 之前完成递增,所以我们需要让 j 为了违反 i< = n&& j <= m 。类似的情况适用于 n> m ,但相反,我们需要增加 i >过去 n 。 注意,如果 n == m ,我们可以安全地递增他们各自的限制,并终止标准将同时打。下面的循环处理任何正面输入 n 或 m ,并根据您的条件正确终止,同时允许 n 或 m 中的较小者成为相应迭代器的最大值。 (int i = 0,j = 0,nadj = n +(n> =m≥1:0),madj = m +( (nadj,i + 1),j = Math.min(n = 1,2,...,n) madj,j + 1)) 值得注意的是,我们计算 nadj 和 madj ,以避免在每次迭代过程中重新计算它们。 Suppose you want to loop from i=0 to i=n and j=0 to j=m and that m!=n. Is it possible to shorten the following two loops into one? To something along In essence I want the loop to say "increment both i and j by one, stop incrementing i if i=n but keep incrementing j if m>n" or the other way around if n>m. May seem trivial or stupid but I am curious. Naively, we want to do something like: ...but this won't terminate, because the maximum value for i is n and the maximum value for j is m, and one of those will always be true. The problem is much simpler if you're willing to let (for n < m) i finish at n+1, as we could write: This is complicated only if you want to keep (for n < m) i = n while j finishes incrementing. The complexity is isolated to getting the loop to terminate at the right time, while still allowing j to finish incrementing. To get the loop to terminate, we want to increment the larger number one step past its maximum, so that we hit the termination criteria. Since we know at least one of i <= n and j <= m will always be true, let's focus on making both always true, and change our termination criteria to In the case where n < m, i will finish incrementing before j, and so we need to let j increment one past its effective maximum in order to violate i <= n && j <= m. A similar condition holds for n > m, but instead, we need to increment i one past n. Notice, though, that if n == m, we can safely increment both one past their respective limits, and the termination criteria will hit at the same time. The loop below handles any positive input n or m and terminates correctly given your conditons, while allowing the lesser of n or m to become the maximum value for the respective iterator. Worth noting, we compute nadj and madj in the first section to avoid recomputing them during every iteration.
更多推荐
对于同一行中的循环不同的结束条件?
发布评论