Attempting to switch columns and rows in a 2d array in Java - java

I am trying to switch the rows and columns for a 2d array.
For example:
[1,1,1]
[2,2,2]
[3,3,3]
goes to
[1,2,3]
[1,2,3]
[1,2,3]
However, my code returns the same 2d array as when it starts. Anyone know how to fix this?
Code:
public static int[][] invert(int[][] array) {
for(int j = 0; j < array.length; j++) {
for(int i = 0; i < array[j].length / 2; i++) {
int temp = array[j][i];
array[j][i] = array[j][array[j].length - i - 1];
array[j][array[j].length - i - 1] = temp;
}
}
return array;
}

Related

How can I copy a 2D array and add a new row to store the sum of the columns in Java?

Basically I have a function that receives a two dimensional array, adds an extra row and then calculates the sum of the columns and stores the results for each individual column in the extra row that was created earlier. Here is my code:
public static int[][] sum(int[][] array) {
int tempArray[][] = new int[array.length + 1][array[0].length];
for (int column = 0; column < tempArray[0].length; column++) {
int total = 0;
for (int row = 0; row < tempArray.length; row++) {
total += tempArray[row][column];
}
tempArray[tempArray.length][column] = total;
}
return tempArray;
}
So when I run a for loop to print the results I get an ArrayIndexOutOfBounds error for some reason that refers to the function. I think my logic is correct but I can't seem to make it work. For some more context the values for the array are entered by the user. Thank you whoever will answer !
You are getting ArrayIndexOutOfBounds because you are accessing the index more than the bound of array in the below line:
tempArray[tempArray.length][column] = total;
Replace it with following the line would solve your problem:
tempArray[tempArray.length - 1][column] = total;
However your code still won't work as your summation logic have bug. You are calculating the total by the following line.
total += tempArray[row][column];
But your tempArray doesn't have any value but zeros. To solve this make sure you initiate the tempArray by the values of array's like following:
int tempArray[][] = new int[array.length + 1][array[0].length];
for(int i = 0; i < array.length; i++) {
for(int j = 0; j < array[0].length; j++) {
tempArray[i][j] = array[i][j];
}
}
Hopefully this will solve your problem. Happy coding!
You have not initialised the tempArray[][].
tempArray[tempArray.length][column] = total
change it to
tempArray[tempArray.length-1][column] = total
this will resolve the index out of bound issue.
public static int[][] sum(int[][] array) {
int tempArray[][] = new int[array.length + 1][array[0].length];
for (int column = 0; column < array[0].length; column++) {
int total = 0;
for (int row = 0; row < array.length; row++) {
tempArray[row][column] = array[row][column];
total += array[row][column];
}
tempArray[tempArray.length-1][column] = total; // resolves the index out of bound issue
}
return tempArray;
}
Mentioned solutions will not work in case if rows have different length. For example, if input array is
int[][] input = new int[][] { { 1, 2, 3 }, { 2, 3 } };
This solution eliminates such problem
public static int[][] sum(int[][] array) {
int[][] tempArray = new int[array.length + 1][];
int maxLength = 0;
for (int i = 0; i < array.length; i++) {
tempArray[i] = Arrays.copyOf(array[i], array[i].length);
maxLength = Math.max(maxLength, array[i].length);
}
tempArray[tempArray.length - 1] = new int[maxLength];
for (int i = 0; i < maxLength; i++ ) {
int total = 0;
for (int[] row : tempArray) {
if (i <= row.length - 1) {
total += row[i];
}
}
tempArray[tempArray.length - 1][i] = total;
}
return tempArray;
}
And the test
public static void main(String[] args) {
int[][] arr = new int[][] { { 1, 2, 3 }, { 2, 3 } };
System.out.println(Arrays.deepToString(sum(arr)));
// Output
// [[1, 2, 3], [2, 3], [3, 5, 3]]
}

Jagged Arrays in Java: Converting char[][] and ArrayList<ArrayList<char>>

