Shifting specific elements in a 2D Array - java

I am trying to shift specific elements in a two dimensional array i.e. while some elements move, others stay in a fixed position. For Example:
char arr[][] = {{'.','.','.'},{'.','u','.'},{'x','.','.'}};
will be shifted to:
arr[][] = {{'.','u','.'},{'.','.','.'},{'x','.','.'}};
I have a code sample to shift all elements in the array a certain number of places up such that it wraps around from the bottom, but can't figure out how to keep the x's in a fixed position. I read all elements into a new Array.
public static void moveUp(char arr[][], int pos){
for(int r = 0; r < 6; r ++){
for(int c = 0 ; c < 5; c++){
newArr[(r+(6-pos))%6][c] = arr[r][c];
}
}
}
This is made on the auumption that the array has 6 rows and 5 columns.

You should do a boolean if you want the 'u' to go up and the x to stay as you commented. For example, the position of 'u' should change from char[i][j] to char[i-1][j].

Related

How do I get the code to print random numbers in all the elements of the 2d array?

I got the 2d array to print but with all zero's and the only random number comes up on the bottom right corner
How do I get the code to print random numbers in all the elements of the 2d array?
Here is my code:
public static void main(String[] args) {
int columns = 8;
int rows = 4;
int rLow = 2;
int rHigh = 9;
printRandos(columns, rows, rLow, rHigh);
}
public static void printRandos(int clmn, int rws, int rlow, int rhigh) {
Random rando = new Random();
int randoNum = rlow + rando.nextInt(rhigh);
int[][] randoArray = new int[rws][clmn];
for (int i = 0; i < rws; i++) {
for (int k = 0; k < clmn; k++) {
randoArray[rws - 1][clmn - 1] = randoNum;
System.out.print(randoArray[i][k] + " ");
}
System.out.print("\n");
}
}
for (int i = 0; i < rws; i++)
{
for (int k = 0; k < clmn; k++)
{
int randoNum = rlow + rando.nextInt(rhigh);
randoArray[i][k] = randoNum;
System.out.print(randoArray[i][k]+" ");
}
System.out.print("\n");
}
your mistake inside the inner for loop of the printRandos method. Firstly your random number is outside the loop so your array elements were receiving the same number all the time. Another mistake is that you are assigning the value to the same array element all the time i.e rws-1 and clmn-1 .
inside your inner loop replace it with this:
int randoNum = rlow + rando.nextInt(rhigh);
randoArray[i][k] = randoNum;
System.out.print(randoArray[i][k]+" ");
Your bug is in this line:
randoArray[rws-1][clmn-1] = randoNum;
This stores your random number into randoArray[rws-1][clmn-1] each time, which as you noticed, is the bottom right corner. rws is always 4, and clmn is always 8. So you store the same number there 32 times, which gives the same result as storing it only once.
In the following line you are correctly printing the number from the current array location:
System.out.print(randoArray[i][k]+" ");
An int array comes initialized with all zeroes, and since except for the last corner you have not filled anything into your array, 0 is printed.
Also if you want different random numbers in all the cells, you would need to call rando.nextInt() inside your innermost for loop.
Unless you need this 2-D array for some purpose (which doesn't show from the minimal example code that you have posted), you do not need it for printing a matrix of random numbers, i.e., you may just print the numbers form within your loop without putting them into the array first.
Finally if rhigh should be the highest possible random number in the array, you should use rando.nextInt(rhigh - rlow + 1). With rlow equal to 2 and rhigh equal to 9 this will give numbers in the range from 0 inclusive to 9 - 2 + 1 = 8 exclusive, which means that after adding to rlow = 2 you will get a number in the range from 2 to 10 exclusive, in other words, to 9 inclusive.
I am on purpose leaving to yourself to fix your code based on my comments. I believe your learning will benefit more from working it out yourself.
Your assign the array value outside the array length
int[][] randoArray = new int[rws][clmn];
randoArray[rws][clmn] = randoNum;
Here randoArray[rws] is out of bounds.

Access a 2d array index without coordinates in Java

Lets say we have a 8 x 8 2d integer array named grid and trying to select the element 0 at [5][5]
int[][] grid = new int{{1,1,1,1,1,1,1,1},
{1,1,1,1,1,1,1,1},
{1,1,1,1,1,1,1,1},
{1,1,1,1,1,1,1,1},
{1,1,1,1,1,1,1,1},
{1,1,1,1,1,0,1,1},
{1,1,1,1,1,1,1,1},
{1,1,1,1,1,1,1,1}};
Now the question is, is it possible to access the index of element 0 without using coordinates and just use a single number?
example: access the element 0 with the number 45, like a 1d array
I tried approaching this problem with a for loop but it is giving me out of range errors.
int x = 0;
int y = 0;
for (int i = 0;i<45;i++) {
x += 1;
if (x > grid[y].length) {
x = 0;
y += 1;
}
The code above is supposed to add x and y until it reaches the target element.
Eventually you would have to use the two indexes.
You could calculate the x and y given just a single number.
public static int getAt(int[][] matrix, int position) {
int columns = matrix[0].length; // column size, matrix has to be at least 1x1
return matrix[position / columns][position % columns];
}
public static void setAt(int[][] matrix, int position, int value) {
int columns = matrix[0].length; // column size, matrix has to be at least 1x1
matrix[position / columns][position % columns] = value;
}
Also in your example:
1) You don't need to use a for loop (and again eventually to access or modify the matrix you would have to use both indexes).
2) When y is greater or equal than the row size (8 in this case) you will receive an out of bounds exception because you only have 8 columns.
Finally the only way to access it with one index is if you transform the matrix to a 1d array.
Here you can see how:
how to convert 2d array into 1d?

