I'm trying to understand what this pseudocode does and I can't seem to understand what the comma is suppose to do here.
I know that j <- 1
is j = 1
but what about the i
? And what does j <- j
do in this case?
fib iter(n)
i,j ← 1
for k ← 1 to n−1
i,j ← j,i + j
return j
Best Answer
Assuming this is the algorithm for a Fibonacci number generator, it represents simultaneous/parallel assignment; the comma is not separating two statements, but two operands to the
<-
operator.In
i, j <- 1
, both i and j are set to 1; it's just shorthand fori <- 1
andj <- 1
, which could happen in any order.In
i,j ← j,i + j
, it meansi <- j
and simultaneouslyj <- i+j
. It's necessary for both to happen at once, because you need to use the original values of both variables.In a language without that facility, you'd have to introduce a temporary variable:
or
This may be based on a real language with this syntax, or it may just be a convenience for the algorithms being discussed. For instance, sort algorithms will often be written in a pseudocode with a "swap" operator of some sort, rather than the full set of instructions needed in a particular language, in order to focus on the most relevant details.