Home > Enterprise >  Replace multiple If statements with For statement
Replace multiple If statements with For statement

Time:11-06

My script to find where a value in Array $c[] is in Array $a[] works, but nested If statements are too long. Can this be shortened using a For statement using a variable for array $c[] with the following rules?

#include <Array.au3>
#include <MsgBoxConstants.au3>

Local $a[]=[33,5,3,4,4,'a4',2,22,66,234,'a4',234,31,34,55,'a4',22,44,55,66]
Local $c[]=['a4',22,44,55,66]

For $b=0 To 19

    If $c[0] == $a[$b] Then

        If $c[1] == $a[$b 1] Then

            If $c[2] == $a[$b 2] Then

                $k=$b

            EndIf

        EndIf

    EndIf

Next
#include <Array.au3>
#include <MsgBoxConstants.au3>

Local $a[]=[33,5,3,4,4,'a4',2,22,66,234,'a4',234,31,34,55,'a4',22,44,55,66]
Local $c[]=['a4',22,44,55,66]
Local $k[]

$e=0
For $b=0 To 19

    If $c[$e] == $a[$b] Then

        $k[$e]=$b
        $e =1

    EndIf

Next
_ArrayDisplay($k,"dispay")
MsgBox($MB_SYSTEMMODAL, "", $k &"th value" )

I tried one nested If statement using the For statement, but it doesn't work.

CodePudding user response:

Here is another approach:

#include <Array.au3>

Local $aA[]=[33,5,3,4,4,'a4',2,22,66,234,'a4',234,31,34,55,'a4',22,44,55,66]
Local $aC[]=['a4',22,44,55,66]

Local $aIndex=_ArrayFindAll($aA,$aC[0],0,ubound($aA)-ubound($aC)) ; positions where the first element of $aC is found. Reduces number of comparisons
for $i in $aIndex ; for each of those positions
    $aSubA=_ArrayExtract($aA,$i,$i UBound($aC)-1) ; extract a subarray of $aA with the same lenght as $aC
    if _ArrayToString($aSubA) = _ArrayToString($aC) then ConsoleWrite("found C in A on position "&$i & @CRLF) ; if can't compare arrays, but strings only
Next

CodePudding user response:

"Can this be shortened using a For statement using a variable for array $c[] …"

Yes :

Global Const $g_bGetAll = False
Global Const $g_aArrayA = [33, 5, 3, 4, 4, 'a4', 2, 22, 66, 234, 'a4', 234, 31, 34, 55, 'a4', 22, 44, 55, 66],  _
             $g_aArrayC = ['a4', 22, 44, 55, 66]

For $i1 = 0 To (UBound($g_aArrayA) - 1) - (UBound($g_aArrayC) - 1)

    For $i2 = 0 To UBound($g_aArrayC) - 1

        If Not ($g_aArrayC[$i2] == $g_aArrayA[$i1   $i2]) Then _
        ContinueLoop 2

    Next

    ConsoleWrite(StringFormat('$g_aArrayC matches $g_aArrayA[%i] to $g_aArrayA[%i]\n', $i1, $i1   UBound($g_aArrayC) - 1))

    If Not $g_bGetAll Then _
    ExitLoop

Next

Returns:

$g_aArrayC matches $g_aArrayA[15] to $g_aArrayA[19]

Returns all (multiple) matches if $g_bGetAll = True.

  • Related