3

I am a bit confused and I would need some clarification. Not too sure if I'm on the right track, hence this thread.

Here is my code that I want to decipher into advanced foreach loop.

    int[] arrayA = {3, 35, 2, 1, 45, 92, 83, 114};
    int[] arrayB = {4, 83, 5, 9, 114, 3, 7, 1};
    int n = arrayA.length;
    int m = arrayB.length;
    int[] arrayC = new int[n + m];
    int k = 0;

    for(int i = 0; i < n; i++)
    {
        for(int j = 0; j < m; j++)
        {
            if(arrayB[j] == arrayA[i])
            {
                arrayC[k++] = arrayA[i];
            }
        }
    }
    for(int i=0; i<l;i++)
        System.out.print(arrayC[i] + " ");
    System.out.println();

So far this is the point where I am stuck at:

    int[] a = {3, 8, 2, 4, 5, 1, 6};
    int[] b = {4, 7, 9, 8, 2};
    int[] c = new int[a.length + b.length];
    int k = 0;
    for(int i : a)
    {
        for(int j : b)
        {
            if(a[i] == b[j]) 
            {
                c[k++] = a[i];
            }
        }
        //System.out.println(c[i]);
    }
    for(int i=0; i<c.length;i++)
        System.out.print(c[i] + " ");
    System.out.println();
}
1
  • The value of i and j will get reset at each iteration. And in order to use array[index] form, you cannot use the temporary variables in foreach loop for direct indexing Commented Mar 31, 2018 at 14:10

3 Answers 3

3

You are almost there

for(int i : a)
{
    for(int j : b)
    {
        if(i == j) 
        {
            c[k++] = i;
        }
    }
}

With for(int i : a) access the elements in the array a using i. If a is {3, 8, 2, 4, 5, 1, 6}, then i would be 3,8,2,.. on each iteration and you shouldn't use that to index into the original array. If you do, you would get either a wrong number or a ArrayIndexOutOfBoundsException


Since you want to pick the numbers that are present in both the arrays, the length of array c can be max(a.length, b.length). So, int[] c = new int[Math.max(a.length, b.length)]; will suffice.

If you want to truncate the 0s at the end, you can do

c = Arrays.copyOf(c, k);

This will return a new array containing only the first k elements of c.

Sign up to request clarification or add additional context in comments.

6 Comments

That look reasonable.
I ran the program with the above, and surprisingly it iterated through the entirety of array 'c', result is 3 common numbers plus the rest of the reserved slots within the array, please see here: 8 2 4 0 0 0 0 0 0 0 0 0
Yes, because you precreated the c array. (It has nothing to do with enhanced for loops)
Since arrays need predefined length, the best you can do is to take the max of a and b length. You can read about ArrayList if you need arrays whose size is adjustable (there are lots of other options)
Wicked help there, Sir! Much appreciated
|
1

I would use a List and retainAll. And in Java 8+ you can make an int[] into a List<Integer> with something like,

int[] arrayA = { 3, 35, 2, 1, 45, 92, 83, 114 };
int[] arrayB = { 4, 83, 5, 9, 114, 3, 7, 1 };
List<Integer> al = Arrays.stream(arrayA).boxed().collect(Collectors.toList());
al.retainAll(Arrays.stream(arrayB).boxed().collect(Collectors.toList()));
System.out.println(al.stream().map(String::valueOf).collect(Collectors.joining(" ")));

Outputs

3 1 83 114

Alternatively, if you don't actually need the values besides displaying them, and you want to use the for-each loop (and less efficiently) like

int[] arrayA = { 3, 35, 2, 1, 45, 92, 83, 114 };
int[] arrayB = { 4, 83, 5, 9, 114, 3, 7, 1 };
for (int i : arrayA) {
    for (int j : arrayB) {
        if (i == j) {
            System.out.print(i + " ");
        }
    }
}
System.out.println();

3 Comments

Elliott, your comment surely amazed me, though the level of my current knowledge is insufficient to understand it fully. Thanks for the efforts :)
Just out of curiosity, the first solution you suggested doesn't compile, it runs into an error : List is not generic, it cannot be parameterized with <Integer> , am I missing something?
Requires Java 8+ and that is java.util.List
0

Temporary variables aren't indices in an array in foreach Loop. So in 0th iteration, i contains the 0th element of a, j contains the 0th element in b. Your attempt should be like this:

int[] a = {3, 8, 2, 4, 5, 1, 6}; 
int[] b = {4, 7, 9, 8, 2}; 
int[] c = new int[a.length + b.length]; 
int k = 0; 
for(int i : a) { 
   for(int j : b) { 
       if(i == j) { 
           c[k++] = i; 
       } 
   } //System.out.println(c[i]);
}

Please note your c[] array will contain the order maintained in a[].

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.