Shifting a 2D array to the left loop - java

I have a 2D array with values in it. Example below:
010101
101010
010101
I want to create a loop that shifts these values to the left like the example below.
101010
010101
101010
So the element that "falls off" goes back in to the end. I'm having a hard time solving this issue in code.
Anyone got any advice?
So far I have made it scroll but I have no clue how to get the elements that fall off to go back in.
This is what I have so far.
for (int row = 0; row < array.length; row++) {
for (int col = 0; col < array[row].length; col++) {
if (!(row >= array.length) && !(col >= array[row].length - 1)) {
array[row][col] = array[row][col + 1];
}
}
}

Try using the modulus operator:
arrayShifted[row][col] = array[row][(col + 1) % array[row].length];
Remove your condition check as well. Also note, to avoid overwriting values, you'll need to store the results in a new array.
for (int row = 0; row < array.length; row++) {
for (int col = 0; col < array[row].length; col++) {
arrayShifted[row][col] = array[row][(col + 1) % array[row].length]
}
}

Here is a full method that takes in a variable amount of spots to shift each row and properly handles copying the same elements as in the modulus approach.
public void shiftArray(int[][] array, int shift) {
for (int row = 0; row < array.length; row++) {
int rowLength = array[row].length;
// keep shift within bounds of the array
shift = shift % rowLength;
// copy out elements that will "fall off"
int[] tmp = new int[shift];
for (int i = 0; i < shift; i++) {
tmp[i] = array[row][i];
}
// shift like normal
for (int col = 0; col < rowLength - shift; col++) {
array[row][col] = array[row][col + shift];
}
// copy back the "fallen off" elements
for (int i = 0; i < shift; i++) {
array[row][i + (rowLength - shift)] = tmp[i];
}
}
}
Test Run
int[][] array = new int[][] {
{0,1,0,1,0,1},
{1,0,1,0,1,0},
{0,1,0,1,0,1}
};
shiftArray(array, 1);
for (int[] row : array) {
for (int col : row) {
System.out.print(col);
}
System.out.println();
}
// 101010
// 010101
// 101010

Related

Understanding the logic of a increase max element by 1 method

