How to compare two arrays? - 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: How to compare two arrays? (
/showthread.php?tid=660268)
How to compare two arrays? -
JustNothing - 29.10.2018
For example I have 2 arrays.
array1 = {0, 5, 3};
and
array2 = {5, 0, 3};
How to check that those arrays are same?
Re: How to compare two arrays? -
TheToretto - 29.10.2018
Did you mean:
PHP код:
new MyVAR[3] = {0, 5, 3};
new MyVAR2[3] = {5, 0, 3};
public OnFilterScriptInit()
{
if(MyVAR[2] == MyVAR2[2])
print("yes");
else print("no");
return 1;
}
Re: How to compare two arrays? -
TheToretto - 29.10.2018
Well both of them' values are 3, so yes they are the same, and the order isn't different for the number 3 in my array.
Re: How to compare two arrays? -
TheToretto - 29.10.2018
Oh I thought he wanted to check just for one array. Anyway, is this code optimized, else can it be? It's running and printing good values.
PHP код:
for(new i; i < sizeof(MyVAR); i++)
{
for(i = 0; i < sizeof(MyVAR2); i++)
{
if(MyVAR[i] == MyVAR2[i])
printf("yes %d - %d", MyVAR[i], MyVAR2[i]);
else printf("no %d - %d", MyVAR[i], MyVAR2[i]);
}
}
Re: How to compare two arrays? -
BigETI - 29.10.2018
Why would you do the checks n * n times?
Further more you should check if they are the same size before iterating through them.
pawn Код:
new bool:are_same;
// If they are the same size
if (sizeof arr1 == sizeof arr2)
{
// Assume both arrays are the same
are_same = true;
// Iterate through both arrays
for (new i; i < sizeof arr1; i++)
{
// If both elements are not the same
if (arr1[i] != arr2[i])
{
// Both arrays are not the same
are_same = false;
// No need to check further elements
break;
}
}
}
// "are_same" is "true" if both arrays are the same, otherwise "false"
It takes O(n) time at worst case.
Re: How to compare two arrays? -
JustNothing - 29.10.2018
Quote:
Originally Posted by ******
It depends, would you classify those two in your example as the same, since the values match; or different, since the order doesn't?
|
Same
Re: How to compare two arrays? -
SyS - 29.10.2018
Quote:
Originally Posted by JustNothing
Same
|
1.Check if the arrays have same size
2.Sort them
3.Check if the elements are same one by one.
Putting it in a function would be better. If the step 1 and step3 fails return 0 (at the end of function return 1 )