Understanding 2D Arrays in Java - java

I'm trying to figure out how to loop through all of the elements of a 2D array. I am given a 2D rectangular array of chars (someChars). I am tasked with writing a looping statement that will calculate and print the number of 'x''s in the rectangle.
int x;
for (int r = 0; r < someChars.length; r++)
for (int c = 0; c < someChars[r].length; c++)
if(someChars.charAt(r) = "x"){
x++;}
if(someChar.charAt(c) = "x"){
x++;}
System.out.println(x);
I'm having trouble figuring out how to reference all of the variables within the array, and I don't really understand the significance/where the [bracketed] integers should be in reference to the whole thing.
p.s. I think it's abundantly obvious that this is a homework problem. Even if someone were to hand me the answer, it's worth a single point out of approximately 700 total. I'm much more interested in understanding how it works than mining for an easy answer.

If you're given a 2d array of chars then it will be declared as:
char[][] someChars;
This means you reference a particular value as (for example) someChars[1][2]. To check if that character is an 'x' then the expression would be: someChars[r][c] == 'x'.
Other suggestions:
give your variables sensible names like xCount
initialise your variables so it's clear what they are int xCount = 0;
put { and } around the blocks following for
indent
Hopefully that will get you started.

Related

why do my averages not print out the way they're supposed to? [duplicate]

for (int i = 0; i < reports.length; i++) {
Products[] products = reports[i].getDecisions;
for (int j = 0; j < products.length; j++) {
}
}
Here I want to index the inner for loop starting from 1 , but it is not working as expected, I also changed the j
Java arrays are always 0-based. You can't change that behavior. You can fill or use it from another index, but you can't change the base index.
It's defined in JLS §10.4, if you are interested in it.
A component of an array is accessed by an array access expression (§15.13) that consists of an expression whose value is an array reference followed by an indexing expression enclosed by [ and ], as in A[i].
All arrays are 0-origin. An array with length n can be indexed by the integers 0 to n-1.
You can't do that as array index in Java starts from 0.
But you can access array with index 1 with little modifications.
Example:
Consider an integer array "a" with length n
for(int i=0;i<n;i++) {
System.out.println(a[i]);
}
This can be modified as:
int a[] = new int[n+1];
for(int i=1;i<n+1;i++) {
System.out.println(a[i]);
}
Just like in most languages arrays are indexed from 0. You better get used to it, there is no workaround.
Base Index of Java arrays is always 0. It cannot be changed to 1.
You can use pointers, to jump to a certain point of the array and start the array from there.
For example:
char str[20];
str={'H', 'E' ,'L' ,'L', 'O','W' ,'O ','R','L',' D'};
char *ptr;
*ptr=str[0];
//right now its pointing to the starting.
ptr=ptr+3;
//Now pointing at 3rd unit.
This doesn't work in every compiler.This is the closest thing that can be done for your question.
its all simple that in C , C++ , Java or etc.. the array index start from "0" only. and we can't change it. but sometimes in some Practice problems we are asked to use 1-indexed-based array, which we actually can't do that, so to tackle that, just leave 0th-index aside, and start using the array from 1th-index onwards, and while solving the situation always keep in mind that we have to never include or use that 0th-index in our operations.

How I can index the array starting from 1 instead of zero?

for (int i = 0; i < reports.length; i++) {
Products[] products = reports[i].getDecisions;
for (int j = 0; j < products.length; j++) {
}
}
Here I want to index the inner for loop starting from 1 , but it is not working as expected, I also changed the j
Java arrays are always 0-based. You can't change that behavior. You can fill or use it from another index, but you can't change the base index.
It's defined in JLS §10.4, if you are interested in it.
A component of an array is accessed by an array access expression (§15.13) that consists of an expression whose value is an array reference followed by an indexing expression enclosed by [ and ], as in A[i].
All arrays are 0-origin. An array with length n can be indexed by the integers 0 to n-1.
You can't do that as array index in Java starts from 0.
But you can access array with index 1 with little modifications.
Example:
Consider an integer array "a" with length n
for(int i=0;i<n;i++) {
System.out.println(a[i]);
}
This can be modified as:
int a[] = new int[n+1];
for(int i=1;i<n+1;i++) {
System.out.println(a[i]);
}
Just like in most languages arrays are indexed from 0. You better get used to it, there is no workaround.
Base Index of Java arrays is always 0. It cannot be changed to 1.
You can use pointers, to jump to a certain point of the array and start the array from there.
For example:
char str[20];
str={'H', 'E' ,'L' ,'L', 'O','W' ,'O ','R','L',' D'};
char *ptr;
*ptr=str[0];
//right now its pointing to the starting.
ptr=ptr+3;
//Now pointing at 3rd unit.
This doesn't work in every compiler.This is the closest thing that can be done for your question.
its all simple that in C , C++ , Java or etc.. the array index start from "0" only. and we can't change it. but sometimes in some Practice problems we are asked to use 1-indexed-based array, which we actually can't do that, so to tackle that, just leave 0th-index aside, and start using the array from 1th-index onwards, and while solving the situation always keep in mind that we have to never include or use that 0th-index in our operations.