Iterative Depth First Search To Find A String (2D Array)

I'm trying to create an iterative approach to a boggle game. The class contains fields for a 2d Array of Strings called "board" and has a 2d array of booleans called "haveVisit". The method that calls test 2 loops through the whole board, finding positions of the first character of the target string, then passes the coordinates into the test2 method, returning a list holding coordinates.
The return1Index method takes a 2D array coordinate at creates a int representative of the coordinates from a corresponding 1d array from it. The return2DIndex does the opposite and returns an int array holding the two coordinates.
public List<Integer> test2(int row1, int row2, String findMe){
String temp = findMe;
List<Integer> output = new ArrayList<Integer>();
if (board[row1][row2].charAt(0) != findMe.charAt(0))
return output;
haveVisit = new boolean[size][size];
int row = row1;
int column = row2;
output.add(return1DIndex(row, column));
haveVisit[row][column] = true;
//for each letter in the string
for(int j = 0; j < temp.length(); j++)
//for every column and row combination
for (int x = row - 1; x < row + 2 ; x++)
for (int y = column - 1; y < column + 2 ; y++)
//if index is valid and not visited
if (x > -1 && y > -1 && y < size && x < size && !haveVisit[x][y])
//if the output is the same size as string, return
if(output.size() == findMe.length())
return output;
//if the character in the board matches the char we're looking for
if(board[x][y].charAt(0) == temp.charAt(j))
{
haveVisit[x][y] = true;
output.add(return1DIndex(x, y));
//update row and column indices
row = x;
column = y;
}
}
}
return output;
}
For some reason this method works only 50% of the time. The method works fine with finding the letters when they're arranged left to right or top to bottom, but finding words from right to left or bottom to top never works except for one case: when you're searching for a string of length 1 or 2, where this method always works.
I have a working recursive solution but I wanted to try this way. Any thoughts as to why this wouldn't work?
Edit: Code now works from right to left, but still does not work when attempting to search upwards.
I don't know exactly what the problem is, but there are a few suspects:
You are updating row and column indices while checking their neighbors. This is like removing an element from an array while iterating through it: it's well defined, but has tricky semantics. I suggest either bailing out (greedy algorithm) or keeping a stack of matches (deeper search, requires saving stack of visited cells too).
The fors are missing opening braces, but the closing braces are there, suggesting missing code.
I'm not familiar with boggle, but isn't it possible for a letter to have two similar neighbors, like AXA? By just doing output.add(return1DIndex(x, y)); you may be outputting two ways to get the same letter. You may end up with output longer than findMe.
My suggestion is to follow a more standard format of depth-first search while you iron out the bugs. Wikipedia has a non-recursive pseudocode implementation, for example: https://en.wikipedia.org/wiki/Depth-first_search#Pseudocode .

searching a 2D int[][] array?

