Results 1 to 4 of 4
- 11-23-2011, 07:22 PM #1
Member
- Join Date
- Oct 2011
- Posts
- 16
- Rep Power
- 0
Need help with 2d array and sorting 1d array
The topic title is a little bit confusing, but here is the excercise description.
Matrix of grades (int[][] g) contains one row per student where elements of the row are grades (in scale 0 to 5) of corresponding student. Write a Java method to calculate an array of row indices in descending order of average grade, in case of equal averages the row that has smaller index comes first.
Java Code:package Sone_matrix; import java.util.Arrays; public class matExample4 { //On antud hinnete maatriks (int[][] g), milles on iga //üliõpilase jaoks üks rida, mille elementideks on selle // üliõpilase binded (skaalal 0 kuni 5). Koostada Java meetod //üliõpilaste pingerea moodustamiseks, mis tagastaks reanumbrite //massiivi (kõrgeima keskhindega reast allapoole, võrdsete korral //jääb ettepoole see rida, mille number on väiksem). public static void main(String[] args) { int res [] = sortByAvg(new int [][] {{3,3,3},{2,2,2},{4,4,4},{2,2,2}});//0,1,2 System.out.print(Arrays.toString(res)); } public static int [] sortByAvg(int [][] m ) { int [] result = new int[m.length]; int temp; //Võtame keskmised hinded for(int i=0;i<m.length;i++) { for(int j=0;j<m[i].length;j++ ) { result[i] +=m[i][j]; } result[i] = result[i]/m[i].length; System.out.print(+i); } //Sorting array so that lower average grades will be first return result; } }
- 11-23-2011, 08:42 PM #2
Re: Need help with 2d array and sorting 1d array
Look at using the contents of one array to index another array. The syntax would be something like this:
anArray[anotherArray[j]]
Then take a piece of paper and work out the logic for doing a sort using this type of variable references.
- 11-24-2011, 11:44 AM #3
Member
- Join Date
- Oct 2011
- Posts
- 16
- Rep Power
- 0
Re: Need help with 2d array and sorting 1d array
Could i get one hint more ;) I am still a little bit confused.
- 11-24-2011, 02:38 PM #4
Re: Need help with 2d array and sorting 1d array
Break the problem up into several steps.
One step is to get the averages for each student.
The next step is to create an array of indexes.
Say the averages are {33, 555, 22}
then the array of indexes would be {2(index of 22), 0(index of 33), 1 (index of 55)}
Look at the logic of sorting the indexes original order {0,1,2} to that get the above order.
Use lots of paper and pencil to work this out.
Similar Threads
-
Code for Array and Sorting
By Sync in forum New To JavaReplies: 9Last Post: 10-30-2011, 02:22 AM -
Sorting Array High-Low
By Brandon Seale in forum New To JavaReplies: 2Last Post: 02-18-2011, 02:56 AM -
Sorting Array UI
By Brandon Seale in forum New To JavaReplies: 6Last Post: 02-18-2011, 02:50 AM -
Sorting Array
By saqib15 in forum New To JavaReplies: 1Last Post: 02-12-2010, 04:42 AM -
Sorting an array of Strings
By Java Tip in forum java.langReplies: 0Last Post: 04-15-2008, 08:39 PM
Bookmarks