Decrements a multidimensional array in java - java

I'm having trouble understanding how to start the first index of array from the bottom to to the top of a multidimensional array. Here's what I've tried to initialize my array from bottom to top (in 2d array table format):
for(int row = arrayName.length - 1; row > 0; row--) {
for(int col = 0; col < arrayName.length; col++) {
arrayName[row][col] = ' ';
}
}
or
for(int row = arrayName.length - 1; row > 0; row--) {
for(int col = arrayName.length - 1; col < 0; col--) {
arrayName[row][col] = ' ';
}
}
i mean..when i run the program, the array always store my values from top to bottom, the opposite of what i wanted it to do. Please help! thanks in advance.

Matrices and Arrays don't really have any inherent sense of direction. Their direction is entirely determined by the order in which you choose to display the information. Depending on how you structure your loop, the contents of the array will be outputted differently. If you want to store elements from the "bottom" to the "top," what that actually means is that your print out loop should be structured in an opposite direction from your assignment loop. So for example (assuming an NxN array),
for (int i = 0; i < arr.length; i++) {
for (int j = 0; j < arr.length; j++) {
arr[i][j] = <some value here>;
}
}
Say for simplicity's sake you think of vertex (0,0) being in the top left corner, where columns increase as you move right and rows increase as you move down. Then to print from the bottom up, you would want to start from the last row and move to the first row.
for (int i = arr.length - 1; i >= 0; i--) { // Note the >= 0, which was incorrect
// in the code you posted
for (int j = 0; j < arr.length; j++) {
System.out.print(arr[i][j]+" ");
}
System.out.println();
}
That would start from the bottom row and print out its contents from the first to last column, then move up to the second to last row, etc. all the way up to the first (top) row. So there is no inherent directionality in arrays at all, but because we are printing in the opposite order from the one used in the value assignment, the values will appear to be printed from the "bottom up." If you wanted to also invert the columns, printing the last one first, you could do this:
for (int i = arr.length - 1; i >= 0; i--) {
for (int j = arr.length - 1; j >= 0; j--) {
System.out.print(arr[i][j]+" ");
}
System.out.println();
}
I hope that explanation was clear. Best of luck~!
PS. As there is no inherent directionality in arrays, you should not necessarily be storing the values in the direction you want to print them. You should store the values in the way that makes the most sense to you and in the way that makes them easy to manage. Then whenever you need to print the values, you can print them however you like.

Try this code, but I see that you are filling the array with empty spaces, how can you realize
that your code is not working good try for example filling numbers to test your code.
for(int row = arrayName.length -1; row >= 0; row--){
for(int col = arrayName.length - 1; row >= 0; col--){
arrayName[row][col] = col;
}
}

Related

How can I populate this 2d array with values from a char array

So I have a grid that is 6 by 7
char[][] grid = new char[6][7];
And is populated with blank spaces using this loop:
for (int row = 0; row < grid.length; row++) {
for (int col = 0; col < grid[0].length; col++) {
grid[row][col] = ' ';
}
}
I also have a char[] array that holds 'A's 'B's and blank spaces. For example ch[0] = B, ch[1] = A, ch[8] = " ".
And I am simply trying to populate each slot of the 2d array 'grid' with the contents of the char array one at a time.
I tried to use the same for loop with some changes to populate the grid but when I run it only populates the top row of my grid and I'm not sure why. I have tried to move the i++, and change the for loop parameters but nothing is working and I need help. This is how I am trying to do it:
int i = 0;
for (int row = 0; row < grid.length; row++) {
for (int col = 0; col < grid[0].length; col++) {
grid[row][col] = ch[i];
i++;
}
}
If it helps to know I am getting the contents of ch[] from a .csv file and storing it in a char array. When I run this code as is, it perfectly populates the top row of my grid (first row) but then it does not do anything to the remaining rows.
I don't want to change the data types of anything, I know I can get this too work I just need some help.

Why I don't want to embed this loop in my insertion sort?

I have a class and right now we are doing insertion sort. I think my code worked properly but my professor said not to embed one of my loops (it shifts the values in my array over) and that it should be done while "searching".
public static void insertionSort(int array[]) {
int n = array.length;
for(int i = 0; i < n; i++) {
int nextIndex = i;
for(int j = 0; j < i; j++) {
if(array[nextIndex] < array[j]) {
int temp = array[nextIndex];
// ********************************
for(int k = i; k > j; k--) {
array[k]=array[k-1];
}
// ********************************
array[j]=temp;
j = i
}
}
}
}
What's wrong with the above?
I think what your professor meant is this: You are currently looking through the sorted part of your array [0..i] from bottom to top to find the position at which the new element should be inserted. Afterwards you move through your array from top to bottom to shift the new element to the right position.
Instead, you could just move the new element through the element and simultaneously look for the right position, similar to Bubblesort, if you know the algorithm. This saves you this for-loop your prof marked.

How to reverse a loop

