Jagged array; check for column-wise value increase - java

This method is simple, there is 2D array, not a rectangle, the purpose is to check the values in each column whether they are increasing or not, if they are in an increasing order, return true, else return false.
The shape of the array is like the following, it is a Young Tableaux
{
[1,4,5,10,11],
[2,6,8],
[3,9,12],
[7]
}
The main properties of a young tableaux:
it consists of cells which are filled with integers, and arranged in
left-justified rows,
no row is longer than a preceding row,
from left to right in any row, and down any column the integers are increasing,
the set of integers used is {1, 2, . . . , n} where n is the number
of cells
How I solve it?
My approach is simple, first convert this 2D array into a rectangle matrix, if some position is empty, then filled it with 0.
Then check the column one by one, if found a error, then break, and return the result.
It works, I just wonder if there is a better apporach for this.
public static boolean columnValuesIncrease(int[][] t) {
//How many columns are there?
int columnCounts = t[0].length;
int rowCounts = t.length;
//create a rectangle matrix, fill 0 when outIndex
int[][] addZero = new int[rowCounts][columnCounts];
for (int row = 0; row < rowCounts; row++) {
for (int col = 0; col < t[0].length; col++) {
try {
addZero[row][col] = t[row][col];
} catch (IndexOutOfBoundsException e) {
addZero[row][col] = 0;
}
}
}
//Let's check the damn column!
boolean mark = true;
myLoop:
for (int col = 0; col < columnCounts; col++) {
for (int row = 0; row < rowCounts; row++) {
if (row + 1 < rowCounts && col + 1 < columnCounts) {
if (addZero[row + 1][col] != 0) {
mark = addZero[row][col] <
addZero[row + 1][col] ? true : false;
}
}
if (!mark) {
break myLoop;
}
}
}
return mark;
}

This approach takes a row. It considers 'this' row and the one after it. It considers N number of columns, where N is the minimum of the number of columns in this row and the row after. In math, if R is the number of rows in this 2D matrix, take some r1: r1 ∈ [0, R) and r2 = r1 + 1. Then, N = min{num_cols(r1), num_cols(r2)}.
In column n, where n ∈ [0, N], if the value at the column in the next row happens to be smaller than the value in the preceding row, it returns false. If everything else worked, it returns true.
public static boolean columnValuesIncrease(int[][] t) {
for(int i = 0 ; i < t.length - 1 ; i++)
for(int j = 0 ; j < Math.min(t[i].length, t[i+1].length) ; j++)
if(t[i][j] > t[i+1][j])
return false;
return true;
}

Related

How can I print an multidimensional array element by specifying the array position with an index?

