SA-MP Forums Archive
Playing with loops : one - Printable Version

+- SA-MP Forums Archive (https://sampforum.blast.hk)
+-- Forum: SA-MP Scripting and Plugins (https://sampforum.blast.hk/forumdisplay.php?fid=8)
+--- Forum: Scripting Help (https://sampforum.blast.hk/forumdisplay.php?fid=12)
+--- Thread: Playing with loops : one (/showthread.php?tid=352444)



Playing with loops : one - milanosie - 19.06.2012

A question like this was on my ICT exams,

Quote:

In a loop like shown above, what would p be at the end?

So I was being bored at home and made something real quick.


pawn Код:
CMD:loop(playerid, params[])
{
new p;
new a;
new piet;
if(sscanf(params, "ii", p,a)) return SCM(playerid, COLOR_GREY, "USAGE: /loop [1-50] [1-15]");
if(a < 0 || a > 15) return SCM(playerid, COLOR_GREY, "USAGE: /loop [1-50] [1-15]");
if(p < 0 || p > 50) return SCM(playerid, COLOR_GREY, "USAGE: /loop [1-50] [1-15]");
piet = p;
for(new i = 0; i <= a; i++)
{
   p = p + i;
}
new string[128];
format(string, sizeof(string), "[DEBUG] Using Starting number %d and loop size %d the result would be %d", piet, a, p);
print(string);
printf("[DEBUG] Set P %d,Set A %d ||==||==|| P = P + A gives P = %d while loop = A", piet, a, p);
SCM(playerid, COLOR_WHITE, string);
return 1;
}


Example:

/loop 2 5 would give:

2 + 0 = 2
2 + 1 = 3
3 + 2 = 5
5 + 3 = 8
8 + 4 = 12
12 + 5 = 17


P would be 17 at the end of this loop.




that's basically what I do when I'm bored


Re: Playing with loops : one - TheLazySloth - 20.06.2012

Neat, but what's the use?


Re: Playing with loops : one - milanosie - 20.06.2012

Quote:

Neat, but what's the use?

Its to understand more how maths/C++/pawn works, and it's just fun to figure out new stuff ^.^, atleast thats what I think.


Quote:
Originally Posted by ******
Посмотреть сообщение
They're called triangular numbers and there's a much simpler way to do it:

pawn Код:
p = (a * a + a) / 2;
Or:

pawn Код:
p = a * (a + 1) / 2;
This is referred to as "algorithmic complexity" - a loop takes "N" time to get the answer because it has to repeat some arbitrary code many times. A formula takes "1" time because it only has to do one thing. Look up "Big-O" (big-oh) notation.
But if I used a starting number for p, like I did in my example, I would need to edit that formula right?
As in something like this:


pawn Код:
p = (a * a + p) / 2;
Or maybe not the above one, but I can't figure out the right formula atm, as the one you gave me wouldn't work for starting numbers, or am I being an idiot now? (I just woke up ^.^)


Re: Playing with loops : one - milanosie - 20.06.2012

Quote:
Originally Posted by ******
Посмотреть сообщение
Then you would just change "p = " to "p += " in my code. The majority of the calculation is still the same.
Ow right, I wasn't paying attention there as I woke up exactly 5 minutes ago.
Will give it a shot to see if the results are the same