2D array and creating a mirror of an image - java

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

Related

Attempting to switch columns and rows in a 2d array in 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;
}

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

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

How to get the contents of a column to slide down to the bottom row of my 7x7 2D array?

I've been lurking and found heaps of great information form here, however the last few days I have been stuck and haven't been able to find help with my issue so I thought id post.
I have some homework and I have to make the contents of my array drop down to the bottom row. If i rotate the grid the items should still drop down to the bottom row and if i eat an object from the bottom row, everything above it in that column should drop down too.
Any help is greatly appreciated.
Here is a demo video of what should happen:
http://youtu.be/CB07vN-C_-Y
This is what i have so far:
`public class Assignment
{
// This method should return a *new copy* of
// the 2D cell matrix, with entries rotated clockwise
// The original matrix should not be changed
public static int[][] rotateClockwise(int[][] cells)
{
int w = cells.length;
int h = cells[0].length;
int[][] matrix = new int[h][w];
for (int i = 0; i < h; ++i)
{
for (int j = 0; j < w; ++j)
{
matrix[i][j] = cells[j][h - i - 1];
}
}
return matrix;
}
// This method should return a *new copy* of
// the 2D cell matrix, with entries rotated anti-clockwise
// The original matrix should not be changed
public static int[][] rotateAnticlockwise(int[][] cells)
{
int w = cells.length;
int h = cells[0].length;
int[][] matrix = new int[h][w];
for (int i = 0; i < h; ++i)
{
for (int j = 0; j < w; ++j)
{
matrix[i][j] = cells[w - j - 1][i];
}
}
return matrix;
}
// This method should return a *new copy* of the array, except
// that if there is a 0 that has a non-zero in the preceding
// slot in the array, then those two entries should be swapped
// See ProgrammingProject.pdf for an example
// The original array should not be changed
public static int[] dropOne(int[] column)
{
return column; // this will compile but gives the wrong result
}
}`
I'd model a column as a Queue<Icon> col = new LinkedList<Icon>(); there's an outline here for Queue<Segment> and a complete example here for Queue<Bauble>. You can peek() at the head (bottom) of the queue; if it's empty, you remove() a block from the column and add() it to the tail (top).
Addendum: You might start with this example, drop the getGray(), change the layout to new GridLayout(0, 1). Then, instead of shuffle(list), you'd cycle the queue.
for(int i = 0; i < arrayWidth; i++) {
boolean reachedZero = false;
for( int j = 0; j < arrayHeight; j++) {
if(array[i][j] == 1 && reachedZero == true) {
while( j >=0 && array[i][j - 1] == 0) {
array[i][j-1] = array[i][j];
array[i][j] = 0;
j--;
reachedZero = false;
}
j--; // Maybe an error here, it's late
if( array[i][j] == 0) {
reachedZero = true;
}
}
}
This was posted by a lovely redditor (RankWeis) from the /learnprogramming sub-reddit.
http://www.reddit.com/r/learnprogramming/comments/126597/java_help_needed_on_adding_a_gravity_effect_to/

Eclipse - Java Array ID Values are Equal. Cannot change values independently

I have two arrays that I create like this:
public int GameBoard[][] = new int[30][14];
public int DirectionMap[][] = new int[30][14];
I then initialize the arrays like this:
for (int i = 0; i < GameBoard.length; i++)
{
for (int j = 0; j < GameBoard[i].length; j++)
{
GameBoard[i][j] = 0;
}
}
... //Same for DirectionMap
When I run the function:
DirectionMap = AStar(GameBoard);
To render the pathfinding map that my units will follow, DirectionMap is correctly set to the values generated based on my GameBoard. However GameBoard is set to the result as well. When I run the application in Debug Mode within Eclipse, I can see that the ID's of the two arrays are the same. For some reason they seem to be pointing to the memory space. My AStar function does not modify the GameBoard array at all. The only reference to it is int retVal[][] = GameBoard;
My function prototype is public int[][] AStar(int[][] Board); and it returns the int[][] retVal.
I have no idea why I cannot change the values of DirectionMap without GameBoard following. I have never had any issues like this before.
Any ideas are really appreciated. Thanks for your help.
public int[][] AStar(int[][] Board)
{
int retVal[][] = Board;
//Initialize All Needed Lists
int width = retVal.length;
int height = retVal[0].length;
int goalX = 0;
int goalY = 0;
//List<Node> fieldInfo = new ArrayList<Node>();
Node fieldArray[][] = new Node[width][height];
for (int i = 0; i < fieldArray.length; i++)
{
for (int j = 0; j < fieldArray[i].length; j++)
{
fieldArray[i][j] = new Node(i, j);
if (retVal[i][j] == 2)
{
fieldArray[i][j].setOpen(1);
fieldArray[i][j].setDirection(10); //Set as target
goalX = i;
goalY = j;
}
if (retVal[i][j] == 1)
{
fieldArray[i][j].setOpen(0);
fieldArray[i][j].setDirection(9); //Set as wall
}
}
}
//Add AStar Algorithm Here
for (int i = 0; i < fieldArray.length; i++)
{
for (int j = 0; j < fieldArray[i].length; j++)
{
if (fieldArray[i][j].getDirection() == 0)
{
//Occurs when node was never reached
int dX = i - goalX;
int dY = j - goalY;
if (dX < 0)
dX = -dX;
if (dY < 0)
dY = -dY;
if (dY > dX)
fieldArray[i][j].setDirection(1);
else
{
if (i > goalX)
fieldArray[i][j].setDirection(7);
if (i < goalX)
fieldArray[i][j].setDirection(3);
}
}
}
}
for (int i = 0; i < fieldArray.length; i++)
{
for (int j = 0; j < fieldArray[i].length; j++)
{
retVal[i][j] = fieldArray[i][j].getDirection();
}
}
return retVal;
}
Remember when you are passing an object to methods you are actually passing a copy of reference. So when you initialise retVal[][] = Board; you actually point Board using another reference retVal. And you are returning the same reference to DirectionMap. Hence same id's for Board and DirectionMap. Consider array copy instead.
I can see that the ID's of the two arrays are the same. For some
reason they seem to be pointing to the memory space
The int[] array in Java has 0's as default values.
int[] x = new int[2];
System.out.println(x[0]); // prints 0
System.out.println(x[1]); // prints 0
The only reference to it is int retVal[][] = GameBoard;
Java arrays are objects. If at any point you are setting array = array, you are setting one reference to point to the same object as the other.

Categories