I am a first year programming trying to solve this challenge that was given to us students at uni.
Question image
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.
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
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());
}
}
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;
}
I have this line of code to create a zigzag array, its fairly simple and I already have the code for it. here's the summary of the question:
This method creates and returns a new two-dimensional integer array, which in Java is really just a one-dimensional array whose elements are one-dimensional arrays of type int[]. The returned array must have the correct number of rows that each have exactly cols columns. This array must contain the numbers start, start + 1, ..., start + (rows * cols - 1) in its rows in order, except that the elements in each odd-numbered row must be listed in descending order.
For example, when called with rows = 4, cols = 5 and start = 4, this method should create and return the two-dimensional array whose contents are
4 5 6 7 8
13 12 11 10 9
14 15 16 17 18
23 22 21 20 19
I've tried talking with my colleagues but they can't spot the problem too
public class P2J1
{
public static int[][] createZigZag(final int rows, final int cols, int start)
{
final int[][] array = new int[rows][cols];
for (int i = 0; i < rows; i++)
{
for (int j = 0; j < cols; j++)
{
array[i][j] = start;
start++;
}
}
return array;
}
}
/// heres the tester program
#Test public void testCreateZigZag() {
Random rng = new Random(SEED);
CRC32 check = new CRC32();
for(int i = 0; i < TRIALS; i++) {
int rows = rng.nextInt(20) + 1;
int cols = rng.nextInt(20) + 1;
int start = rng.nextInt(100);
int[][] zig = P2J1.createZigZag(rows, cols, start);
assertEquals(rows, zig.length);
for(int j = 0; j < rows; j++) {
assertEquals(cols, zig[j].length);
for(int e: zig[j]) { check.update(e); }
}
}
assertEquals(3465650385L, check.getValue());
}
Your column index always goes from 0 to cols-1, in that order. You need to alternate the order every other row.
You can do this by using variables for the start, end, and increment of the inner loop and assign those variables based on the row index being odd or even.
Something like this (untested):
public static int[][] createZigZag(final int rows, final int cols, int start) {
final int[][] array = new int[rows][cols];
for (int i = 0; i < rows; i++) {
boolean backwards = ((i & 1) == 1);
final int jStart = backwards ? cols-1 : -1;
final int jEnd = backwards ? 0 : cols;
final int jStep = backwards ? -1 : 1;
for (int j = jStart; j != jEnd; j += jStep) {
array[i][j] = start;
start++;
}
}
return array;
}
You could also just write two different inner loops, selected on the same condition. One would fill starting from 0, the other would fill starting from cols-1 and going backwards.
public static int[][] createZigZag(final int rows, final int cols, int start) {
final int[][] array = new int[rows][cols];
for (int i = 0; i < rows; i++) {
if ((i & 1) == 1) {
for (int j = cols-1; j >= 0; j--) {
array[i][j] = start;
start++;
}
} else {
for (int j = 0; j < cols; j++) {
array[i][j] = start;
start++;
}
}
}
return array;
}
For a practice problem for my programming class we have:
"Define a method that returns the first row of a two-dimensional array of strings that has a string with the name “John”."
public class TwoDimensionalStringArrayI {
public static void main(String[] args) {
String[][] b = {{"John", "Abby"},
{"Sally", "Tom"}};
System.out.println(firstRow(b)); // line 8
}
public static String[] firstRow(String[][] a) {
String[] name = new String[a[0].length];
int counter = 0;
for (int row = 0; row < a.length; row++) {
for (int col = 0; col < a[row].length; col++) {
name[counter++] = a[row][col]; // line 17
}
}
return name;
}
}
After going through the debug process on Eclipse, my String array name is set to {"John", "Abby"}, however I am getting an ArrayIndexOutOfBoundsException error at lines 8 and 17 when attempting to run the program.
Confused on what to do to get this program to output the names "John" and "Abby."
Because of this line;
for (int row = 0; row < a.length; row++) {
The goal of firstRow(String[][] a) method is returning the first row of the array, thus, the line above should be as below;
for (int row = 0; row < 1; row++) {
Because that it traverse all of the elements of the array, it exceeds the size of the name array which has only a[0].length rooms, numerically, 2. ( String[] name = new String[a[0].length]; )
In order to make your code functional, there are two ways;
First Solution
Update the for loop conditional as written above, the test code is;
public class TwoDimensionalStringArrayI {
public static void main(String[] args) {
String[][] b = {{"John", "Abby"},
{"Sally", "Tom"}};
// System.out.println(firstRow(b)); // line 8
String[] result = firstRow(b);
for(int i = 0; i < result.length; i++)
System.out.print(firstRow(b)[i] + " ");
}
public static String[] firstRow(String[][] a) {
String[] name = new String[a[0].length];
int counter = 0;
// for (int row = 0; row < a.length; row++) {
for (int row = 0; row < 1; row++) {
for (int col = 0; col < a[row].length; col++) {
name[counter++] = a[row][col]; // line 17
}
}
return name;
}
}
The output is as below;
John Abby
You've noticed (you should), I've also updated the print line.
Second Solution
The second way to make your code functional is, returning only first row for a[][], which is actually is as easy as returning a[1]. The test code is;
public static void main(String[] args) {
String[][] b = {{"John", "Abby"},
{"Sally", "Tom"}};
// System.out.println(firstRow(b)); // line 8
String[] result = firstRow(b);
for(int i = 0; i < result.length; i++)
System.out.print(firstRow(b)[i] + " ");
}
public static String[] firstRow(String[][] a) {
return a[0];
}
And the output is;
John Abby
Hope that it helps.
I think you should switch the variables row and col in line 17.
Please help me to fix this. I just want to store a two dimensional array into a single dimensional array is it possible. what I'm trying is that I have to store two dimensional integer array which will be created dynamically.
Try like this:
int[][] arr = new int[Rows][Cols];
int[] arr1D= new int[Rows * Cols];
Rows = arr.length;
if (Rows > 0) {
Cols = arr[0].length;
} else {
Cols = 0;
}
for (int row = 0, count = 0; row < Rows; row++) {
for (int col = 0; col < Cols; col++) {
arr1D[count] = arr[row][col];
count++;
}
}
One way of doing it
import java.util.ArrayList;
public class Test1 {
public static void main(String[] args) {
int[][] twoDArrays={{10,5},{4,6},{9,8}};
ArrayList<Integer> oneDArray= new ArrayList<Integer>();
for(int i=0; i<twoDArrays.length;i++){
for(int j=0;j<twoDArrays[i].length;j++){
oneDArray.add(twoDArrays[i][j]);
}
}//printing onedArray
for(Integer s:oneDArray){
System.out.println(s);
}
}
}
Output:
10
5
4
6
9
8
First of all, Beginner here.
I'm using this code.
class MDArrays {
public static void main(String[] args) {
int[][] x;
int t=2;
x = new int[2][3];
for(int i=0; i<=1; i++) {
for(int j=0; i<=2; j++) {
x[i][j] = t;
t += 2;
System.out.println(x[i][j]);
}
}
}
}
It compiles perfectly, but when running it, after displaying 3 numbers correctly I'm getting the following error.
Exception in thread "main" java.Lang.ArrayindexOutOfBoundsException : 3 at MDArrays.main(MDArrays.java:13)
Where am I going wrong?
You are incrementing j while checking against i.
for(int j=0; i<=2; j++)
j will keep incrementing which will eventually give you an IndexOutOfBoundsException
for(int j=0; i<=2; j++) {
Is your problem. Try:
for(int j=0; j<=2; j++) {
I would write it like this:
class MDArrays
{
private static final int ROWS;
private static final int COLS;
private static final int START_VALUE;
private static final int INC_VALUE;
static
{
ROWS = 2;
COLS = 3;
START_VALUE = 2;
INC_VALUE = 2;
}
public static void main(String[] args)
{
final int[][] x;
int t;
x = new int[ROWS][COLS];
t = START_VALUE;
for(int row = 0; row < x.length; row++)
{
for(int col = 0; col < x[row].length; col++)
{
x[row][col] = t;
t += INC_VALUE;
System.out.println(x[row][col]);
}
}
}
}
The major difference is that I use the .length member rather than hard coded values. That way if I change it to x = new int[3][2]; then the code magically works and stays within its bounds.
The other big difference is that I use row/col instead of i/j. i/j are fine (and traditional) but I find when dealing with arrays of arrays (Java doesn't actually have multi-dimensional arrays) that it is easier to keep track of things if I use the more meaningful row/col (helps prevent you from doing things like for(int col = 0; row < x.length; col++)... which, incidentally, is the bug you have.