-2

I am a first year programming trying to solve this challenge that was given to us students at uni.

Question image

Screen Shot

There's a typo at where it says (N + K) whereas in fact it's actually (M+K) columns.

My attempt for this question goes as follows

public static int[][] mergeArrays(int[][] arrayA, int[][] arrayB){
    int rows = 3;
    int columns = arrayA[0].length + arrayB[0].length;      
    int[][] mergedArray = new int[rows][columns];
    int k = 0;
    for (int i = 0; i < rows; i++)
    {
        for ( int j = 0  ; j < columns; j++)
        {
            try
            {
                mergedArray[i][j] = arrayA[i][j];
            }
            catch (ArrayIndexOutOfBoundsException e)
            {
                mergedArray[i][j] = arrayB[i][k];
                k += 1;
            }
        }
    }
    return mergedArray;
}

public static void main(String [] args)
{
    int [][] a1 = { {1,2,3,3,3} , {3,2,1,6,3} , {4,5,6,1,3}  };
    int [][] a2 = { {1,9,7,2,3} , {0,7,8,3,2} , {3,8,9,7,2} };

    int[][] m = mergeArrays(a1,a2);
    for (int[] x : m)
    {
        for (int y : x)
        {
            System.out.print(y + " ");
        }
        System.out.println();
     }
}

The program doesn't work for some reason. I don't know what's wrong with my approach here. Would really appreciate if someone helps me out.

Sham Dhiman
  • 1,348
  • 1
  • 21
  • 59
Eesa
  • 35
  • 6
  • 4
    Define "doesn't work". Does it compile? What is the error? If it compiles, then what is excepted vs actual output? – Amongalen Mar 03 '20 at 11:49
  • @Eesa Consider picking one the available answers below, and accept and upvote it if it solves your problem. This is a common practice in this site, as to thank the answerer for his time and effort. ;) – solid.py Mar 03 '20 at 13:47
  • Sorry i wasn't available, guys consider knowing what time zones are!. By doesn't work i meant I dont know whats wrong in my loop, i'm having a hard time visualizing what's causing my bounds to mess up. – Eesa Mar 04 '20 at 06:08

3 Answers3

1

You are not merging it properly. Your logic is that if arrayA column index is out of bounds, you are adding from arrayB's columns. But what if that is also out of bounds, as in your case. Since you are always incrementing its index k. You could simply iterate over 2 arrays separately and merge into resulting array.

public static int[][] mergeArrays(int[][] arrayA, int[][] arrayB) {
        int rows = 3;
        int columns = arrayA[0].length + arrayB[0].length;
        int[][] mergedArray = new int[rows][columns];
        int k = 0;
        for (int i = 0; i < rows; i++) {
            for (int j = 0; j < arrayA[0].length; j++) {
                mergedArray[i][k++] = arrayA[i][j];
            }
            for (int j = 0; j < arrayB[0].length; j++) {
                mergedArray[i][k++] = arrayB[i][j];
            }
            k=0;
        }
        return mergedArray;
    }
solid.py
  • 2,782
  • 5
  • 23
  • 30
Rahul Agrawal
  • 623
  • 1
  • 5
  • 18
1

Since you're a student I think to better if we give a hint, but since the solution is already there you can check this one as well:

public static int[] merge(int[] first,int[] second) {
    return ArrayUtils.addAll(first, second);
}

public static void main(String[] args) {
    int [][] a1 = { {1,2,3,3,3} , {3,2,1,6,3} , {4,5,6,1,3}};
    int [][] a2 = { {1,9,7,2,3} , {0,7,8,3,2} , {3,8,9,7,2}};
    int [][] a3 = new int[a1.length][];

    for (int i = 0; i < a1.length; i++) {
        a3[i] = merge(a1[i],a2[i]);
    }
    for (int[] ints : a3) {
        StringJoiner joiner = new StringJoiner(",","[","]");
        for (int i1 : ints) {
            joiner.add(i1+"");
        }
        System.out.println(joiner.toString());
    }
}
AMA
  • 408
  • 3
  • 9
1

Without using any libraries, in a manual way, here is my working answer.
I didn't use any of them, since we were not allowed, when I was a student.

public class Main {
    private static int[][] mergeArrays(int[][] a1, int[][] a2) {
        // Count rows and cols length.
        int rows = a1.length;
        int cols_a1 = a1[0].length;
        int cols_a2 = a2[0].length;

        // Total number of cols
        int cols = cols_a2 + cols_a1;

        int [][] merged = new int[rows][cols];


        for (int i = 0; i < rows ; ++i) {
            for (int j = 0; j < cols_a1; ++j) {
                merged[i][j] = a1[i][j];

            }
            // To not overwrite values,
            // the trick is to add an offset, while assigning,
            // which is the amount of elements (cols_a1) used by the previous loop.
            // Basically, we are shifting the k-index by this constant,
            // as to not overwrite the values assigned from the previous 
            // inner loop.
            for (int k = 0; k < cols_a2; ++k) {
                merged[i][cols_a1 + k] = a2[i][k];
            }
        }
        // Return the merged array
        return merged;
    }

    // I refactored your good printing code into a method, for readability.
    private static void print2darray(int[][] array2d) {
        for (int[] x : array2d) {
            for (int y : x) {
                System.out.print(y + " ");
            }
            System.out.println();
        }
    }

    public static void main(String[] args) {
        int [][] a1 = {{1,2,3,3,3} , {3,2,1,6,3} , {4,5,6,1,3}};
        int [][] a2 = {{1,9,7,2,3} , {0,7,8,3,2} , {3,8,9,7,2}};
        int [][] merged = mergeArrays(a1, a2);
        print2darray(merged);
    }
}

The result is the same, as expected, from your question image:

1 2 3 3 3 1 9 7 2 3
3 2 1 6 3 0 7 8 3 2 
4 5 6 1 3 3 8 9 7 2 
solid.py
  • 2,782
  • 5
  • 23
  • 30
  • Thank you so much hitter! Could you explain what ++i does, its the first time i'm seeing such an operator. Sorry couldn't reply in time (time zones....) – Eesa Mar 04 '20 at 06:11
  • 1
    @Eesa Don't worry, I thought as well you might lived in a different timezone. Ok so there is this really excellent tutorial about for loops in Java by the company who owns it. https://docs.oracle.com/javase/tutorial/java/nutsandbolts/for.html – solid.py Mar 04 '20 at 09:46
  • 1
    @Eesa Also check this short answer for the differences of `++i` and `i++` https://stackoverflow.com/questions/2371118/how-do-the-post-increment-i-and-pre-increment-i-operators-work-in-java – solid.py Mar 04 '20 at 09:48
  • 1
    Personally, when I need to for loop with an index variable, I always use the pre-increment operator, because when I started programming with C as my first language, it was supposed to be slightly faster. That's not the case for Java though as explained here https://stackoverflow.com/questions/4831748/is-i-really-faster-than-i-in-for-loops-in-java – solid.py Mar 04 '20 at 09:52