2
$\begingroup$

for every j != i in {0,....,n-1}

How to interpret this for loop? I never seen this type of definition of for loop.

Is it like - j=0 to n-1; j !=i ; ++j

$\endgroup$
  • 1
    $\begingroup$ It's pseudocode, isn't it? I suppose just take it literally then? $\endgroup$ – xuq01 Jul 30 '18 at 3:52
  • 1
    $\begingroup$ If i is not defined before the meaning is clearly $for\;(i,j)\;\in\{(a,b) \mid a \in \{0..n-1\} \land b \in \{0,..n-1\} \land a\neq b\}$. $\endgroup$ – Giacomo Alzetta Jul 30 '18 at 12:48
18
$\begingroup$

Here is the probable interpretation:

for every $j \neq i$ in $\{0,\ldots,n-1\}$:

  code

should be interpreted as:

for every $j$ in $\{0,\ldots,n-1\}$:

  if $j \neq i$:

    code

This is similar to the way this kind of statement is interpreted in mathematical text.

It is also possible that the roles of $i$ and $j$ should be switched — this should be clear from context, and it's an ambiguity that also exists in mathematical texts.

As mentioned in Evil's answer, if neither $i$ nor $j$ has been defined, then the interpretation is probably

for every $i,j$ in $\{0,\ldots,n-1\}$:

  if $i \neq j$:

    code

$\endgroup$
  • $\begingroup$ Upvoted, but note that "for every i, j in {0,…,n−1}" isn't 100% formal either. I think Evil's formulation of that possibility (as two nested loops) is clearer. $\endgroup$ – Quuxplusone Jul 31 '18 at 7:00
  • $\begingroup$ Evil's interpretation is a guess - perhaps the loops should be switched? $\endgroup$ – Yuval Filmus Jul 31 '18 at 7:02
  • $\begingroup$ Swapping the order of the inner i and outer j loops has no effect on the semantics of the program. (However, one or the other ordering may well take more advantage of cache effects if we're going to use the loop indices as indices into a 2D array. See Row-major and column-major order.) $\endgroup$ – Quuxplusone Jul 31 '18 at 16:41
13
$\begingroup$

There is another interpretation, both $i, j$ might be variables, in that case it is double loop:

for every $j$ in $\{0,\ldots,n-1\}$:

  for every $i$ in $\{0,\ldots,n-1\}$:

    if $j \neq i$:

      code

Simply reading it out loud helps only if we know beforehand if $i$ is fixed variable or another counter, so there is context missing.

$\endgroup$
  • 1
    $\begingroup$ An analogous mathematical notation would be $$\sum_{i,j=0\\i\neq j}^{n-1}$$ $\endgroup$ – ComFreek Jul 31 '18 at 9:05
6
$\begingroup$

Just read it out loud. "For every $j$ that is not equal to $i$, in $\{0, \dots, n-1\}$."

In my opinion, it would be better to have written "For every $j\in\{0, \dots, n-1\}\setminus\{i\}$."

$\endgroup$
  • 1
    $\begingroup$ My guess is that $i$ is a counter, too. $\endgroup$ – Andrej Bauer Jul 30 '18 at 13:13

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.