Transpose matrix stored in a 1-dimensional array without using extra memory [duplicate]

This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
In-place transposition of a matrix
Recently attended an Technical Written Interview. Came through the following question.
I have an array as say
testArray = {a1,a2,a3,...an,b1,b2,b3,....bn,c1,c2,c3,.....,cn}
I need to sort this array as `
testArray = {a1,b1,c1,a2,b2,c2,a3,b3,c3,.....,an,bn,cn}
Constraint is I should not use extra memory, should not use any inbuilt function.
Should write complete code, it can be in any language and can also use any data structure.
eg:
Input: {1,2,3,4,5,6,7,8,9}, n = 3
Output: {1,4,7,2,5,8,3,6,9}
I could not get any solution within the constraint, can anyone provide solution or suggestion?
This is just a matrix transpose operation. And there is even a problem and solution for in-place matrix transposition on Wikipedia.
No extra space is impossible, since you need to at least go through the array. O(1) additional memory is possible, with heavy penalty on the time complexity.
The solution is built on follow-the-cycle algorithm in the Wikipedia page: for each cell, we will find the cell with the smallest index in the cycle. If the cell with the smallest index is greater than or equal (>=) to the index of the current cell, we will perform chain swapping. Otherwise, we ignore the cell, since it has been swapped correctly. The (loosely analyzed) upper bound on time complexity can go as high as O((MN)2) (we go through M * N cells, and the cycle can only be as long as the total number of cells).
Impossibility
It is impossible to implement this algorithm without extra use of memory and an arbitrary length because you need a an iterator to traverse the list and that takes up space.
Finding the right indices to swap
For fixed lengths of the array and fixed n you can use a matrix transpose algorithm.
and in order to swap the elements y
The algorithm you are looking for is a matrix transpose algorithm.
so you have to swap every element exactly once iterating through it.
http://en.wikipedia.org/wiki/Transpose
basically you have to swap the m -th element in the n - th component with the n - th element in the m -th component. This can be done by a double loop.
m = length(array)/n;
for (i = 0; i < m; i++)
for (j = 0; j < n; j++)
{
index_1 = i * m + j;
index_2 = j * m + i
swap(index_1, index_2);
}
Note: For fixed m and n this loop can be completely unrolled and therefore m, i, j can be replaced by a constant.
Swaping without Memory consumption
In order to swap every element without using extra space you can use the XOR swap algorithm as pointed out in the comments:
X := X XOR Y
Y := Y XOR X
X := X XOR Y
The simplest way to swap two numbers (a and b) without using a temporary variable is like this:
b = b + a;
a = b - a;
b = b - a;
If you write that in a function, then you're part of the way there. How you keep track of which variable to swap within the arrays without using a temporary variable eludes me right now.
Bear in mind voters: he doesn't actually need to sort the array, just swap the right values.
Edit: this will work with large values in Java (and in C/C++ unless you turn on some very aggressive compiler optimisations - the behaviour is undefined but defaults to sane). The values will just wrap around.
Second edit - some (rather untested) code to flip the array around, with I think 4 integers over the memory limit. It's while technically massively unthreadsafe, but it would be parallelisable just because you only access each array location once at most:
static int[] a = {1,2,3,4,
5,6,7,8,
9,10,11,12,
13,14,15,16};
static int n = 4;
public static void main(String[] args)
{
for(int i = 0; i < a.length/n; i++) // 1 integer
for(int j = 0; j < n; j++) // 1 integer
if(j > i)
swap(i*n+j, j*n+i);
}
static void swap(int aPos, int bPos) // 2 integers
{
if(a[aPos] != a[bPos])
{
a[bPos] = a[aPos] + a[bPos];
a[aPos] = a[bPos] - a[aPos];
a[bPos] = a[bPos] - a[aPos];
}
}
Apologies if this misunderstands the question; I read it carefully and couldn't work out what was needed other than this.
Take a look at Quicksort algorithm
For more information about available algorithms, go to Sorting algorithm page.

Sparse Matrix multiplication in Java

Hello I know there are a lot of questions on sparse matrix multiplication, but many of the answers say to just use libraries. I want to do it without using library functions. So far I've done the easy part, getting my matrices into the form of
element array
column array
row array.
What I need help with is the logic portion. If matrix A is M*N and matrix B is N*P, how do I do this? I considered iterating over the elements in matrix A and checking if it's rowA== colB, and if so if colA==rowB and if that's true then multiply. I currently know my version is wrong, but I can't think of a way to make it right.
for(int i = 0; i < rows; i++)
{
sum = 0;
for(int k = 0; k < cols; k++)
if (row_values.get(i) == col_valuesb.get(k))
if (col_values.get(i) == row_valuesb.get(k))
{
sum += (short) (elements.get(i)*elementsb.get(k));
}
elementsc.add(sum);
row_valuesc.add(row_values.get(i));
col_valuesc.add(col_values.get(k));
}
You said:
"I considered iterating over the elements in matrix A and checking if it's rowA== colB, >and if so if colA==rowB"
Well, since two matrices are, by definition, able to multiply if and only if colA==rowB, then shouldn't you modify
if (row_values.get(i) == col_valuesb.get(k)){
if (col_values.get(i) == row_valuesb.get(k))
{
and just make it
if (row_values.get(i) == col_valuesb.get(k)){
instead?

Java double[][] Issue

I'm doing the following on my code:
double[][] temp=new double[0][2];
The program will run with no runtime exceptions. When I get the length of the temp like this temp.length it returns 0 and when I tried accessing the length of the inner arrays like this temp[0].length it always throws an ArrayIndexOutOfBoundsException. (That was only a test.)
Now I am wondering, Java did create a array with 0 length and at the same time an inner array with a length of 2 in an array with 0 length?
Did this kind of declaration has implications on memory management?
Will it develop complications on the coding and running the code?
Did Java really permit this kind of declaration?
In what sense did they permit this kind of declaration or did they just overlook this kind of situation?
And if they permit this declaration does it also has some special uses?
I was just exploring the possibility of doing this kind of declaration and had been questioning myself if this is really permissible.
Your opinions are gladly appreciated.
It is equivalent to
double[][] temp = new double[0][]; // a zero length array of double[]
for(int d=0; d<0; d++)
temp[d] = new double[2]; // whose each element is a new double[2]
of course the loop isn't executed, so there's no waste from "inner array"
see 15.10.1 Run-time Evaluation of Array Creation Expressions (JLS 3 - CHAPTER 15 Expressions)
If an array creation expression
contains N DimExpr expressions, then
it effectively executes a set of
nested loops of depth N-1 to create
the implied arrays of arrays. For
example, the declaration:
float[][] matrix = new float[3][3];
is equivalent in behavior to:
float[][] matrix = new float[3][];
for (int d = 0; d < matrix.length; d++)
matrix[d] = new float[3];
,so
double[][] temp=new double[0][2];
will be equivalent to
double[][] matrix = new double[0][];
for (int d = 0; d < 0; d++)
matrix[d] = new double[2];//would newer hepened
The only valid scenario ,I can think of is where you want to send and empty 2 dimensional array.
double[][] temp = new double[0][0];
return temp;
The above is a valid requirement in many matrix calculations.
Did this kind of declaration has
implications on memory management?
Not sure. And might also depends on the JVM to JVM implementations.
Will it develop complications on the
coding and running the code?
It should not if you are accessing the array in a loop like this
for(int i = 0; i<temp.length;i++)
for(int j=0; j<temp[i].length;j++)
{
// your code
}
Otherwise if you are accessing directly by using index then you should first check the index bounds.
Did Java really permit this kind of
declaration?
Yes. As I have said in the first statement.
In what sense did they permit this
kind of declaration or did they just
overlook this kind of situation?
As said before: A valid scenario is where you want to send and empty 2 dimensional array
There might be other scenarios.
And if they permit this declaration
does it also has some special uses?
Other than the my last answer I am not sure of any other scenario. But would love to know if they exist.

Categories