How to compare two arrays?
#1

For example I have 2 arrays.

array1 = {0, 5, 3};
and
array2 = {5, 0, 3};

How to check that those arrays are same?
Reply
#2

Did you mean:

PHP код:
new MyVAR[3] = {053};
new 
MyVAR2[3] = {503};


public 
OnFilterScriptInit()
{
    if(
MyVAR[2] == MyVAR2[2])
        print(
"yes");
    else print(
"no");
    return 
1;

Reply
#3

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.
Reply
#4

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 isizeof(MyVAR); i++)
    {
        for(
0sizeof(MyVAR2); i++)
        {
            if(
MyVAR[i] == MyVAR2[i])
                 
printf("yes %d - %d"MyVAR[i], MyVAR2[i]);
            else 
printf("no %d - %d"MyVAR[i], MyVAR2[i]);
        }
    } 
Reply
#5

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.
Reply
#6

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
Reply
#7

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 )
Reply


Forum Jump:


Users browsing this thread: 1 Guest(s)