for (int i = 0 ; i < size; i++)
for(int j = 0 ; j < size ; j++)
{
if ( arr[i][j] == 88)
{
`save this 2 indexes`
break;
}
}
Answer from Ofer on Stack Overflowfor (int i = 0 ; i < size; i++)
for(int j = 0 ; j < size ; j++)
{
if ( arr[i][j] == 88)
{
`save this 2 indexes`
break;
}
}
If they are not sorted, you will have to loop through all indexes [using double loop] and check if it is a match.
int[][] arr = {{41, 44, 51, 71, 63, 1}, {7, 88, 31, 95, 9, 6}, {88, 99, 6, 5, 77, 4}};
for (int i = 0; i < arr.length; i++) {
for (int j = 0; j < arr[i].length; j++) {
if (arr[i][j] == 88) {
System.out.println("i=" + i + " j=" + j);
}
}
}
will result in:
i=1 j=1
i=2 j=0
By converting your 2D Array int[][] to List<List<Integer>>, you can take advantage of indexOf to find the index of your max:
List<List<Integer>> triangle = new ArrayList<List<Integer>>();
triangle.add(Arrays.asList(75));
triangle.add(Arrays.asList(95, 64));
for (List<Integer> row : triangle) {
// you can also ask for row.indexOf(max);
System.out.println("At row: " + triangle.indexOf(row) + " is: " + row.indexOf(64));
}
I might be mistaken but wouldn't the index be the j variable?
Since you are looping over the array with first loop, i will contain the index of current array (relative to the parent array).
But second loop iterates over the child arrays, so the index of your element will be the j.
int[][] triangle = {
{75},
{95,64}
};
for (int i = 0; i < array.length - 1; i++) {
for (int j = 0; j < array[i].length; j++) {
// notice we use j variable to access the item, since it contains the index for current
int item = array[i][j];
if (item == 64) {
// your code
}
}
}
EDIT:
Based on the update, I'd recommend to throw away the Math.max function because that makes you lose the track of the index. Since you only have 2 elements to compare, a simple if statement would do.
int x = triangle[i][j];
int y = triangle[i][j + 1];
int max = 0;
int indexOfMax = 0;
// using >= just in case if both numbers are equal
if (x >= y) {
max = x;
indexOfMax = j;
} else {
max = y;
indexOfMax = j + 1;
}
if (someCondition) {
// your code
}
You might want to try using a HashMap<Integer, Integer> instead if you want the code to scale and stay performant.
public class MobScene {
private HashMap<Integer, Integer> mobs = new HashMap<Integer, Integer>(10);
// Note that '10' is the initial capacity of the Collection.
// I only use it as I already know the given capacity and avoid extra memory being reserved.
public MobScene() {
mobs.put(9300127,2);
mobs.put(9300128,2);
mobs.put(9300129,2);
mobs.put(9300130,3);
mobs.put(9300131,3);
mobs.put(9300132,3);
mobs.put(9300133,4);
mobs.put(9300134,4);
mobs.put(9300135,5);
mobs.put(9300136,6);
}
public void addPoints(int mobid) {
if(mobs.contains(mobid)) {
mobs.put(mobs.get(mobid) + 1);
}
}
}
This will do the work....
public void addPoints(int mobid) {
// create a boolean to know if key has been found
boolean found = false;
// iterate over first column of your matrix array
for (int c = 0; c < mobPoints.length; c++) {
// if the key still not found and is equal first column value
if (!found && mobPoints[c][0] == mobid) {
// add points or do your stuff
System.err.println("Value = " + mobPoints[c][1]);
// mark as found
found = true;
}
}
if (!found) {
// not found error
}
}
If list is your list, you should be able to find the value "res" with:
list.get(0).get(0)
For a reference a[row][col] to an element of a 2d array, the equivalent reference to an ArrayList of ArrayLists (or really any List of Lists) will be list.get(row).get(col)
Iterate over the list in the list:
List<List<String>> dList = new ArrayList<>();
dList.add(Arrays.asList("A", "B", "C"));
dList.add(Arrays.asList("A", "B", "C"));
dList.add(Arrays.asList("A", "B", "C"));
for (List<String> list : dList) {
if (list.contains("A")) {
// todo
}
}
or use a java8 stream
example:
List<List<String>> dList = new ArrayList<>();
dList.add(Arrays.asList("A", "B", "C"));
dList.add(Arrays.asList("f", "t", "j"));
dList.add(Arrays.asList("g", "4", "h"));
String a = dList.stream().flatMap(List::stream).filter(xx -> xx.equals("a")).findAny().orElse(null);
a = dList.stream().flatMap(List::stream).filter(xx -> xx.equalsIgnoreCase("a")).findFirst().orElse(null);
a = dList.stream().flatMap(List::stream).filter(xx -> xx.equals("h")).findFirst().orElse(null);
As long as the comparison operator (equals() method) of your Square is suitable for you, then any of these method would work :
- Converting to
ArrayListand unsingindexOfandget - Using
java.util.Arrays.binarySearch - Do a
foreachloop and search manually - etc.
You only need a valid comparison operator, if the default Object.equals()(comparison of object instances) is suitable for your need, then you don't have much to do :
Point getObject(Square s){
{
for(int i = 0; i<n; i++){
for(int j = 0; j<n; j++){
if( squares[i][j].equals(s) ) {
return Point(i, j);
}
}
}
return null;
}
Note that if your array is large, it's not the fastest way to do it.
if you can use equals method (assuming n is defined also, or you can use length) :
public int[] getObject(Square s){
int[] returnIndex = new int[2];
for(int i = 0 ; i<this.n ;i++){
for(int j=0; j<this.n ;j++){
if(s.equals(this.squares[i][j])) {
returnIndex[0] = i;
returnIndex[1] = j;
return returnIndex;
}
}
}
return null;
}
Right now, you should consistently get 2 * arr.length as the final value. That isn't what you are probably looking for. It looks like you want to know the coordinates for the max value. To do this, you'll need to cache the values of the indexes and then use them later:
public static void main(String[] args) {
int[][] arr = {{4, 44, 5, 7, 63, 1}, {7, 88, 31, 95, 9, 6}, {88, 99, 6, 5, 77, 4}};
int tmpI = 0;
int tmpJ = 0;
double max = arr[0][0];
// there are some changes here. in addition to the caching
for (int i = 0; i < arr.length; i++) {
int[] inner = arr[i];
// caches inner variable so that it does not have to be looked up
// as often, and it also tests based on the inner loop's length in
// case the inner loop has a different length from the outer loop.
for (int j = 0; j < inner.length; j++) {
if (inner[j] > max) {
max = inner[j];
// store the coordinates of max
tmpI = i; tmpJ = j;
}
}
}
System.out.println(max);
// convert to string before outputting:
System.out.println("The (x,y) is: ("+tmpI+","+tmpJ+")");
Be careful with your array dimensions! The second for-statement most of you have is wrong. It should go to up to arr[i].length:
for (int i = 0; i < arr.length; i++) {
for (int j = 0; j < arr[i].length; j++) {
if (arr[i][j] > max) {
max = arr[i][j];
tmpI = i; tmpJ = j;
}
}
}
My Java is a bit rusty but I'm not seeing any logical issues with the code doing what you want it to.
Since you return just the row or column index, the caller can't tell from that if the match was a row or a column.
There are several issues with this code.
The biggest one is that you use != to check for string equality instead of !String.equals().
The parameter n shouldn't need to be specified, since it can be inferred from the dimensions of myArray. As others have noted, the function is weird in that it ignores the first row and the first column, that it uses 0 as a special indicator that no match was found, and that the return value doesn't tell you whether it was a row or column that was found.
I'm not a fan of variable names i, j, and k. Variable names like row and col would have been clearer. The flag variable isError can be eliminated if you just structure the inner loops properly. (In general, flag variables are a poor way to direct flow of control; keywords like break, continue, and return are preferable.)
There is no sense in putting a test like if (j == n …) inside the loop, since it is only relevant when the loop terminates.
I'd write something more like this:
for (int row = 0; row < myArray.length; row++) {
int col;
for (col = myArray[row].length - 1; col >= 0; col--) {
if (row != col && !"error".equals(myArray[row][col])) {
break;
}
}
if (col < 0) {
return row; // Every relevant column in this row is "error"
}
}
…
return …; // Some value to indicate that no match was found
If you really want to not return an array nor string with both integers, you could create a class with two attributes (x,y), and return an instance of that class. But I don't see why you would do this
Class be looking like:
public class MyIndex{
int x;
int y;
public MyIndex(int x, int y){
this.x=x;
this.y=y;
}
public int getX() {return x;}
public void setX(int x) {this.x = x;}
public int getY() {return y;}
public void setY(int y) {this.y = y;}
}
Or use Point class from package java.awt
You have no other solution but to return the two indices:
public static int[] find(int a[][], int val) {
for(int i = 0 ; i < a.length ; ++i) {
for(int j = 0 ; j < a[i].length ; ++j) {
if(a[i][j] == val) {
return new int[] {i, j};
}
}
}
return null;
}