How do I search a 2D array for a specific number (1)? I thought the following code did it, but apparently I was looking in a specific spot whenI declared it with [4][4].
boolean undirectedCircuit (int [][] graph)
{
//graph = graph1(graph1(null));
int edgeCounter = 0;
for (int edge = 0; edge < graph.length; edge++)
{
/* SET FOR WHEN 1s are found in array: edgeCounter++;*/
if(graph[4][4] == '1')
{
edgeCounter++;
System.out.println("edgeCounter found '1' " + edgeCounter + "times");
}
}
if (edgeCounter % 2 == 0)
{
System.out.println("This is a circuit!");
//return true;
}
else System.out.println("This is not a circuit!!");
return false;
}
public void go ()
{
graph1 = new int[][] //This line is complained about.
{
{0,1,1,1,0},
{1,0,0,0,1},
{1,0,0,1,0},
{1,0,1,0,1},
{0,1,0,1,0}
};
undirectedCircuit(graph1); //This is complained about.
}
This is part of an assignment from my school, just pointers would be great. Thank you!
This line is wrong in two ways:
if(graph[4][4] == '1')
The quotes around '1' make it a char literal. Since your array contains ints, you'll want to drop the quotes and just write 1.
graph[4][4] will always check the same value in the array as you said. Specifically, it will always access the fifth value in the fifth array of your 2d array. Whenever you write numbers in your code, they are constants: the number 4 is never going to change during your program's execution, so you keep using 4 as the index over and over again, accessing the fifth element each time you do so.
In order to access every element in an array, you can loop over it like this:
for (int n = 0; n < array.length; n ++)
{
array[n]; //access the nth element of the array
}
n in this instance is the same as your edge variable.
However, since you are using a 2d array, these elements are themselves arrays! Therefore, you need another loop:
//array is a 2d array...
for (int n = 0; n < array.length; n ++)
{
//...so its elements are 1d arrays
for (int m = 0; m < array[n].length; m ++)
{
array[m][n]; //here we have a specific object in our 2d array.
}
}
We use variables for our indices so they can change in the loop and access different values in the array. Hope this helps!
You could try something like this where you will iterate through both dimensions of the array and check your current location rather than the 4,4
for (int x = 0; x < graph.length; x++)
{
for (int y = 0; y < graph[x].length; y++)
{
/* SET FOR WHEN 1s are found in array: edgeCounter++;*/
if (graph[x][y] == 1)
{
edgeCounter++;
System.out.println("edgeCounter found '1' " + edgeCounter + "times");
}
}
}

Searching specific rows in a multi-dimensional array

I'm new to java programming and I can't wrap my head around one final question in one of my assignments.
We were told to create a static method that would search a 2-D array and compare the numbers of the 2-D array to an input number...so like this:
private static int[] searchArray(int[][] num, int N){
Now, the part what we're returning is a new one-dimensional array telling the index of the first number in each row that is bigger than the parameter variable N. If no number is bigger than N, then a -1 is returned for that position of the array.
So for example a multi-dimensional array named "A":
4 5 6
8 3 1
7 8 9
2 0 4
If we used this method and did searchArray(A, 5) the answer would be "{2,0,0,-1)"
Here is a very good explanation about Java 2D arrays
int num[][] = {{4,5,6},{8,3,1},{7,8,9}};
int N = 5;
int result[] = new int[num.length];
for(int i=0; i<num.length; i++){
result[i] = -1;
for(int j=0; j<num[0].length; j++){
if( N < num[i][j] ){
result[i] = j;
break;
}
}
}
for(int i=0; i<result.length; i++){
System.out.println(result[i]);
}
The first for loop(The one with a for inside it) traverses the 2D array from top to bottom
in a left to right direction. This is, first it goes with the 4 then 5,6,8,3,1,7,8,9.
First the result array is created. The length depends of the number of rows of num.
result[i] is set to -1 in case there are no numbers bigger than N.
if a number bigger than N is found the column index is saved result[i] = j and a break is used to exit the for loop since we just want to find the index of the first number greater than N.
The last for loop just prints the result.
Generally when using multi-dimensional arrays you are going to use a nested for loop:
for(int i = 0; i < outerArray.length; i++){
//this loop searches through each row
for(int j = 0; j < innerArrays.length; j++) {
//this loop searches through each column in a given row
//do your logic code here
}
}
I won't give you more than the basic structure, as you need to understand the question; you'll be encountering such structures a lot in the future, but this should get you started.

Categories

Resources