So basically my assignment was to print a list of stars.
public class Practice_6_2
{
public static void main (String[] args)
{
final int MAX_ROWS = 10;
for (int row = 1; row <= MAX_ROWS; row++)
{
for (int star = 1; star <= row; star++)
System.out.print ("*");
System.out.println();
}
}
}
But when it prints, it is actually the opposite. How would I fix this?
Edit:
When I run the program, it will print one star on the first line, two stars on the second, and so forth until it reaches the tenth line. I need it to print ten stars on the first line, nine on the second, and so forth. Kind of reversing it.
You could reverse the direction you iterate on row. Change
for (int row = 1; row <= MAX_ROWS; row++)
to something like
for (int row = MAX_ROWS; row >= 1; row--)
to start at MAX_ROWS and descend to 1.

How would you go through each row and each column seperatly in two dimensional array

I am just curious as to how that is done. I am writing a small program to get a better understanding of two dimensional arrays. I want to know how I can go though each row and then each column separately using for loops.
Lets say I have a 2D array that is made out of different letters. I want to go through each row and each column and check if a certain letter is there. Then I want it to print how many occurrences of this letter happened in each row and then each column.
First index is row and second index is column.
Assuming that the something[][] is an something[] of something-rows (that is something[i] gives us a row, not a column - if it'S the way round, just change the examples):
public static void loopExample (String[][] someTwoDimArray) {
// Looping rows
for (var row = 0 ; row < someTwoDimArray.length ; row++) {
for (var col = 0 ; col < someTwoDimArray[0].length ; col++) {
System.out.println(someTwoDimArray[row][col]);
}
}
// looping columns
for (var col = 0 ; col < someTwoDimArray[0].length ; col++) {
for (var row = 0 ; row < someTwoDimArray.length ; row++) {
System.out.println(someTwoDimArray[row][col]);
}
}
}
I don't know if the first or second index is considered rows or columns, but this is a pretty standard nested loop for iterating over every element of a 2d array.
for(int column = 0; column < array.length(); ++column) {
for(int row = 0; row < array[column].length(); ++row) {
// do stuff to array[column][row]
}
}
Given your update, let's look for the letter 'N', in a 2d char array called myLetters.
int counter = 0;
for(int i = 0; i < myLetters.length(); ++i) {
for(int j = 0; j < myLetters[i].length(); ++j) {
if('N' == myLetters[i][j]) {
++counter;
}
}
}
System.out.println("N occurs " + counter + " times.");
if you have a 2D array if you want to access each cell you will have to use a nested for loop.
eg:
for(int i = 0; i < length1; i++)
for(int j = 0; j<length2; j++){
// do something
to format column first do array[i][j] = //do something
to format row first do array[j][i] = // do something
}
"I tried using a for loop however i dont have a good understanding of for loops and i was wondering how not just go through array in its entirety but small bits like rows and columns"
A for loop is a java control flow statement. It lets you initialize a variable (i and j) it gives you a condition (i
int i = 0
while (i < length1){
//do something
i++
}
if working with arrays for loops are almost always required.

Randomize tictactoe

A while I did an assignment creating a tictactoe program through eclipse. It works well enough, with me clicking empty boxes to place O's, and the program inputting X's afterward. However, I was using a pretty simple code for the placement of X's:
public int putX(){
for(int i=0; i<3;i++)
for(int j = 0;j<3;j++) {
if(position[i][j]==' ') {
position[i][j]='X';
return 0;
}
}
return -1; //some error occurred. This is odd. No cells were free.
}
Because of this, the X's are just placed in the row of each column, going down until the next column. Can someone show me a simple way to randomize this program?
What we want to do is generate an array of all the possible points, and pick one of those points at random. We use a for loop to iterate through all points in the 3x3 array, and add the valid ones to our temporary array, and then we choose a random index, and place an X there.
String[] list = new String[9]; // maximum 9 points
int size = 0;
for(int i = 0; i < 3; i++) {
for(int j = 0; j < 3; j++) {
if(position[i][j] == ' ') {
list[size] = "" + i + j;
size++;
}
}
}
int index = (int) (Math.random() * (size+1));
position[Integer.parseInt(list[index].charAt(0))][Integer.parseInt(list[index].charAt(1))] = 'X';
Alternatively, instead of storing the x,y coordinates of the point in a String we could store them in a java.awt.Point like so:
Point[] list = new Point[9]; // maximum 9 points
int size = 0;
for(int i = 0; i < 3; i++) {
for(int j = 0; j < 3; j++) {
if(position[i][j] == ' ') {
list[size] = new Point(i, j);
size++;
}
}
}
int index = (int) (Math.random() * (size+1));
position[list[index].getX()][list[index].getY()] = 'X';
As you can see, the code for using a Point is practically the same, but instead of parsing the coordinates out of the String, we can just access them directly from the Class.
You should also check to make sure that there are some elements left, by checking if size is still 0 after the for loop. If so, you should probably return -1 (what your existing code does). Otherwise, at the end of the whole code return 0.

Categories