(link: https://www.interviewbit.com/problems/array_2d/)
having difficulty in performing a dry run for the following code with performOps being called with
A : [[1, 2, 3, 4], [5, 6, 7, 8], [9, 10, 11, 12]] .
ArrayList<ArrayList<Integer>> performOps(ArrayList<ArrayList<Integer>> A) {
ArrayList<ArrayList<Integer>> B = new ArrayList<ArrayList<Integer>();
for (int i = 0; i < A.size(); i++) {
B.add(new ArrayList<Integer>());
for (int j = 0; j < A.get(i).size(); j++) {
B.get(i).add(0);
}
for (int j = 0; j < A.get(i).size(); j++) {
B.get(i).set(A.get(i).size() - 1 - j, A.get(i).get(j));
}
}
return B;
}
Can anyone please help me in understanding it?
The output will be
4 3 2 1
8 7 6 5
12 11 10 9
You must be trying to initialize A.That is not the case here.The value of A is
1 2 3 4
5 6 7 8
9 10 11 12
and then the output of the further code is asked in the question.Please read the question carefully.Reach out if you need anything else.Cheers
Try substituting the variable values for one or two loops. That will be easier to understand such questions and if possible code it in editor and debug through the code one step at a time.
I have tried for one loop.
ArrayList<ArrayList<Integer>> performOps(ArrayList<ArrayList<Integer>> A) {
ArrayList<ArrayList<Integer>> B = new ArrayList<ArrayList<Integer>>();
//A.size() is 3
for (int i = 0; i < 3; i++) {
B.add(new ArrayList<Integer>());
//First Loop i = 0; A.get(0).size() = 4; Four elements in first index of array list
for (int j = 0; j < 4; j++) {
B.get(0).add(0); //Setting all elements to zeros
}
for (int j = 0; j < 4; j++) {
B.get(0).set(4 - 1 - j, A.get(0).get(j));
//For j = 0
// B.get(0).set(3, 1); //A.get(0).get(0) = 1
//For j = 1
B.get(0).set(2, 2); //A.get(0).get(1) = 2
//For j = 2
B.get(0).set(1, 3); // A.get(0).get(2) = 3
//For j = 3
B.get(0).set(0, 4); //A.get(0).get(3) = 4
}
//At the end of above loop B=[[4, 3, 2 ,1]]
}
return B;
}
By the way the output will be two dimensional collection with each inner collection elements in reverse order.
Related
My Java code get all numbers I need, but every row in new array have length like in old array. How to make array with different row length only for numbers I've got?
Please check for my code:
import java.util.Arrays;
import java.util.Random;
public class Help {
public static void main(String[] args) {
Random random = new Random();
int n = random.nextInt(10);
int m = random.nextInt(10);
if (n > 0 && m > 0) {
int[][] arr = new int[n][m];
for (int i = 0; i < arr.length; i++) {
for (int j = 0; j < arr[i].length; j++) {
arr[i][j] = random.nextInt(20);
System.out.print(arr[i][j] + " ");
}
System.out.println();
}
System.out.println();
System.out.println("***** EvenMatrix *****");
int[][] evenMatrix = new int[n][m];
int evenElement = 0;
for (int i = 0; i < arr.length; i++) {
for (int j = 0; j < arr[i].length; j++) {
if (arr[i][j] % 2 != 0) {
continue;
} else
evenElement = arr[i][j];
for (int k = 0; k < arr[i].length; k++) {
evenMatrix[i][j] = evenElement;
}
System.out.print(evenMatrix[i][j] + " ");
}
System.out.println();
}
System.out.println(Arrays.deepToString(evenMatrix));
} else {
System.out.println("Incorrect array length! Try again!");
System.exit(0);
}
}
}
I wanted to help but didn't understand the question well
Let's say your random numbers are 3x3 for n and m
And let's say your array "arr" is
[1,2,3]
[4,5,6]
[7,8,9}
And you want to be your array "evenMatrix" to be
[2,4,6,8] n = 1 and m = 4
or
[2,4] n = 2 and m = 2
[6,8]
Not n = 3 m = 3 just like in the array "arr"
[2,4,6]
[8,0,0]
is that right? If so you can check n and m before creating the "evenArray" like
int[][] evenMatrix;
if(n<m)
evenMatrix = new int[m][m];
else
evenMatrix = new int[n][n];
creating a square matrix but this still has problems let's say your random numbers are n = 5 and m = 2 so this code will create a 5x5 matrix and fill with even numbers and let's say your randomize arr array doesn't have that many even numbers are so it will become something ugly
The easy solution here is to use an ArrayList, however, we can also create variable length rows using the following, note the comments below explaining the process, but the key is this int[][] evenMatrix = new int[n][];, note how we only specify the column size, not the row size.
Complete code:
System.out.println("***** EvenMatrix *****");
//Create 3D array
int[][] evenMatrix = new int[n][];
for (int i = 0; i < arr.length; i++) {
//Create inner row that we will trim later
int[] evenElements = new int[m];
//Create a counter to track variable locations
int counter = 0;
for (int j = 0; j < arr[i].length; j++) {
if (arr[i][j] % 2 != 0) {
continue;
} else{
evenElements[counter] = arr[i][j];
//Incriment counter
counter++;
}
System.out.print(arr[i][j] + " ");
}
System.out.println();
//Trim the inner array to the correct length that we know from the `counter`
evenElements = Arrays.copyOf(evenElements, counter);
//Assign the inner row of variable length to the 3D matrix
evenMatrix[i] = evenElements;
}
//Print the result
System.out.println(Arrays.deepToString(evenMatrix));
Example output of the above code:
1 11 15 0 15 18 10
6 12 0 13 15 15 3
10 13 6 1 12 4 12
10 7 12 8 19 4 6
5 10 4 12 4 5 5
***** EvenMatrix *****
0 18 10
6 12 0
10 6 12 4 12
10 12 8 4 6
10 4 12 4
[[0, 18, 10], [6, 12, 0], [10, 6, 12, 4, 12], [10, 12, 8, 4, 6], [10, 4, 12, 4]]
l'm trying to print the diagonal numbers of a square 2D array but l'm having a hard time with it.It's because of how l create the array isn't it? What l am doing wrong?
int[][] arr1 = { { 1, 2,6}, { 3, 4,5} }; // l'm stuck here
for (int i = 0; i < arr1.length; i++) {
for (int j = 0; j <arr1.length; j++) {
System.out.print(arr1[i][j] + " ");
}
System.out.println();
}
for (int k = 0; k < arr1.length; k++) {
System.out.println( arr1[k][k]);
}
l expected to see 1 2 3
4 5 6
7 8 9
And for the actual results? l have being stuck
Your array declaration should look like this:
int[][] arr1 = { { 1, 2, 3}, { 4, 5, 6}, {7, 8, 9} };
assuming you want an ordered 3 x 3 matrix.
So if I have one int[3][3] temp1 and an int[3][3] temp2, both filled up, how would I combine them to make one temp1and2[6][3]? What I'm trying to do is splice a grid array, where x is the array to be spliced and y is the column I want to remove. I tried
public static int[][] splice(int[][] x, int y){
int[][] temp1 = new int[y][x[0].length];
for(int i = 0; i < y; i++){
for(int j = 0; j < x[0].length; j++)
temp1[i][j] = x[i][j];
}
int[][] temp2 = new int[x.length-y][x[0].length];
for(int i = y; i < x.length; i++){
for(int j = 0; j < x[0].length; j++)
temp2[i][j] = x[i][j];
}
int[][] temp1and2 = new int[temp1.length + temp2.length][x[0].length];
System.arraycopy(temp1, 0, temp1and2, 0, temp1.length);
System.arraycopy(temp2, 0, temp1and2, temp1.length, temp2.length);
return temp1and2;
}
but that didn't work. I am getting the error:
java.lang.ArrayIndexOutOfBoundsException: 2 on the temp2[i][j] = x[i][j]; line.
So for example, temp1 and temp2 would both be would be:
1 2 3
4 5 6
7 8 9
and the combined would be:
1 2 3 1 2 3
4 5 6 4 5 6
7 8 9 7 8 9
This is how i would do it by hand
//returns a new 2D array with temp1 stacked on top of temp2 or
// null if the arrays aren't the correct dimensions
public int[][] stackArrays(int[][] temp1, int[][] temp2)
{
int [][] temp1n2 = null;
if(temp1.length != 0 && temp1.length == temp2.length
&& temp1[0].length == temp2[0].length)
{
//create the new array to hold both
temp1n2 = new int[temp1.length + temp2.length][temp1[0].length];
for(int i = 0; i < temp1.length; i++)
{
for(int j = 0; j < temp1[i].length; j++)
{
temp1n2[i][j] = temp1[i][j];
temp1n2[i + temp1.length][j] = temp2[i][j];
}
}
}
return temp1n2;
}
The result of stackArrays(allZero2DArray, allOnes2DArray) gives the following 2D array:
000
000
000
111
111
111
I am trying to solve a problem on multi dimensional array using Java. I need to print all the numbers appearing diagonally for a given two dimensional matrix. I have done for one scenario but not able to do for the rest of the elements
public class TwoDimensionalArray {
private static int[][] array = {{1,2,3,4},{5,6,7,8},{9,10,11,12,}, {13,14,15,16}};
public static void main(String args[]){
for (int i=0;i<4; i++){
for(int j=0;j < 4; j++){
System.out.print(" "+ array[i][j] +" ");
}
System.out.println();
}
System.out.println();
for (int i = 0;i < 4; i++){
int offset = 0;
for(int j = offset;j <= i; j++){
System.out.print("i >> "+i+" ");
System.out.print("j >> "+j);
System.out.println(" == "+ array[i][i+offset] +" ");
}
offset++;
}
}
}
I started off writing the below code to get the first diagonal elements printed correctly.
for (int i = 0;i < 4; i++){
int offset = 0;
System.out.print(array[i][i+offset] +" ");
offset++;
}
Output: 1 6 11 16
But when I try to extend the same approach by adding inner for loop, I start iterating from 0 till i every time which results it printing the elements more than one time and not with correct output. Is my approach right or I am missing something when implementing the inner for loop.
The desired output should be like below:
1 6 11 16
2 7 12
3 8
4
5 10 15
6 11 16
7 12
8
9 14
10 15
11 16
12
This is not an assignment. I am just trying to improve my programming skills. Also please let me know the difficulty level of this problem on a scale of 1 to 5, 5 being hardest and 1 being simple.
I suppose you're looking for something like this:
private static int[][] array = {{1, 2, 3, 4}, {5, 6, 7, 8}, {9, 10, 11, 12,}, {13, 14, 15, 16}};
private static void f(int y, int x) {
while ((y < 4) && (x < 4))
System.out.print(array[y++][x++] + " ");
System.out.println();
}
public static void main(final String args[]) {
for (int i = 0; i < 3; i++)
for (int j = 0; j < 4; j++)
f(i, j);
}
I am encountering a problem generating 6 random numbers between 1 and 6 in Java. All the numbers have to be unique. When I enter kolon value 5, the arrays should be like this:
1 2 3 4 5 6
1 2 3 4 5 6
1 2 3 4 5 6
1 2 3 4 5 6
I don't want the program to generate the same two numbers. What is wrong here?
Relevant code:
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.println("Please enter row quantity: ");
int kolon = input.nextInt();
Integer[][] dizi_asil = new Integer[kolon][6];
for (int i = 0; i < kolon; i++) {
Integer[] dizi = new Integer[6];
for (int j = 0; j < 6; j++) {
dizi[j] = (int) ((Math.random() * 6) + 1);
for (int u = 0; u < 1; u++) {
for (int k = 0; k < j; k++) {
while (dizi[k] == dizi[j]) {
dizi[j] = (int) ((Math.random()* 6) + 1);
u++;
}
}
}
dizi_asil[i][j] = dizi[j];
}
Arrays.sort(dizi_asil[i]);
}
for (int i = 0; i < dizi_asil.length; i++) {
for (int k = 0; k < dizi_asil[i].length; k++) {
System.out.print(dizi_asil[i][k] + "\t");
}
System.out.println();
}
create a list containing 1 to 6. then shuffle it using Collection.shuffle. Then you will get random unique number
This is an easy way:
List<Integer> list = Arrays.asList(1,2,3,4,5,6);
Collections.shuffle(list);
// you can convert it to an array if you need to.
A very simple fix - replace u++; with u--;. ++ will make the loop stop, -- will make it carry on.
Though I'd suggest something more like the below. I hope it's easy enough to understand.
Integer[] dizi = new Integer[6];
for (int j = 0; j < 6; j++)
{
boolean isValid;
do
{
dizi[j] = (int) ((Math.random() * 6) + 1);
isValid = true;
for (int k = 0; isValid && k < j; k++)
if (dizi[k] == dizi[j])
isValid = false;
}
while (!isValid);
dizi_asil[i][j] = dizi[j];
}
I'd also suggest the Random class, which has a nextInt(int) method, which is better than (int) ((Math.random() * 6) + 1).
But shuffling is probably a faster way to do it. Either use the API like one of the other answers or look into the Fisher-Yates / Knuth shuffle for an easy shuffle algorithm.
Try Collections.shuffle(list);
List<Integer> list = new ArrayList<Integer>();
for(int i = 1; i<7 ; i++)
list.add(i);
Or you can do :
List<Integer> list = Arrays.asList(1,2,3,4,5,6)
Collections.shuffle(list);
Iterate the list and get unique value each time.
A much shorter way is to use shuffle as many have mentioned already.
public static void main(String... ignored) {
Scanner input = new Scanner(System.in);
System.out.println("Please enter row quantity: ");
List<Integer> rolls = Arrays.asList(1, 2, 3, 4, 5, 6);
for (int i = 0, rows = input.nextInt(); i < rows; i++) {
Collections.shuffle(rolls);
System.out.println(rolls);
}
}
if you run it you get something like
Please enter row quantity:
5
[5, 6, 3, 2, 4, 1]
[5, 4, 3, 6, 2, 1]
[6, 4, 2, 3, 5, 1]
[3, 1, 6, 2, 5, 4]
[4, 1, 6, 3, 5, 2]
Imports:
import acm.util.RandomGenerator;
private RandomGenerator rgen = RandomGenerator.getInstance();
Actually picking:
randnum = rgen.nextInt(1, 6);
This picks a random number between 0 and 5. You can just do this for 1 through 6:
randnum = rgen.nextInt(2, 7);
Or:
randnum = rgen.nextInt(1, 6);
randnum++;