dmitrivada
dmitrivada

Reputation: 51

Looping over parallel arrays that are different lengths

I am a begginer and this is my first question. I've scoured the net for answers and I am coming up short. Any help any of you can provide will put a smile on my face!!

I am writing a program that loops over two arrays simultaneously. These are char arrays cast from user defined strings so they will likely be different lengths. Below is how things are currently set up in my code.

for(int i = 0; i < charArray1.length; i++)
    {   
        char keyChar = charArray1[i];
        char messageChar = charArray2[i];
    }

Considering the example above. lets say that:

charArray1 = {'A','B','C','D'} and
charArray2 = {'1','2','3','4','5','6','7}

Currently this scenario tosses me an out of bounds exception, as it should. What I'd like to see happen is for a loop to return to the start of charArray1 while another loop continues to the end of charArray2.

If I were to print this it might look something like below.

A1, B2, C3, D4, A5, B6, C7

Any help would be greatly appreciated. I've been at this for a while now.

Upvotes: 5

Views: 3842

Answers (5)

khelwood
khelwood

Reputation: 59166

The number of iterations you want from your loop is the length of the longest array. You can get that with Math.max(charArray1.length, charArray2.length);

Then you want to get the array item at index i, but cycling around when it passes the array's length. You can get that with arr[i%arr.length].

In combination:

int m = Math.max(charArray1.length, charArray2.length);
for (int i = 0; i < m; ++i) {
    char keyChar = charArray1[i%charArray1.length];
    char messageChar charArray2[i%charArray2.length];
}

Edit:

The modulo operator (a%b) gives you the amount left over after dividing a by b.

For instance, with b=3:

a   a%3
0    0
1    1
2    2
3    0
4    1
5    2
...

You can see that if a and b are integers with a>=0 and b>0, then a%b will always be in the range:

0 <= a%b < b

which is the range of acceptable indexes for an array of length b.

Upvotes: 6

jgr208
jgr208

Reputation: 3066

What you need to do is make a for loop inside a for loop

for(int i = 0; i < charArray2.length; i++)
    {   
        for(int j = 0; j < charArray1.length; j++)
            char keyChar = charArray1[j];
        char messageChar = charArray2[i];
    }

This loops over the inside loop and once it reached the end loops over again until the end of charArray2 is reached at which point the outter for loop will terminate thus exiting the loop. There are other ways to do this but this is one ways that makes it easier for a beginner like you to understand.

Then if you want it to print out A1,B2,... exactly without two for loops you can do the following. Two for loops not be the best way to go if you are dealing with a large set of numbers since two for loops are n^2 while an if statement is just a constant like 1 i think.

int max = Math.max(charArray1.length, charArray2.length);
int j = 0;
for (int i = 0; i < max; ++i) {
    if(j==charArray1.length)
      j = 0;
    else
      j++;
    char keyChar = charArray1[j];
    char messageChar charArray2[i];
}

Upvotes: 0

ajb
ajb

Reputation: 31699

There's no rule that says the index of a for loop has to be an index into any array. Here's an approach that uses a counter and two separate array indexes:

int totalCount = Math.max(charArray1.length, charArray2.length);
int i = 0;
int j = 0;
for (int count = 0; count < totalCount; count++) {
     char keyChar = charArray1[i++];
     if (i >= charArray1.length) {
         i = 0;
     }
     char messageChar = charArray2[j++];
     if (j >= charArray2.length) {
         j = 0;
     }
     // code that outputs the two characters, or whatever
}

This will work regardless of which array is longer, and it doesn't rely on %.

Upvotes: 0

WoDoSc
WoDoSc

Reputation: 2618

You want to loop until the end of the longest array, so you pick the max of the two lengths as your loop's exit condition.

Then, you can loop the two arrays at the same time by using the modulo for the indexes, in such a way you can not throw an index out of bounds exception: when i becomes grater then the bounds of an array, with the modulo (%) operator you restart from the beginning of that array.

for (int i = 0; i < Math.max(charArray1.length,charArray2.length); i++) {
   char keyChar = charArray1[i%charArray1.length];
   char messageChar = charArray2[i%charArray2.length];
}

This will work independently of which array will be the larger.

Upvotes: 0

Have a second variable j to keep track of the indexing for the smaller array.

//charArray1 = {'A','B','C','D'}
//charArray2 = {'1','2','3','4','5','6','7}

int j = 0;
for(int i = 0; i < charArray2.length; i++)
{   
    char keyChar = charArray1[j];

    j++;
    if(j == charArray1.length)
        j=0;

    char messageChar = charArray2[i];
}

Here's a test run

This assumes charArray2 will always be the longest array. If you expect this to be untrue, just do a check prior entering loop

You can also do fancy stuff with the % operator, but I prefer this approach because it's more readable for newcomers.

Upvotes: 0

Related Questions