tags:

views:

288

answers:

4
 for m := 0 to 300 do
       if Pos(certain_String, string(arrayitem(m)) <> 0 then
        begin
          randomize;
          x := random(100);
        begin
            case x of
             0..69  : function(m); //  70 percent
            70..79 : function(m+1); // 10 percent
            80..84 : function(m+2); // 5 percent
            85..88 : function(m+3); //  5 percent
            89..91 : function(m+4); //  2 percent
            92..94 : function(m+5); //  3 percent
            95..97 : function(m+6); //  3 percent
            98..98 : function(m+7); //  1 percent
            99..99 : function(m+8); //  1 percent


           end;
           m := 300;

    end;

Trying to make this thing loop through a rather large array, but if it finds a certain string in it stop entirely and go to the next thing, had to take out some proprietary function names but m := 300; seems to be the problem, doesn't like me assigning m a value in the middle of a for loop. Sorry for the lack of knowledge here, got a halfdone pascal project dropped on my lap and have never even seen the stuff before.

A: 

There must be an equivalent to C's break in Object Pascal. That's a cleaner way to get out of the loop.

Eduardo León
break ends a loop, continue goes to the next cycle of the loop, exit leaves the function or method.
Gamecat
+3  A: 

Changed the code a bit:

randomize;
for m := 0 to 300 do begin
  if Pos(certain_String, string(arrayitem(m)) <> 0 then begin
    x := random(100);
    case x of
       0..69 : function(m); //  70 percent
      70..79 : function(m+1); // 10 percent
      80..84 : function(m+2); // 5 percent
      85..88 : function(m+3); //  5 percent
      89..91 : function(m+4); //  2 percent
      92..94 : function(m+5); //  3 percent
      95..97 : function(m+6); //  3 percent
          98 : function(m+7); //  1 percent
          99 : function(m+8); //  1 percent
    end;
    break;
  end;
end;

Will do the trick.

Randomize should not be called each loop.

And why the string cast?

Gamecat
I assume you know that function is a reserved word that can not be used as a function identifier.
Gamecat
"does not need to be called each" -> "should not be called each"
Craig Stuntz
Thanks (I'm not a native english speaker).
Gamecat
Your English is fine; just pointing out that your suggestion is actually a *requirement.*
Craig Stuntz
A: 

Example with while loop:

m := 0;

while m<=300 do begin
  if condition do begin
    // Do something

    m := 300; // Will be 301 at end of loop.
  end;
  Inc(m);
end;
Gamecat
+3  A: 

Besides the other issues, the way to end a for loop is Break. Just replace the m := 300; with Break; and it will do what you want.

Additionally calling randomize more then once is a bad idea, but you know that now since it was mentioned in the answer you accepted yesterday for this issue.

Jim McKeeth