The duty of this method is to increment or add 1 to, the largest element in the array arr. If the same largest element is present more than once in the array, the last occurrence should be incremented. ("Last" means the one in the row with the largest subscript, and the one with the largest column subscript if there is more than one occurrence of the largest element in that row.) The method should not do any unnecessary work or computation. Note that the array's rows may have different numbers of elements.
Solution:
public static void incrMax(int[][] arr) {
int maxRow = 0;
int maxCol = 0;
boolean found = false;
for(int row = 0; row < arr.length; row++) {
for(int col = 0; col < arr[row].length; col++) {
if(!found || arr[row][col] >= arr[maxRow][maxCol] {
maxRow = row;
maxCol = col;
found = true;
}
if(found) {
arr[maxRow][maxCol] += 1;
}
}
}
}
What I understand is that we would want to create two int's to store the maximum elements for horizontal rows and vertical columns. In order to seek those values out we need to loop the 2D-array. I am particularly confused by nested for-loops and 2d arrays. And the line:
if(!found || arr[row][col] >= arr[maxRow][maxCol]
Can someone please walk through the logic of this code?
Thank you
void increment(int[][] mat) {
//increment the max of every row by one
for (int i = 0; i < mat.length; i++) {
int maxRow = 0, maxIndex = -1;
for (int j = 0; j < mat[i].length; j++) {
if (maxRow <= mat[i][j]) { // to allow multiple occurences of the same value i used <=
maxRow = mat[i][j];
maxIndex = j;
}
}
//we check if a max is found
if (maxIndex != -1) {
mat[i][maxIndex]++;
}
}
}
this will do the work you are asking for

Printing ragged array column by column

Given an array of integers with rows of different lengths, is it possible to print the whole two-dimensional array but doing so column by column? I understand how to do it row by row but I am struggling with this.
int[][] a = new int[5][];
a[0] = new int[4];
a[1] = new int[2];
a[2] = new int[5];
a[3] = new int[3];
a[4] = new int[1];
int longestRowLength = a[0].length;
for(i = 1; i < a.length; i++)
{
if(a[i].length > longestRowLength)
longestRowLength = a[i].length;
}
for(i = 0; i < a.length; i++)
{
for(j = 0; j < a[i].length; j++)
{
a[i][j] = rand.nextInt(10);
System.out.print(a[i][j]);
}
System.out.println();
}
for(j = 0; j < longestRowLength; j++)
{
for(i = 0; i < a.length; i++)
{
if(a[i].length < longestRowLength)
continue;
System.out.print(a[i][j]);
}
}
}
I have done this but the issue is with how to recognize we are going out of bounds with one of the arrays. My if(a[i].length < longestRowLength doesn't work as it will not even print any numbers if its length is not the longest ones. How can I achieve this?
EDIT:
Ok I have changed that line to:
if(longestRowLength - a[i].length > 0 && (j+1) > a[i].length)
continue;
System.out.print(a[i][j]);
Now it works but it prints the columns as rows. Is there anyway to make it print column by column but to make it print just like it would with rows? (P.S. yeah the first condition of the if statement is unecessary).
Replace your last loop with:
for(j = 0; j < longestRowLength; j++)
{
for(i = 0; i < a.length; i++)
{
if(a[i].length <= j)
continue;
System.out.print(a[i][j]);
}
System.out.println();
}
Prints the columns one by one.
Instead of:
if(a[i].length <= j)
continue;
you can do:
if(a[i].length <= j) {
System.out.print(' ');
continue;
}
to leave a space for arrays which are too short. This way you print the transposed “jagged” matrix.

Adding Elements of an Array (sum of rows and columns)

I'm looking for a way to add up the elements of the rows of an array and get that sum. I have to get the column's sum as well.
The array looks something like this:
{{45.24, 54.67, 32.55, 25.61},
{65.29, 49.75, 32.08, 26.11},
{25.24, 54.33, 34.55, 28.16}};
For example, I would add 45.24, 65.29, and 25.24 to get the sum of that part of the columns. I would then have to add the other 3 columns up as well.
Same goes for the rows.
I keep getting errors concerning the variable types. Is there a way to do this? Thanks.
The logic Would be --->
for(i = 0; i < columns; i++)
{
for(j=0; j<rows; j++)
{
sum+=arr[j][i];
}
}
Opposite for Columns
I think you should define the type of numbers your array will handle, if I use float numbers I can have some code like the class bellow to do the type of operations you are asked for. You can also add some decimal formatting.
public class Test {
public static void main(String[] args) {
new Test();
}
public Test() {
float myarray[][]= {
{45.24f, 54.67f, 32.55f, 25.61f},
{65.29f, 49.75f, 32.08f, 26.11f},
{25.24f, 54.33f, 34.55f, 28.16f}
};
float row[] = new float[3];
float column[] = new float[4];
for (int i=0; i < 3; i++) {
float rowvalue = 0f;
for (int j=0; j < 4; j++) {
System.out.print(myarray[i][j]+" ");
rowvalue+=myarray[i][j];
}
row[i]=rowvalue;
System.out.println("");
}
System.out.println("");
for (int i=0; i < 4; i++) {
float colvalue = 0f;
for (int j=0; j < 3; j++) {
System.out.print(myarray[j][i]+" ");
colvalue+=myarray[j][i];
}
column[i]=colvalue;
System.out.println("");
}
System.out.println("Rows answer:");
for (int i=0; i < 3; i++) {
System.out.println(row[i]);
}
System.out.println("Columns answer:");
for (int i=0; i < 4; i++) {
System.out.println(column[i]);
}
}
}
Suppose you have nxn matrix. The idea is to identify the pattern.
Row values
i j
0 0
0 1
0 2
Column values
i j
0 0
1 0
2 0
The position of i and j values is reversed.
Let's assume we have an array a[][]. The logic would be:
for (int i=0; i<n; i++) {
int row = 0, col = 0;
for (int j=0; j<n; j++) {
row += a[i][j];
col += a[j][i];
}
System.out.println("row" + i + " = " + row);
System.out.println("col" + i + " = " + col);
}
I assumed you wanted the sum of each row and column separately. You can modify it accordingly.

Big O notation O(NM) or (N^2)

I've been told the below code is = O(MN) however, I come up with O(N^2). Which is the correct answer and why?
My thought process:
nested for loops plus if statements --> (O(N^2)+O(1)) + (O(N^2)+O(1)) = O(N^2)
Thank you
public static void zeroOut(int[][] matrix) {
int[] row = new int[matrix.length];
int[] column = new int[matrix[0].length];
// Store the row and column index with value 0
for (int i = 0; i < matrix.length; i++)
{
for (int j = 0; j < matrix[0].length;j++) {
if (matrix[i][j] == 0)
{
row[i] = 1;
column[j] = 1;
}
}
}
// Set arr[i][j] to 0 if either row i or column j has a 0
for (int i = 0; i < matrix.length; i++)
{
for (int j = 0; j < matrix[0].length; j++)
{
if ((row[i] == 1 || column[j] == 1)){
matrix[i][j] = 0;
}
}
}
}
What does M and N refers to? My assumption is that it refers to "rows" and "columns" respectively. If it is so, then the equation is O(MN) because you loop through M number of N times.
O(N^2) will be correct IF rows and columns are equal.

Fill double array with random numbers and then print even and odd numbers from that array

So here's my problem. I have to write a program that will fill array with random numbers(and it's ok), then it's necessary to print only even index numbers or only odd value numbers(j). Tried like this but when i put if statement and it shows every even number (index and value-the second in array) so it wrong. What should i do so?
import java.util.Random;
public class Array {
public static void main(String[] args)
{
int rows = 5;
int colu = 2;
Random r = new Random();
int [][] array = new int [rows][colu];
for(int row = 0; row < array.length; row++)
{
for(int col = 0; col < array[row].length; col++)
{
array[row][col] = r.nextInt(10);
}
}
for(int i = 0; i < array.length; i++)
{
for(int j = 0; j < array[i].length; j++)
{
if(array[i][j]%2 == 0){
System.out.print(array[i][j] + " ");
}
}
}
System.out.println();
}
}
Thanks
I'm going to take a stab at this but I'm not sure if I quite understand yet.
int array[][] = new int[row][col];
// ... populate the array with random numbers, works fine...
// Let's traverse the first column.
for (int i = 0; i < row; i++) {
int value = array[i][0]; // col 0 means first column
if (value % 2 == 0) {
// ...
}
}
// Let's traverse the second column.
for (int i = 0; i < row; i++) {
int value = array[i][1]; // col 1 means second column
// ...
}
Is this what you mean? If it is, do you see the pattern and how you could generalize this and make the code a bit smaller?
Just implement this formula in your "if" statement :
(Number × 2 )/4 ==0. You will always get even numbers. You can handle the rest :D

Categories