Horizontal Transformation of Array (2D) - java

It's a simple matter of flipping an image horizontally and/or vertically. The premise is that given a 2D integer array that was created from importing a picture, I must create a method with a int[][] param and horizontally flip it before returning void.
The syntax is below:
public static void horizontalFlip(int[][] imgArray)
{
int temp;
for (int i = 0; i < imgArray.length; i++)
{
for (int j = 0; j < imgArray[i].length / 2; j++)
{
temp = imgArray[i][j];
imgArray[i][j] = imgArray[imgArray.length - 1 - i][j];
imgArray[imgArray.length - 1 - i][j] = temp;
}
}
}
I use imgArray as the array param and use temp as a placeholder while the loop swaps pixels, or rather, that was the intention. Currently the window does nothing after prompting the flip. Can somebody help me find the problem with the logic or syntax?
Thanks in advance, please specify any details I should provide
P.S. I can confirm the unreferenced supplied code is functional and tested.

It is happening because you are using i instead of j. But i will not stop after halfway, but it is continued and re-swap the array.
Here is a correct code :
for (int i = 0; i < imgArray.length; i++) {
for (int j = 0; j < imgArray[i].length / 2; j++) {
temp = imgArray[i][j];
imgArray[i][j] = imgArray[i][imgArray.length - 1 - j];
imgArray[i][imgArray.length - 1 -j] = temp;
}
}
Or if you want to swap columns, not rows :
for (int i = 0; i < imgArray.length / 2; i++) {
for (int j = 0; j < imgArray[i].length; j++) {
temp = imgArray[i][j];
imgArray[i][j] = imgArray[imgArray.length - 1 - i][j];
imgArray[imgArray.length - 1 -i][j] = temp;
}
}

This will correctly flip the image horizontally:
public static void horizontalFlip(int[][] imgArray)
{
int temp;
for (int i = 0; i < imgArray.length; i++) {
for (int j = 0; j < imgArray[i].length/2; j++) {
temp = imgArray[i][j];
imgArray[i][j] = imgArray[i][imgArray[i].length - 1 - j];
imgArray[i][imgArray[i].length - 1 - j] = temp;
}
}
}

Please see my solution below,
for(int i=0; i<matrix.length / 2; i++)
{
int[] row = matrix[i];
int[] temp = row;
matrix[i] = matrix[matrix.length - 1];
matrix[matrix.length - 1] = row;
}

Related

JAVA Inversion of multidimensional arrays [duplicate]

I'm trying to invert and flip a two-dimensional array, but something goes wrong! Flipping works ok, but inverting is not.
Can't find a mistake right here:
public int[][] flipAndInvert(int[][] A) {
int row = -1;
int col = -1;
int[][] arr = A;
for (int i = 0; i < arr.length; i++) {
row++;
col = -1;
for (int j = arr[i].length - 1; j >= 0; j--) {
col++;
arr[row][col] = A[i][j];
}
}
for (int i = 0; i < arr.length; i++) {
for (int j = 0; j < arr[i].length; j++) {
if (arr[i][j] == 1) {
arr[i][j] = 0;
} else {
arr[i][j] = 1;
}
}
}
return arr;
}
int[][] A = { { 0, 1, 1 },{ 0, 0, 1 },{ 0, 0, 0 } };
After proceeding the output should be:
After inverting:
{1,1,0},{1,0,0},{0,0,0}
After flipping:
{0,0,1,},{0,1,1},{1,1,1}
Thanks to all a lot, the problem was here:
int[][] arr = A;
The reference of the array is being passed to arr.
What I think is that since you are using this line:
int[][] arr = A;
The reference of the array is being passed to arr, and hence the line:
arr[row][col] = A[i][j];
is equivalent to:
A[row][col] = A[i][j];
as arr has an reference to A and they both now refer to the same memory location (or they are both different names to a single variable)
You can fix this by either using the new keyword with arr and then initializing it:
int[][] arr = new int[someRows][someCols];
//use for loop to assign the value to each element of arr
Or you can run the for loop till arr[i].length/2 - 1:
for (int i = 0; i < arr.length; i++) {
row++;
col = -1;
for (int j = arr[i].length / 2 - 1; j >= 0; j--) { //here changed arr[i].length to arr[i].length / 2
col++;
arr[row][col] = A[i][j]; //for this you do not need arr and you can directly work on A and return it
}
}
The problem of your code should be this line:
int[][] arr = A;
You are assigning the reference of array A to arr and from then when you modify one you modify both of the arrays or better they are modified together because they refer to the same address.
Using apache commons lang:
int[][] matrix = new int[3][3];
for (int i = 0; i < matrix.length; i++) {
matrix[i][0] = 3 * i;
matrix[i][1] = 3 * i + 1;
matrix[i][2] = 3 * i + 2;
}
System.out.println(Arrays.toString(matrix[0]));
System.out.println(Arrays.toString(matrix[1]));
System.out.println(Arrays.toString(matrix[2]));
ArrayUtils.reverse(matrix);
System.out.println(Arrays.toString(matrix[0]));
System.out.println(Arrays.toString(matrix[1]));
System.out.println(Arrays.toString(matrix[2]));
Hope this helps.

