nested

Nested loops can look a little challenging at first, but it is really easier than it may look.

Before we get started on the loops, we want to measure the length of the array $myAlphaNum and save this to $len (line 23 of the graphic below).  While we are still on the topic of arrays, remember that the first entry in an array is at index 0, we will come back to this.

Next, keeping in mind that we wanted a 5 character code, each place of the code was broken down into the following variables:   $p5 $p4 $p3 $p2 $p1.

If we wanted to step through AAAAA - AAAA9, we could simply do the following:

                                For ($i1=1; $i1 -lt $len; $i1++)
                                    {
                                        $p1 = $myAlphaNum[$i1-1]
                                    }
Each time through the loop, the value of $i1 advanced by 1.  Once the loop gets to the number of characters in our array (this is why we measured the array earlier and saved it to $len) the loop stops.  Again, Powershell arrays are zero indexed.  So, the first item in the array is at position 0.  Since we are attempting to ready $myAlphaNum each time we are in the loop, we subtract 1 from $i1 to account for the zero index.


Once we get to AAAA9, we want to advance to AAABA.  This is where nesting come into play.  By placing a loop within a loop, we return to the earlier loop each time the for loop reaches the end.

                       For ($i2=1; $i2 -lt $len; $i2++)
                            {
                                $p2 = $myAlphaNum[$i2-1]
                                For ($i1=1; $i1 -lt $len; $i1++)
                                    {
                                        $p1 = $myAlphaNum[$i1-1]
                                                    $thisTag = $p5+$p4+$p3+$p2+$p1+"`n"
                                                    $tags = $tags + $thisTag
                                    }
                            }

In our case, we called a unique code a tag.  Each time we create a new tag, we append it to the list of $tags.  By creating a series of nested loops for each place in the code, we can loop through all 5 positions and go from AAAAA - 99999.

No comments:

Post a Comment