Implementing Loops from Pseudocode - algorithm

I was wondering if anyone could suggest to me how to implement this loop in the following pseudocode:
8: loop
9: while f[0] = 0 do
10: for i = 1 to N do
11: f[i ¡ 1] = f[i]
12: c[N + 1 - i] = c[N - i]
13: end for
14: f[N] = 0
15: c[0] = 0
16: k = k + 1
17: end while
18: if deg(f) = 0 then
19: goto Step 32
20: end if
......... ...... ....
31: end loop
My question is how I should implement the loop that starts on line 8 and ends on 31; I am comfortable with the statements between lines 8 to 31, but what kind of loop do I use on line 8, and what conditions do I give for the loop?
Thanks in advance.

That's an infinite loop. No conditions, just loop forever. The only way out is to get to step 19. In C-like languages you can write that as while (true) or for (;;):
for (;;) {
// ...
if (deg(f) == 0) {
goto afterLoop;
}
// ...
}
afterLoop:
// ...
goto is frowned upon, though. It'd be better to replace goto Step 32 with a break statement, which exits a loop immediately:
for (;;) {
// ...
if (deg(f) == 0) {
break;
}
// ...
}
For what it's worth, if you didn't have steps 21-30 you could use a do/while loop, where the loop condition goes at the bottom of the loop instead of the top:
do {
// ...
}
while (deg(f) != 0);
That would work if lines 18-20 were the final lines in the loop. Since they're not, it looks like option #2 is the one to go with.

If you are going to write pseudocode in such detail, you might as well write in the target language. Pseudocode should be a much broader brush - something like this (not related to your code):
for each bank account
check balance as of last month
if balance greater than promotion limit
send out valued customer pack
endif
endfor

Related

Is my understanding on this piece of correct?I am getting an output 12 for the below code which is stated as wrong

The piece of code returns the value "P". Initialized with something blank,I want to understand what does this code produce. I am getting an output as 12 which is not true. asciiValueof('A') this is as taken as 065 .
p= ""
code = 15
while(code>0)
{
if (code % 2 == 0)
{
p=p+toString(code)
code-= 1
}
else
{
code-= 3 * (asciiValueof('A') - 64)
}
}
\i want to print p\
print(p)
It should produce "1284" from the program flow.
About how.
This is what you have as code and p after each iteration
// code =15, p=""
// code =12, p="", substracting 3 from code adding nothing to p
// code = 11, p ="12" add code to p, subtracting 1 from code
// code = 8, p="12" substracting 3 from code adding nothing to p
// code =7 p = "128" add code to p, subtracting 1 from code
// code =4 p ="128" substracting 3 from code adding nothing to p
// code = 1 p = "1284" add code to p, subtracting 1 from code
// code =0, p = "1284" terminate from loop as code is not > 0

How can I adjust my program to close the loop and print the expected results?