How to sort 2D array by columns and by diagonal using Selection Sort in Java

Firsly, I have a Matrix which I need to sort in such way (shown on the picture) using Selection Sort:
the way to sort the Matrix
Thus, the array should be sorted in increasing way from up to down. What's more, we have to sort elements of the right diagonal of Matrix.
Here's my code, but it doesn't work properly because I take diagonal into account.
public class PAS {
public static void main(String[] args) {
int n = 5; int max = 25; int minimL = 0; int MinRow, Temp;
int[][] array = new int [n][n];
for (int i = 0; i < n; i++)
for (int j = 0; j < n; j++)
array[i][j] = (int) (Math.random() * (max - minimL + 1) + minimL);
for (int i = 0; i < n; i++) {
for (int j = 0; j < n; j++)
System.out.print(" " + array[i][j]);
System.out.println();
}
System.out.println();
for (int NumCol = n - 1; NumCol >= 0; NumCol --) {
for (int NumRow = 0; NumRow < n; NumRow++) {
if (NumCol >= n - NumRow - 1) // Getting the right diagonal of Matrix changing position of columns to rows in order to sort them
{
MinRow = NumRow;
for (int j = NumRow + 1; j < n; j++)
if (array[(n - 1) - NumCol][NumCol] > array[MinRow][(n - 1) - NumCol])
MinRow = j;
Temp = array[NumRow][(n - 1) - NumCol];
array[(n - 1) - NumCol][NumCol] = array[MinRow][(n - 1) - NumCol];
array[MinRow][(n - 1) - NumCol] = Temp;
}
}
}
for (int i = 0; i < n; i++) {
for (int j = 0; j < n; j++) {
System.out.print(" " + array[i][j]);
}
System.out.println();
}
}
}
Is it possible to sort it properly in the way shown on the picture taking O(n^3) notation?

How to write condition to pretend go over array size?

Iam doing homework and i have problem with two dimensional array. To be specific i have to find highest sum of numbers and write left hand corner and right corner. But how to write condintion when the number is in the corner ?
There is an image https://imgur.com/cHCPDuN
I already tried to start FOR from 1 not from 0 and it works but i want more effective way
int[][] pole = new int[6][6];
Random sc1 = new Random();
int a = 0;
for (int j = 1; j < pole.length - 1; j++) {
for (int i = 1; i < pole.length - 1; i++) {
a = sc1.nextInt(9) + 1;
pole[i][j] = a;
}
if (j == 4) {
for (int j1 = 0; j1 < pole.length; j1++) {
for (int i1 = 0; i1 < pole.length; i1++) {
System.out.print(pole[i1][j1] + " ");
}
System.out.println();
}
}
}
This one works but i had to used this wrong way...

Sort an array alphabetically

I need to sort book objects by their titles in a simple way. However, the selection sort algorithm I wrote isn't working properly and just moves the books around, but with no apparent order. What am I doing wrong?
int j;
int b;
for (int i = 0; i < 20 - 1; i++) {
int minIndex = i;
for (j = i + 1; j < 20; j++) {
b = (bookA[j].getTitle().compareTo(bookA[minIndex].getTitle()));
if (b < 0) {
minIndex=j;
}
}
Book temp = bookA[i];
bookA[i] = bookA[j];
bookA[j] = temp;
}
for (int z = 0; z < 20; z++)
System.out.println(bookA[z].toString());
You're using j as an index in bookA[i] = bookA[j];. The problem is that you're overriding the value of j at every iteration, so when it finally gets to bookA[i] = bookA[j]; it will always be 20.
What you want is to replace it with bookA[minIndex]. The resulting code would look like this:
int j;
int b;
for(int i=0;i<20-1;i++){
int minIndex=i;
for(j=i+1;j<20; j++) {
b=(bookA[j].getTitle().compareTo(bookA[minIndex].getTitle()));
if(b<0){
minIndex=j;
}
}
Book temp = bookA[i];
bookA[i] = bookA[minIndex];
bookA[minIndex] = temp;
}
for(int z=0;z<20;z++)
System.out.println(bookA[z].toString());

