return index of element in java multidimensional array
ProgrammingThis forum is for all programming questions.
The question does not have to be directly related to Linux and any language is fair game.
Notices
Welcome to LinuxQuestions.org, a friendly and active Linux Community.
You are currently viewing LQ as a guest. By joining our community you will have the ability to post topics, receive our newsletter, use the advanced search, subscribe to threads and access many other special features. Registration is quick, simple and absolutely free. Join our community today!
Note that registered members see fewer ads, and ContentLink is completely disabled once you log in.
If you have any problems with the registration process or your account login, please contact us. If you need to reset your password, click here.
Having a problem logging in? Please visit this page to clear all LQ-related cookies.
Get a virtual cloud desktop with the Linux distro that you want in less than five minutes with Shells! With over 10 pre-installed distros to choose from, the worry-free installation life is here! Whether you are a digital nomad or just looking for flexibility, Shells can put your Linux machine on the device that you want to use.
Exclusive for LQ members, get up to 45% off per month. Click here for more info.
return index of element in java multidimensional array
hi all
I cant seem to find any syntax to allow searching or sorting in multidimensional arrays. I have a [4][5] array that i need to sort and then binary search to return an index position for any one element. On the sun website the binary search reference shows a single int[] as an argument but there is no mention of multidimensions.
Well, multidimensional arrays are simply arrays inside arrays. So if you got it for the one dimensional array then should be able to easily modify it for the multidimensional arrary.
good idea for the map but i am interested in learning about multidimensional arrays. I thought it would just require a small modification too, i spent most of last night looking for how to do this.
(twoD is the array)
int returnPos = Arrays.binarySearch(twoD,intToFind);
this statement wont compile - cannot resolve symbol Array.binarySearch
also Arrays.sort(twoD) wont compile but for a one dimensional it compiles fine.
Is there another command which can return me the index of an element i have searched for ?
I guess the short answer is the method only accepts one dimensional arrays, and that's that.
You probably know but remember a multidiemnsional array in java is an array of arrays meaning each array in the array can be a different size rather than say an array 4x2
you can have an array like lke this
int myArray[][]={ {1,2,3},{4,5,6,7,8,9},{2,4},{0,4,5,7,8,10,11,23,56,54}};
with each part/element (what's the name?) of the array having it's only separate length.
something to consider I guess when you do it yourself
yes, thats the conclusion i have come to. Problem is when i write for loops so i can only loop through 1 row i still have compilation errors pointing out its [][]. I guess ill go away and put the first row in a new array, the second row in a new array etc
Im sure there is probably a better method to solve this problem (megaspaz politely suggests map again). But i guess now i've learnt what i wanted to learn about MDimensional arrays . . .
For what it's worth here's an example using Arrays.binarySearch just to show it can be used:
Code:
import java.util.*;
import java.awt.Dimension;
//Searches two dimensional integer array for first instance of a given integer
public class MySearch
{
private static Dimension biSearch(int[][] arry, int target)
{
Dimension result=new Dimension(-1,-1);
int j=0;
int numberOfArrays=arry.length;
if(numberOfArrays<=0)
return result;
for(int i=0; i<numberOfArrays;i++)
{
Arrays.sort(arry[i]); //as we are using a binary search the array must be sorted first
//or the correct answer may not be found. As a result the
j=Arrays.binarySearch(arry[i], target); // original array will be sorted and the array indexes of
// any found number will reflect this new order..blah..blah
if(j>-1)
{
result.width=i;
result.height=j;
break;
}
}
return result;
}
public static void main(String args[])
{
int arry1[][]={ {12,13,14,15,16,17},{45,11,2,-1}};
int target=15;
Dimension result=new Dimension(biSearch(arry1,target));
if( (result.width==-1) || (result.height==-1))
System.out.println("Number not found");
else
{
System.out.println("The number " + target + " was found at position " + result.width + "," + result.height);
System.out.println("And here it is referenced in the array " + arry1[result.width][result.height]);
}
}
}
wow, thanks. if i lived nearer scotland id buy you a pint !!
I cant beleive how long i spent looking for that method last nite - and then i spent an hour tonite to put each multidimensional row in a seperate array, then sort each row and then return index in a really messy way.
this was a school assignment, notice the code for //get position (last two methods near the end of this post). I know I posted this a few weeks later than the original post, but it is for anyone else who is looking for info on how to do this. I am inserting the entire project below:
//**************************************************************************************************** ******************************
//Mark Ennis
//Assignment 14 Chap 9
//November 28, 2003 A WHOLE WEEK BEFORE DUE DATE!!!!!!!
//I must be getting this array stuff!
//**************************************************************************************************** ******************************
import java.io.*;
import java.text.DecimalFormat;
public class A14MEnns
{
static BufferedReader keyboard = new BufferedReader(new InputStreamReader(System.in));
public static void main(String [] args) throws IOException
{
//preload temps
int[][] Temps = {{40,0},{47,29},{59,17},{71,27},{80,22},{95,49},{99,47},{101,71},{105,62},{89,30},{80,5},{77,99}};
String go;
System.out.println("The following program outputs the average high, average low, highest, lowest, \nand the position of each in the array. The temperatures are pre-loaded, but are\nretrieved by the method getData as directed in the assignment.");
System.out.println("Hit 'Enter' to continue");
go = keyboard.readLine();
System.out.println();
//Call the methods, print the temps
System.out.println("High's(COL 0)" + "\t \t" + "Lows(COL 1)");
getData(Temps);
System.out.println();
averageHigh(Temps);
averageLow(Temps);
indexHighTemp(Temps);
indexLowTemp(Temps);
}
//method to print hi's and lo's
public static void getData(int[][] matrix)
{
int row, col;
}
//*NOTE I left this in here for my future refernce*
// public static void sumColumns(int[][] matrix)
// {
// int row, col;
// int sum;
//sum of each individual column
// for(col = 0; col < matrix[0].length; col++)
// {
// sum = 0;
// for(row = 0; row < matrix.length; row++)
// sum = sum + matrix[row][col];
// System.out.println("Sum of column " + (col+1) + " = " + sum);
// }
// }
//method to get the average high temp
public static void averageHigh(int[][] matrix)
{
DecimalFormat twoDecimal = new DecimalFormat("0.00");
double sumhi = 0;
int col = 0;
int row = 0;
for(row = 0; row < matrix.length;row++)
sumhi = sumhi + matrix[row][col] ;
System.out.println("Yearly average high temperature = " + twoDecimal.format(sumhi / 12));
System.out.println();
}
//method to get average low temp
public static void averageLow(int[][] matrix)
{
DecimalFormat twoDecimal = new DecimalFormat("0.00");
double sumlo = 0;
int col = 1;
int row = 0;
for(row = 0; row < matrix.length;row++)
sumlo = sumlo + matrix[row][col];
System.out.println("Yearly average low temperature = " + twoDecimal.format(sumlo / 12));
System.out.println();
}
//method to return the highest temp and its position
public static void indexHighTemp(int[][] matrix)
{
int row = 0;
int col = 0;
int largest;
//Largest element in high's column
for(row = 0; row < matrix.length; row++)
{
largest = matrix[0][col];
for(row = 0; row < matrix.length; row++)
if(largest < matrix[row][col])
largest = matrix[row][col];
System.out.println("Highest temp of the year " + largest);
System.out.println();
}
System.out.println("The postion of highest temp in the array is: Row " + position + ", Col " + col);
System.out.println();
}
//method to get lowest temp and its position
public static void indexLowTemp(int[][] matrix)
{
int row = 0;
int col = 1;
int lowest;
//Smallest element in lows column
for(row = 0; row < matrix.length; row++)
{
lowest = matrix[0][col];
for(row = 0; row < matrix.length; row++)
if(lowest > matrix[row][col])
lowest = matrix[row][col];
System.out.println("Lowest temperature of the year " + lowest );
System.out.println();
}
//get position
int position = 0;
int counter;
LinuxQuestions.org is looking for people interested in writing
Editorials, Articles, Reviews, and more. If you'd like to contribute
content, let us know.