Is there a way to compare two arrays?

Hi all,
Is there a way to check if two arrays contain the same data?
I was thinking of something as simple as

If inputArray == [0, 1, 2, 3] Then
    Print("True")
Else
    Print("False")
End

But I’ll understand if that would take a function with a For loop.

I think the only way is to compare is element by element. (use the Size function to determine the size of the arrays, and before parsing, don’t forget that if the arrays to compare have different sizes they are already different different).

Hi @David-san,
Yep, this is how I do it now. The reason I asked is that it needs a separate implementation for Strings, Doubles and MIDI messages etc. So it would be handy if it was an overloaded GPScript function. I’ll file a feature request.

Function compareIntegerArrays(A: Integer Array, B : Integer Array) returns Boolean
// Returns True if both arrays are of the same size and contain the same data
    var i : Integer // index

    If Size(A) != Size(B) Then
        result = False
    Else
        result = True
        For i = 0; i < Size(A); i = i + 1 Do
            If A[i] != B[i] Then
                result = False
            End
        End
    End
End

A quick and dirty hack, without changing your parsing loop, could be to write:

            If A[i] != B[i] Then
                i = A.Size();
                result = False;
            End

As at the first different element found in the array, you can conclude that the arrays are different and save CPU time not parsing the rest of the array.

Actually, it is a very elegant way to implement the missing break statement. Thanks for the tip :wink:

Well, well… hmmmm… hmmmm :innocent:

There is no missing break statement. It was deliberately omitted as was the ability to return from the middle of a function!

Here’s the way to implement that function without the need for a break. Note the extra test in the FOR loop.

Function compareIntegerArrays(A: Integer Array, B : Integer Array) returns Boolean
// Returns True if both arrays are of the same size and contain the same data
    var i : Integer // index

    If Size(A) != Size(B) 
       Then
          result = False
       Else
          result = True
          For i = 0; i < Size(A) And result; i = i + 1 Do
              If A[i] != B[i] Then
                  result = False
              End
          End
    End
End
1 Like

Even more elegant :+1:

I am nitpicking, but it seems to be one more boolean test per iteration (And result)… OK, don’t know if it has an effect on the execution time. :nerd_face:

Meh, if that’s your concern then write the following:

          For i = 0; i < Size(A);  i = i + 1 Do
              If A[i] != B[i] Then
                  i = Size(A)
              End
          End

Me? I’d rather have the readability and I’ll optimize only if it becomes an issue!

:rofl: :joy: :sweat_smile: