I came across a pseudocode which I am unable to implement because, I am unable to understand it:
i, c := 0,0;
do i ≠ n →
if v = b[i] → c, i := c + 2, i + 1
c = i → c, i, v := c + 2, i + 1, b[i]
c ≠ i ^ v ≠ b[i] → i := i + 1
fi
od
I think that tis pseudocode is about finding the value v which has occurred more than n / 2 times in b[].
The three conditions in the if
are alternatives, they should be translated to an if-else if-else
chain.
The assignment-like statements c,i,v := c+2, i+1, b[i]
are multiple assignments, as far as I know like the Python multiple assignments, so the i
in b[i]
refers to the old value of i
. That yields
// n and v are initialised to something sensible, hopefully
i = 0;
c = 0;
while(i != n) {
if (b[i] == v) {
c = c + 2;
i = i + 1;
} else if (c == i) {
c = c + 2;
v = b[i]; // conjecture that the b[i] on the RHS refers to the old i
i = i + 1;
} else {
i = i + 1;
}
}
Since i
is incremented in every branch, we can lift that out, and get
for(i = 0, c = 0; i != n; ++i) {
if (b[i] == v) {
c += 2;
} else if (c == i) {
c += 2;
v = b[i];
}
}