I'm trying to print an element of a 2D array by designating it's location with an index. Say, I want to print location 3 which would be String[1][0] for my array.
String[][] fruit = new String[2][2];
fruit[0][0] = "apple"; //position 1
fruit[0][1] = "banana"; //position 2
fruit[1][0] = "pear"; //position 3
fruit[1][1] = "melon"; //position 4
I would like to call fruit[1][0] position 3 so when I ask to print "position 3" it gives me "pear".
What you're looking for is obviously the literal position of a cell since arrays start from an index value of 0. You also need to keep in mind that a 2D Array can possibly have different number of columns for any given row. The first and second rows for example may have 4 columns, the fifth row might have 6 columns, and the sixth, seventh row may have 4 columns again. Unless you know for sure that all columns within the Array are indeed fixed to a specific length (a "square" 2D Array), I can't see an advantage to this scheme.
Never the less, this can be easily done with two for loops (one nested within the other), for example:
String[][] array = {
{"cell 1", "cell 2"}, // Row 1 (index 0)
{"cell 3", "cell 4", "cell 5"}, // Row 2 (index 1)
{"cell 6", "cell 7"}}; // Row 3 (index 2)
int yourDesiredCell = 5;
int cellCount = 0;
boolean found = false;
for (int i = 0; i < array.length; i++) {
for (int j = 0; j < array[i].length; j++) {
cellCount++;
if (cellCount == yourDesiredCell) {
System.out.println(array[i][j]);
found = true;
break;
//return array[i][j];
}
}
if (found) {
break;
}
}
You could also place this into a class method, for example:
public static String getCellData(String[][] array, int yourDesiredCell) {
int cellCount = 0;
for (int i = 0; i < array.length; i++) {
for (int j = 0; j < array[i].length; j++) {
cellCount++;
if (cellCount == yourDesiredCell) {
return array[i][j];
}
}
}
return null;
}
Another method that could be handy is retrieving the total number of actual cells contained within the 2D Array (if you don't already know):
public static int getTotalCellCount(String[][] array) {
int cellCount = 0;
for (int i = 0; i < array.length; i++) {
for (int j = 0; j < array[i].length; j++) {
cellCount++;
}
}
return cellCount;
}
What I got from your question was that there is a multi-dimensional array A of size say nxm where n is number of rows and'mis number of columns. You want to get let say 1st element which will beA[0][0], but you don't know how to convert 1` into indices for the array.
Lets do this for a 2d array A of size nxm, then you can extend it to 3d etc too. Remember that each A[i] is an array of'melements, hence the position of row where the element isx/m, i=x/m. No need to make it 0-indexed because the integer division of java does that for you. If i>=n`, then we should say element is not present.
Now you have to decide the position of the element in m elements. Hence j or position of the column is x%m. This will give you index b/w 0 and m-1 which is correct range of j, but for an element in the first place it should give 0, but it's giving 1. Hence it js not 0-indexed. So j= x%m -1 but for (m-1)th element its giving
-1 as x would be divisible by m or x%m=0. So use ternary operator here, j = x%m-1 < 0 ? m-1 : x%m-1.
i = x/m ;
if(i<n){
j = x%m -1 < 0 ? m-1 : x%m -1 ;
}else{
System.out.println("Element " +m+" does not exist") ;
}
I would like to suggest another approach with a time complexity O(n).
public String getByPosition(int pos,String[][] mulArr){
int row,col;
int temp = pos;
while(temp % mulArr.length != 0)temp++;
row = (temp / mulArr.length) - 1;
col = ((pos % mulArr[0].length) - 1 < 0) ? mulArr[0].length - 1 : (pos % mulArr[0].length) - 1;
return mulArr[row][col];
}

Java - find consecutive elements in 2D array

I'm having trouble with an algorithm, suppose the following:
A cinema has n rows, each row consists of m seats (n and m do not exceed 20). A two-dimensional matrix stores the information on the sold tickets, number 1 means that the ticket for this place is already sold, the number 0 means that the place is available. You want to buy k tickets to the neighboring seats in the same row. Find whether it can be done.
Input data
On the input, the program gets the number of n rows and m seats. Then, there are n lines, each containing m numbers (0 or 1) separated by spaces. The last line contains a number k.
Output data
The program should output the number of the row with k consecutive available seats. If there are several rows with k available seats, output the first row with these seats. If there is no such a row, output the number 0.
Code
import java.util.Scanner;
class Main {
static int findRowWithAvailableSeat(int[][] matrix, int tickets) {
final int rows = matrix.length;
final int columns = matrix[0].length;
int seatCounter = 0;
for (int r = 1; r <= rows; r++) {
for (int c = 1; c <= columns; c++) {
if (matrix[r][c] == 1) {
continue;
} if (matrix[r][c] == matrix[r][c + 1]) {
seatCounter++;
if (seatCounter == tickets) {
return r;
}
}
}
}
return 0;
}
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
int rows = scanner.nextInt();
int columns = scanner.nextInt();
int[][] matrix = new int[rows][columns];
for (int r = 0; r < rows; r++) {
for (int c = 0; c < columns; c++) {
matrix[r][c] = scanner.nextInt();
}
}
int kTickets = scanner.nextInt();
int rowWithAvailableSeats = findRowWithAvailableSeat(matrix, kTickets);
System.out.println(rowWithAvailableSeats);
}
}
I know the problem is somewhere in findRowWithAvailableSeat method. I would like a hint on how to solve the problem, not the actual solution. Thank you very much.
EDIT
I could finally solve it (or at least it works as intended, I'm not sure if it's the best implementation). Thanks you all for your tips.
static int findRowWithAvailableSeat(int[][] matrix, int tickets) {
final int rows = matrix.length;
final int columns = matrix[0].length;
int seatCounter;
for (int r = 0; r < rows; r++) {
seatCounter = 0;
for (int c = 0; c < columns; c++) {
if (matrix[r][c] == 1) {
seatCounter = 0;
continue;
}
if (matrix[r][c] == 0) {
seatCounter++;
if (seatCounter == tickets) {
return r + 1;
}
}
}
}
return 0;
}
Here are the 4 tips you need:
Don't compare matrix[r][c] == matrix[r][c + 1]. Plainly compare to 0:
matrix[r][c] == 0. To avoid ArrayIndexOutOfBoundsException
As DarkSigma already pointed, start your loops iterator from 0, not 1: for (int r = 0; r < rows...
Re-init your seatCounter to 0 for each row.
And! When you print out System.out.println(rowWithAvailableSeats), remember that row counting starts from 0.
Hope this helps
on main() method, you set matrix from index 0 to rows-1, and from index 0 to columns-1. But on findRowWithAvailableSeat(), you start from index 1. So index 0 will never be accessed.
} if (matrix[r][c] == matrix[r][c + 1]) { this line will try to access index c+1, will result index out of bound exception. either you need to check whether or not c+1 is less than column size or compare matrix[r][c] with 0 (matrix[r][c] == 0).
if you looking for neighboring seats, then you need to reset the seatCounter when you visit the sold seat (matrix[r][c] == 1)
you also need to reset seatCounter for each row.
I would put each row in a string and all rows in a string array a[m], then do a[i].contains(k) on each row:
"1001101110100010110010".contains("000")
Your for loops start at 1 instead of 0
for (int r = 1; r <= rows; r++) {
for (int c = 1; c <= columns; c++) {
if (matrix[r][c] == 1) {
The first index of the matrix array is being skipped. So you're not checking the first row and the first seat of each row.
Also, seatCounter is not being reset for each row. It currently retains any seats counted from previous rows.
I'm also not sure what this is for
if (matrix[r][c] == matrix[r][c + 1])

How to traverse through 2d array and count how many elements are greater than 1 in each row in row major order

I'm writing a method that traverses through a 2d array in row-major order and at the start of each row, I initialize a count variable to zero. In the inner loop, if a value is non-zero I increment the count variable. At the end of the row, if the count variable is not exactly equal to 1, return false. Ive been working on this for about 2 weeks and can't find my error. Please point me in the right direction.
** Don't mind the print statements I'm trying to see how much the count is and my code only seems to hit the second row of the array
public static boolean isGPM(int[][] matrix) {
int count =0;
for (int row = 0; row < matrix.length; row++) {
count =0;
for (int col = 0; col < matrix[row].length; col++) {
if (matrix[row][col] > 0) {
count++;
}
else {
return !gpm;
}
}
}
System.out.println(count);
return gpm;
}
If I understand you correctly, you only care about the per-row count. This should work:
int count = 0;
// Process each row...
for (int row = 0; row < matrix.length; row++) {
count = 0;
// Process each column...
for (int col = 0; col < matrix[row].length; col++) {
// Check the cell.
if (matrix[row][col] != 0) {
count++;
}
}
// Row processing complete. Check count.
if (count != 1) {
System.out.println(count);
return gpm;
}
}

How can i test to see if the row is even in a 2d array?

I'm trying to test each row in my array to see if they are even or odd. If the row is even i want to change the random value in the elements of the row to 0. If the row is odd i want to change the elements to 1. Ive been able to create the element and print it out but im stuck on how to test the rows. I know to test if a number is even you use (i % 2 == 0) but im not sure what coding i should use.
public static void main(String[] args) {
int[][] box;
box = new int[2][2];
int row;
int column;
for (row = 0; row < box.length; row++) {
for (column = 0; column < box[row].length; column++) {
box[row][column] = (int) (Math.random() * 100);
}
}
//where im having issues
// i get error 'bad operand types for binary operator'
if (box[row] % 2 == 0) {
for (row = 0; row< box.length;row++){
box[row][column] = [0][];
}
}
else{
for(row = 0; row < box.length; row++){
box[row][column] = [1][];
}
}
for (row = 0; row < box.length; row++) {
for (column = 0; column < box[row].length; column++) {
System.out.print(box[row][column] + " ");
}
System.out.println();
}
}
}
you can use Arrays built in function fill(int[],value) that takes two argument, First 1d array and second a value to fill
//also if you are checking is row is even or odd divide row not box[row]
if (row % 2 == 0) {
Arrays.fill(box[row],0);//set 0 to every element in this wor
}
else{
Arrays.fill(box[row],1);//set 1 to every element in this wor
}

How to check if a 2D array is diagonally dominant in Java

Hey guys i want to make a function which checks a 2D array whether is diagonallydominant or not
Any Ideas??
I have managed to find the diagonall but how to check if diagonally dominant??
public static int arraySum(int[][] array){
int total = 0;
for (int row = 0; row < array.length; row++)
{
total += array[row][row];
}
return total;
}
According to Wikipedia, a diagonally dominant matrix is a matrix such that:
for every row of the matrix, the magnitude of the diagonal entry in a row is larger than or equal to the sum of the magnitudes of all the other (non-diagonal) entries in that row.
This just checks for weak diagonal dominance, given a 2D array:
public boolean isDiagonallyDominant(int[][] array) {
int otherTotal = 0;
// Loop through every row in the array
for(int row = 0; row < array.length; row++) {
otherTotal = 0;
// Loop through every element in the row
for(int column = 0; column < array[row].length; column++) {
// If this element is NOT on the diagonal
if(column != row) {
// Add it to the running total
otherTotal += Math.abs(array[row][column]);
}
}
// If this diagonal element is LESS than the sum of the other ones...
if(Math.abs(array[row][row]) < otherTotal) {
// then the array isn't diagonally dominant and we can return.
return false;
}
}
return true;
}
In theory: in the i-th row, check that the i-th entry is smaller than the sum of the absolute values of the other values of the row:
public boolean checkDominance(int[][] matrix)
{
for (int i = 0; i < matrix.length; ++i)
{
int diagEl = Math.abs(matrix[i][i]);
int sum = 0;
for (int j = 0; j < matrix[0].lenght; ++j)
{
if (i == j) { continue; }
sum += Math.abs(matrix[i][j]);
}
if (sum > diagEl) { return (false); }
}
return (true);
}

Categories

Resources