How can I convert the following so that it is essentially a jagged nested ArrayList of ArrayLists, with each row/col a list of chars?
//Following excerpt from https://www.geeksforgeeks.org/jagged-array-in-java/
int r = 5;
//Need this to have capacity to hold list of chars (eg, each row/col index can be empty, //have 1 char, or multiple chars
char toFill = new Variable(" ");
// Declaring 2-D array with 5 rows... need it to be ArrayList<ArrayList<char>>
char matrix[][] = new Variable[r][];
// Creating a 2D array such that first row
// has 1 element, second row has two
// elements and so on.
for (int i=0; i<matrix.length; i++) {
matrix[i] = new char[i + 1];
}
// Initializing array
int count = 0;
for (int i=0; i<matrix.length; i++) {
for (int j = 0; j < matrix[i].length; j++) {
matrix[i][j] = toFill;
}
}
Actually lists are dynamic structures, you don't need to pre-define their sizes as with static structures like arrays. He is a sample program directly translating the jagged array into a jagged list of lists. I tried to keep as much of the structure as possible so as to make it easier for you to understand. The code still looks kind of "array-ish" (which I actually don't like because it is somewhat unnatural), but I hope you get the idea.
package de.scrum_master.stackoverflow.q60367936;
import java.util.ArrayList;
import java.util.List;
/**
* Demonstrate 2-D jagged array/list such that first row has 1 element,
* second row has two elements and so on.
*/
class Main {
private static void jaggedArray() {
int r = 5;
// Declaring 2-D array with 5 rows
int arr[][] = new int[r][];
// Creating a 2D array such that first row has 1 element, second row has two elements and so on.
for (int i = 0; i < arr.length; i++)
arr[i] = new int[i + 1];
// Initializing array
int count = 0;
for (int i = 0; i < arr.length; i++)
for (int j = 0; j < arr[i].length; j++)
arr[i][j] = count++;
// Displaying the values of 2D Jagged array
System.out.println("Contents of 2D Jagged Array");
for (int i = 0; i < arr.length; i++) {
for (int j = 0; j < arr[i].length; j++)
System.out.print(arr[i][j] + " ");
System.out.println();
}
}
private static void jaggedArrayList() {
int r = 5;
// Declaring 2-D list of lists
List<List<Integer>> arr = new ArrayList<>();
// Adding empty sub list to main list
for (int i = 0; i < r; i++)
arr.add(new ArrayList<Integer>());
// Initializing 2-D list
int count = 0;
for (int i = 0; i < r; i++)
for (int j = 0; j <= i; j++)
arr.get(i).add(count++);
// Displaying the values of 2D Jagged list
System.out.println("Contents of 2D Jagged ArrayList");
for (List<Integer> list : arr) {
for (Integer i : list)
System.out.print(i + " ");
System.out.println();
}
}
public static void main(String[] args) {
jaggedArray();
System.out.println("\n------------------------------\n");
jaggedArrayList();
}
}
Console log:
Contents of 2D Jagged Array
0
1 2
3 4 5
6 7 8 9
10 11 12 13 14
------------------------------
Contents of 2D Jagged ArrayList
0
1 2
3 4 5
6 7 8 9
10 11 12 13 14
As you can see, both the array and the list variant yield identical results. Whether you use a List<List<Integer>> or a List<List<Char>> does not matter for the algorithm.

java array for zigzag works, but tester keeps telling me there's an error?

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;
}

2D array and creating a mirror of an image