This is the error I'm getting. I believe this means its caught in an infinite loop:
Line: 2, Column: 1
System.LimitException: Apex CPU time limit exceeded
The code below is what I've tried so far.
for(integer i = 7; i <= 15; i + 2){
System.debug(i);
}
I expect it to print the following:
7
9
11
13
15
Instead it is getting stuck in an infinite loop.
Your diagnosis is correct; your code is caught in an infinite loop.
This is the case because of the third clause of your for loop:
for(integer i = 7; i <= 15; i + 2){
i + 2 is an expression, but it doesn't change the value of i. You want to do i += 2 here. See Apex Operators for the details.

Why are loops executed one more time than the loop body?

A quote from an Algorithms textbook:
"When a for or while loop exits in the usual way (i.e., due to the test in the loop header), the test is executed one time more than the loop body."
So, for example, a for loop that begins with for j=1 to 3 will be executed not 3 times, but 4 times!
Question: Why would such a loop be executed 4 times and not 3 times?
By my reasoning:
When j = 1, the loop is executed.
When j = 2, the loop is executed.
When j = 3, the loop is executed.
When j = 4, the loop is NOT executed.
I count 3, not 4.
I think you are confused about what the statement in the book states
When a for or while loop exits in the usual way (i.e., due to the test in the loop header), the test is executed one time more than the loop body.
This means that the loop condition will be tested one more time than the loop body therefore by your example:
for j = 1:3
j = 1, pass and looped
j = 2, pass and looped
j = 3, pass and looped
j = 4, failed and code executes as written
Here's the pseudo machine code for a for...loop
// int result = 0;
// for(int x = 0; x < 10; x++) {
// result += x;
// }
MOV edx, 0 // result = 0
MOV eax, 0 // x = 0
.ForLoopLabel:
CMP eax, 10 // FillFlags(x - 10)
JGE .ForLoopFinishedLabel // IF x >= 10 THEN GoTo ForLoopFinishedLabel
// for loop's body
ADD edx, eax // result += x
// end of body
ADD eax, 1 // x++
JMP .ForLoopLabel // GoTo ForLoopLabel
.ForLoopFinishedLabel:

'While' loop counting up

I am practicing ruby. In one of the exercises, it asks me to try and use a 'while' loop to print the numbers 1 to 50 inclusively. (counting up)
I also have a code that counts down.
i = 50
while i > 0 do
print i
i -= 1
end
anyway you could make the code above counting up?
Thanks
Try Below Simple Ruby Magics :)
(1..50).each { |n| puts n }
50.times { |n| puts n }
1.upto(50) { |n| print n }
Here counting up is being automatically inside ruby library, so dont worry about it
try
$i = 1
$num = 51
while $i < $num do
print("#$i" )
$i +=1
end
that would help..
and go to this for more help
http://www.tutorialspoint.com/ruby/ruby_loops.htm
Just to help you understand what you typed :
when you type: i -= 1, it is the same as typing: i = i - 1
when you type : i += 1, it is the same as typing : i = i + 1
You should then easily understand why, when you want to decrement your variable i, you start by initializing i at 50 (before the while loop starts).
And when you want to increment your variable i, you start by initializing i at 1 or 0.
Your are counting backwards, from i = 50 to 1. You must go from i = 1 to 50, increasing i += 1 on each loop.
Change it to this:
i = 1
while i <= 50 do
print i
i += 1
end
And a bit simplified:
(1..50).each { |number| puts number }

Which condition is technically more efficient, i >= 0 or i > -1?

This kind of usage is common while writing loops.
I was wondering if i >=0 will need more CPU cycles as it has two conditions greater than OR equal to when compared to i > -1. Is one known to be better than the other, and if so, why?
This is not correct. The JIT will implement both tests as a single machine language instruction.
And the number of CPU clock cycles is not determined by the number of comparisons to zero or -1, because the CPU should do one comparison and set flags to indicate whether the result of the comparison is <, > or =.
It's possible that one of those instructions will be more efficient on certain processors, but this kind of micro-optimization is almost always not worth doing. (It's also possible that the JIT - or javac - will actually generate the same instructions for both tests.)
On the contrary, comparsions (including non-strict) with zero takes one CPU instruction less. x86 architecture supports conditional jumps after any arithmetic or loading operation. It is reflected in Java bytecode instruction set, there is a group of instructions to compare the value on the top of the stack and jump: ifeq/ifgt/ifge/iflt/ifle/ifne. (See the full list). Comparsion with -1 requires additional iconst_m1 operation (loading -1 constant onto the stack).
The are two loops with different comparsions:
#GenerateMicroBenchmark
public int loopZeroCond() {
int s = 0;
for (int i = 1000; i >= 0; i--) {
s += i;
}
return s;
}
#GenerateMicroBenchmark
public int loopM1Cond() {
int s = 0;
for (int i = 1000; i > -1; i--) {
s += i;
}
return s;
}
The second version is one byte longer:
public int loopZeroCond();
Code:
0: iconst_0
1: istore_1
2: sipush 1000
5: istore_2
6: iload_2
7: iflt 20 //
10: iload_1
11: iload_2
12: iadd
13: istore_1
14: iinc 2, -1
17: goto 6
20: iload_1
21: ireturn
public int loopM1Cond();
Code:
0: iconst_0
1: istore_1
2: sipush 1000
5: istore_2
6: iload_2
7: iconst_m1 //
8: if_icmple 21 //
11: iload_1
12: iload_2
13: iadd
14: istore_1
15: iinc 2, -1
18: goto 6
21: iload_1
22: ireturn
It is slightly more performant on my machine (to my surprise. I expected JIT to compile these loops into identical assembly.)
Benchmark Mode Thr Mean Mean error Units
t.LoopCond.loopM1Cond avgt 1 0,319 0,004 usec/op
t.LoopCond.loopZeroCond avgt 1 0,302 0,004 usec/op
Сonclusion
Compare with zero whenever sensible.

Resources