Printing a triangle in Java

I'm practicing basic coding exercises and trying to print the following triangle in Java:
*
***
*****
***
*
The following code gives me the results but I feel like there must be a much more elegant solution
for (int i = 1; i <= 5; i++) {
if (i % 2 == 1) {
for (int j = 1; j <= i; j++) {
System.out.print("*");
}
System.out.println("");
}
}
for (int i = 3; i > 0; i--) {
if (i % 2 == 1) {
for (int j = 1; j < i + 1; j++) {
System.out.print("*");
}
System.out.println("");
}
}
Can anyone provide some insight into how to make this work in a better way?
Ok, here's some more code that produces the correct result that uses just the two for loops, but it looks even uglier:
for (int i = 1; i <= 10; i += 2) {
if (i <= 5) {
for (int j = 1; j <= i; j++) {
System.out.print("*");
}
System.out.println("");
}
else if(i > 5 && i < 8){
for(int j = i/2; j > 0; j--){
System.out.print("*");
}
System.out.println("");
}
else{
for(int j = 1; j > 0; j--){
System.out.print("*");
}
System.out.println("");
}
}
First, you are skipping each 2nd iteration of the loop because you want to increase two steps at once. You can do this by changing the "i++" in your loop to "i += 2" and "i--" to "i -= 2", that will have the same effect and allows you to remove the if inside both loops.
Another improvement would be using a single outer loop and figuring out whether the inner loop should be increasing or decreasing the amount of asterisks. Maybe you can come up with an equation that gives you the amount of asterisks based on the value of i? (I didn't want to solve it completely so you have some exercise left, just comment if you want a full solution)
Updated with a solution that might be considered elegant as you can change the height of the triangle and there is no repetition:
int height = 5;
for (int i = 1; i <= 2 * height; i += 2) {
int numAsterisks;
if (i <= height) {
numAsterisks = i;
} else {
numAsterisks = 2 * height - i;
}
for (int j = 0; j < numAsterisks; j++) {
System.out.print("*");
}
System.out.println();
}
What about the following?
public void printTriangle(int size) {
int half = size / 2;
for (int i = 0; i < size; i++) {
int stars = 1 + 2 * (i <= half ? i : size - 1 - i);
char[] a = new char[stars];
Arrays.fill(a, '*');
System.out.println(new String(a));
}
}
Or just a bit more optimized:
public void printTriangle(int size) {
int half = size / 2;
char[] a = new char[size];
Arrays.fill(a, '*');
for (int i = 0; i < size; i++) {
int stars = 1 + 2 * (i <= half ? i : size - 1 - i);
System.out.println(new String(a, 0, stars));
}
}
for(int i = 0; i < 7; i++) {
for(int j = 0; j < i; j++) {
print("*");
}
print("\n");
}
This can be another solution to print a regular right triangle...
Here's a different way of looking at the problem. By using an integer array, I can solve lots of shape drawing problems by changing the values in the array.
When solving more difficult problems, you would use model classes instead of simple integers. The idea, however, is the same.
Here's the output.
*
***
*****
***
*
And here's the code:
public class Triangle {
public static void main(String[] args) {
int[] heights = {1, 3, 5, 3, 1};
for (int i = 0; i < heights.length; i++) {
for (int j = 0; j < heights[i]; j++) {
System.out.print("*");
}
System.out.println("");
}
}
}
How about...
int width = 5;
for (int i = 1; i <= width; i+=2){
System.out.println(String.format("%"+i+"s", "").replaceAll(" ", "*"));
}
for (int i = width-2; i > 0; i-=2){
System.out.println(String.format("%"+i+"s", "").replaceAll(" ", "*"));
}
Or, even better yet...
int width = 7;
double half = width / 2
for (int i = 0; i < width; i++){
System.out.println(String.format("%"+((i < half ? i : (width-i-1))*2+1)+"s", "").replaceAll(" ", "*"));
}
Gives
*
***
*****
***
*

Categories