Write methods with the following headers 1. public static int[] twoDimensionalTo
ID: 639719 • Letter: W
Question
Write methods with the following headers
1. public static int[] twoDimensionalToOneDimensional(int[][] arr)
- if arr is null then this method returns null
- if arr is not null then (i) copy the rows of arr to a one-dimensional array
and (ii) return the one-dimensional array.
- the length of the return array should be equal to the number of values
stored in arr
Copy the rows in ascending order. In other words, first copy row 0 to the
one-dimensional array, then row 1, 2, etc.
Example:
Assume int[][] arr = { { 1,20, 50}, {5, 8}, {22, 100, 200, 1}};
Also assume we have the variable
int[] returnArray
If we copy the contents of arr to returnArray, then returnArray contains
the following values:
{ 1, 20, 50, 5, 8, 22, 100, 200, 1};
Suggestion: Each row of arr may have a different number of columns. If
arr isn
Explanation / Answer
comment if you have any doubts.
public class HW1 {
public static void display(int[] arr) {
for (int x : arr) {
System.out.print(x + " ");
}
System.out.println();
}
public static void main(String[] args) {
int[][] numbers = { { 7, 6, 5, 3, 2, 1 }, { 109 }, { -77, 61, 2 } };
int[] output = twoDimensionalToOneDimensional(numbers);
if (output == null) {
System.out.println("The 1-D array is null");
} else {
display(output);
}
System.out.println();
numbers = null;
output = twoDimensionalToOneDimensional(numbers);
if (output == null) {
System.out.println("The 1-D array is null");
} else {
display(output);
}
System.out.println();
int[] x = {3, 4, 8, -1, 2, 4};;
display(x);
rotateArray(x, 2);
display(x);
System.out.println();
}
public static int[] twoDimensionalToOneDimensional(int[][] arr)
{
if(arr==null)return null;
int newlength=0;
for(int i=0;i<arr.length;i++)
{
for(int j=0;j<arr[i].length;j++)
newlength++;
}
int newarr[]=new int[newlength];
int num=0;
for(int i=0;i<arr.length;i++)
{
for(int j=0;j<arr[i].length;j++)
{newarr[num]=arr[i][j];num++;}
}
return newarr;
}
public static void rotateArray(int[] arr, int rotate)
{
if(arr!=null)
{
int dummy[]=new int[arr.length];
for(int i=0;i<arr.length;i++)
{
int dum=arr.length+i-rotate;
if(dum >= arr.length)dum=dum-arr.length;
dummy[i]=arr[dum];
}
for(int i=0;i<arr.length;i++)
arr[i]=dummy[i];
}
}
}
//output:
7 6 5 3 2 1 109 -77 61 2
The 1-D array is null
3 4 8 -1 2 4
2 4 3 4 8 -1
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.