LinuxQuestions.org
Latest LQ Deal: Latest LQ Deals
Home Forums Tutorials Articles Register
Go Back   LinuxQuestions.org > Forums > Non-*NIX Forums > Programming
User Name
Password
Programming This forum is for all programming questions.
The question does not have to be directly related to Linux and any language is fair game.

Notices


Reply
  Search this Thread
Old 11-06-2003, 06:27 PM   #1
dave bean
Member
 
Registered: Jun 2003
Location: UK
Distribution: Slackware 9.1
Posts: 136

Rep: Reputation: 15
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.

thanks
 
Old 11-06-2003, 08:46 PM   #2
megaspaz
Senior Member
 
Registered: Nov 2002
Location: Silly Con Valley
Distribution: Red Hat 7.3, Red Hat 9.0
Posts: 2,054

Rep: Reputation: 46
why not use a map instead? it's basically a binary tree using keys.
 
Old 11-06-2003, 08:56 PM   #3
moeminhtun
Member
 
Registered: Dec 2002
Location: Singapore
Distribution: Fedora Core 6
Posts: 647

Rep: Reputation: 30
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.
 
Old 11-07-2003, 03:53 AM   #4
dave bean
Member
 
Registered: Jun 2003
Location: UK
Distribution: Slackware 9.1
Posts: 136

Original Poster
Rep: Reputation: 15
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 ?

thanks so far . .
 
Old 11-07-2003, 11:53 AM   #5
Looking_Lost
Senior Member
 
Registered: Apr 2003
Location: Eire
Distribution: Slackware 12.0, OpenSuse 10.3
Posts: 1,120

Rep: Reputation: 45
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
 
Old 11-07-2003, 12:59 PM   #6
dave bean
Member
 
Registered: Jun 2003
Location: UK
Distribution: Slackware 9.1
Posts: 136

Original Poster
Rep: Reputation: 15
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 . . .

thanks to y'all . .
 
Old 11-07-2003, 01:54 PM   #7
Looking_Lost
Senior Member
 
Registered: Apr 2003
Location: Eire
Distribution: Slackware 12.0, OpenSuse 10.3
Posts: 1,120

Rep: Reputation: 45
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]);
   }
  }


}
 
Old 11-07-2003, 04:46 PM   #8
dave bean
Member
 
Registered: Jun 2003
Location: UK
Distribution: Slackware 9.1
Posts: 136

Original Poster
Rep: Reputation: 15
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.

Still, theres nothing better than trial by error
 
Old 11-28-2003, 11:00 AM   #9
marke2571
LQ Newbie
 
Registered: Nov 2003
Posts: 1

Rep: Reputation: 0
an easier way I hope

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;

for(row = 0; row < matrix.length; row++)
{
for(col = 0; col < matrix[row].length; col++)
System.out.print(matrix[row][col] + "\t \t \t");
System.out.println();
}

}
//*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();
}

//get position
int position = 0;
int counter;

for(counter = 1; counter < matrix.length; counter++)
if(matrix[position][0] < matrix[counter][0])
position = counter;

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;

for(counter = 1; counter < matrix.length; counter++)
if(matrix[position][1] > matrix[counter][1])
position = counter;

System.out.println("The postion of lowest temp int the array is: Row " + position + ", Col " + col);
}

}

Last edited by marke2571; 11-28-2003 at 11:08 AM.
 
  


Reply



Posting Rules
You may not post new threads
You may not post replies
You may not post attachments
You may not edit your posts

BB code is On
Smilies are On
[IMG] code is Off
HTML code is Off



Similar Threads
Thread Thread Starter Forum Replies Last Post
index of an element in the array ? thelonius Programming 1 09-24-2005 12:41 PM
How to allocate memory for a multidimensional array ? indian Programming 12 11-19-2004 03:37 AM
C++ Six Element Array petercool Programming 2 08-20-2003 11:08 AM
multidimensional array (php) niehls Programming 2 01-31-2003 05:34 AM
PHP: Multidimensional array problem lhoff Programming 1 06-10-2002 02:49 PM

LinuxQuestions.org > Forums > Non-*NIX Forums > Programming

All times are GMT -5. The time now is 07:07 PM.

Main Menu
Advertisement
My LQ
Write for LQ
LinuxQuestions.org is looking for people interested in writing Editorials, Articles, Reviews, and more. If you'd like to contribute content, let us know.
Main Menu
Syndicate
RSS1  Latest Threads
RSS1  LQ News
Twitter: @linuxquestions
Open Source Consulting | Domain Registration