I'm supposed to create an image editor using 2D arrays. For this part I'm supposed to create code that creates a mirror of the image by flipping it left to right. Instead I'm flipping it upside down. What am I doing wrong?
public void mirror() {
// TODO Auto-generated method stub
int[] img;
int left = 0, right = data.length -1;
while (right >= left) {
img = data[left];
data[left++] = data[right];
data[right--] = img;
}
}
Multiple Problems:
1. You're using a 1D Array.
2. data.length on 1d array gives you number of rows.
3. Now when you use data.length for reversing, you end up revering rows instead of columns in 2d array.
Hence your logically incorrect output.
Use mirror method should be something like this -
public int[][] mirror(int[][] original) {
int[][] mirror = original;
for (int i=0; i<original.length; i++) {
original[i] = reverseArray(original[i]);
}
return mirror;
}
public int[] reverseArray(int[] array) {
for (i = 0; i < array.length / 2; i++) {
int temp = array[i];
array[i] = array[array.length - 1 - i];
array[array.length - 1 - i] = temp;
}
return array;
}
The problem is you were just mirroring the arrays that made up the matrix, rather than reversing the order of the arrays. Assuming data was in fact a 2D array to begin with, this should work for you.
public void mirror() {
for (int i = 0; i < data.length; i++){
for (int j = 0; j < data[i].length/2; j++){
int temp = data[i][j];
data[i][j] = data[i][data[i].length-j-1];
data[i][data[i].length-j-1] = temp;
}
}
}
A more simple way than the other answers in my opinion:
int[][] mirrored = new int[data.length][data[0].length];
for (int i = 0; i < data.length; i++) {
for (int j = 0; j < data[i].length; j++) {
mirrored[i][data[i].length - j - 1] = data[i][j];
}
}

Shuffle the order of a 2D array in java

I'm creating my own memory game. Everything is going well so far. Just to let you know I'm using processing for Java. I have created a 2 dim PImage array. This is the code for filling the 2D array:
int g = 0;
for(int i = 0; i < 4; i++) {
for (int j = 0; j < 6; j++) {
if (j % 2 == 0) {
kaart[i][j] = loadImage( g + ".jpg" );
kaart[i][j].resize(vlakGrootte - 1, vlakGrootte - 1);
g++;
} else if (j % 2 == 1) {
kaart[i][j] = kaart[i][j-1];
}
}
}
I want the items in this array to be shuffled. It seems like java collections does not support to shuffle a 2D PImage array? Please correct me if im wrong.
Thanks to you all for helping me out.
1).Shuffle per-outter index :
YourType [][] kaart = new YourType [..][..];
List <YourType[]> list = (List<YourType[]> ) Arrays.asList(kaart);
Collections.shuffle(list);
kaart = (YourType[][]) list.toArray(new YourType[0][]);//convert back to a array
// just for checking
for(YourType[] k:kaart ){System.out.println(Arrays.toString(k));}
Replace YourType with the type of kaart.
2). Shuffle per-Outter+Inner index :
YourType[][] kaart = new YourType[..][..];
List<YourType[]> temp = new ArrayList<>();
for(YourType[] k:kaart ){
List <YourType> list = (List<YourType> ) Arrays.asList(k);
Collections.shuffle(list);//shuffle
YourType[] tempArray = (YourType[]) list.toArray();
temp.add(tempArray);
}
Collections.shuffle(temp);
kaart= (YourType[][]) temp.toArray(new YourType[0][]);//convert back to a array
// just for checking
for(YourType[] k:kaart ){System.out.println(Arrays.toString(k)); }
Replace YourType with the type of kaart.
3). Shuffle in The easiest way:
Just put all elements into a single List then call Collections.shuffle()
I would do this the same way you would deal those cards in real world. First you shuffle the deck:
ArrayList<Integer> pieces = new ArrayList<Integer>();
for (int i = 0; i < 4 * 6 / 2; i++) {
for (int j = 0; j < 2; j++) {
pieces.add(i);
}
}
Collections.shuffle(pieces);
Then you deal cards out of shuffled deck:
for(int i = 0; i < 4; i++) {
for (int j = 0; j < 6; j++) {
int g = pieces.remove(pieces.size()-1);
kaart[i][j] = loadImage( g + ".jpg" );
kaart[i][j].resize(vlakGrootte - 1, vlakGrootte - 1);
}
}

Categories