473,376 Members | 1,012 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,376 software developers and data experts.

Circle Sorting Help!!

Hey all,

I'm in a Java data structures class in college and I have a problem with this one sorting assignment. I'm not very experienced in java and have tried tackling this assignment in an assortment of ways but have failed miserably. Basically, here is the assignment:::

================================================== ======
"If you look in http://csis.pace.edu/~bergin/temp/circles.zip , you will find a file containing, among other things, a file named circles.arraylist. This file was created by writing an ArrayList of circle objects on an object output stream. It contains 5000 circle objects. The circle class and the main that created the circles file is also included in the zip. The data is random.

You will need to include the trials.Circle class in your project. in particular, the package must be trials and you should not modify the circle class.

Your job is to:
(a) Sort the circles by radius, smallest first
(b) Sort the circles by the red component of their color, largest first, and for those with the same red component by the blue (largest first) and if the red and blue is the same, then by green (largest first). This requires three sorts, the last two of which need to be stable. First sort by green, then blue (stable) and finally by red( stable). Note that merge sort is fast and stable. Quick sort is fast, but not stable.

Also build an adequete JUnit test to show that you have indeed sorted them as required.
================================================== =======


Im really not to sure how to go about solving this. Im not asking you guys to solve this for me, but if someone could give me a push in the right direction and tell me what to do, I would appreciate it. Please keep in mind that Im an amateur programmer, and some things you guys will probably suggest might be out of my skill range, so a slight explanation wouldnt hurt :)

Thanks in advance.
Dec 16 '07 #1
19 4353
Ganon11
3,652 Expert 2GB
Have you learned how to write sorting methods and get them to work?
Dec 16 '07 #2
I'm not perfect with them but I think I can pull it off. What do you suggest?
Dec 17 '07 #3
Ganon11
3,652 Expert 2GB
Well, then your program basically writes itself. You have a file that contains information about however many Circles - make a method to read them into an array/ArrayList/whatever and return that list/array. Then make a method to sort them by radius size. Then make a method to sort them by color (which, according to your problem, will be several methods combined). Then make a method to print out the circles in the array/list.

Go ahead and give it a try and let us know where you get.
Dec 17 '07 #4
BigDaddyLH
1,216 Expert 1GB
It's not clear from your assignment, but are you expected to code your own sort, or can you use the sorting methods in the API? If so, this is assignment is only a half page of code.
Dec 17 '07 #5
Well he said we could build our own sort programs or use something built into the java libraries to do the sorts...


But anyway, I built one of my own that sorts the circle array....but Im not really sure how to adapt it so that it sorts the circles by radius, then by the green color component, then the blue, then red. I understand you're supposed to used comparators, just not sure how to do it.

Here's my circle sorting code so far...
================================================== =======

package trials;

import java.awt.Color;
import java.awt.Point;

public class SortCircle {

public static <Circle extends Comparable<Circle>> void sort (Circle[] circles)
{
Circle currentMax;
int currentMaxIndex;

for(int i = circles.length - 1; i >= 1; i--)
{ //Find the maximum in the list [0...i]
currentMax = circles[i];
currentMaxIndex = i;

for (int j = i - 1; j >= 0; j--)
{
if (currentMax.compareTo(circles[j]) < 0){
currentMax = circles[j];
currentMaxIndex = j;
}
}

//Swap circles[i] with circles[currentMaxIndex] if necessary
if (currentMaxIndex != i){
circles[currentMaxIndex] = circles[i];
circles[i] = currentMax;
}
}
}
Dec 17 '07 #6
BigDaddyLH
1,216 Expert 1GB
If you can use a sorting method like java.util.Arrays.sort or java.util.Collections.sort, I would prefer it to reinventing the wheel. Here is the tutorial page on Comparators:

http://java.sun.com/docs/books/tutor...x.html#sorting
Dec 17 '07 #7
Since I have to sort the circles in order ( By Radius first, if radius's are equal, sort by the green color component of the circles, if both greens are equal, then sort by the blue component and so forth) should I use nested If statements with sorts in each, or should I do something different?
Dec 17 '07 #8
BigDaddyLH
1,216 Expert 1GB
Since I have to sort the circles in order ( By Radius first, if radius's are equal, sort by the green color component of the circles, if both greens are equal, then sort by the blue component and so forth) should I use nested If statements with sorts in each, or should I do something different?
A single comparator can order by one attribute first, then break times with a second attribute. For example:

Expand|Select|Wrap|Line Numbers
  1. import java.util.Comparator;
  2.  
  3. class Person {
  4.     public String getLastName() {...}
  5.     public String getFirstName() {...}
  6.    ...
  7. }
  8.  
  9. class NameComparator implements Comparator<Person> {
  10.     public int compare(Person x, Person y) {
  11.         int result = x.getLastName().compareTo(y.getLastName());
  12.         if (result == 0) {
  13.             result = x.getFirstName().compareTo(y.getFirstName());
  14.         }
  15.         return result;
  16.     }
  17. }
Dec 17 '07 #9
The code above is a big help, thanks dude.

Im off to class now but when Im back, I'll continue working on the code and i'll come back here if I need anymore help. Thanks everyone.
Dec 17 '07 #10
Im still getting errors. Im trying to understand why this class wont extend the circle class (which contains the methods I need such as getRadius(), etc in order for me to be able to sort. Here's what I have so far..

Expand|Select|Wrap|Line Numbers
  1. package trials;
  2.  
  3. import java.awt.Color;
  4. import java.awt.Point;
  5. import java.util.List;
  6. import java.util.ArrayList;
  7. import java.util.Comparator;
  8.  
  9. public class CircleSort extends Circle{
  10.  
  11.     class CircleComparator implements Comparator<Circle> {
  12.  
  13.         public int compare(Circle cOne, Circle cTwo) {
  14.  
  15.             int result = cOne.getRadius().compareTo(cTwo.getRadius());
  16.             if (cOne.getRadius() = cTwo.getRadius())
  17.             {
  18.                 result = cTwo.getColor().getGreen().compareTo(cTwo.getColor().getGreen());
  19.             }
  20.             else if (cOne.getColor().getGreen() = cTwo.getColor().getGreen())
  21.             {
  22.                 result = cTwo.getColor().getBlue().compareTo(cTwo.getColor().getBlue());
  23.             }
  24.             else if(cOne.getColor().getBlue() = cTwo.getColor().getBlue())
  25.             {
  26.                 result = cOne.getColor().getRed().compareTo(cTwo.getColor().getRed());
  27.             }
  28.  
  29.             return result;
  30.  
  31.         }
  32.  
  33.     }
  34. }
  35.  
What now?
Dec 17 '07 #11
I keep getting this error "Cannot invoke compateTo(int) on the primitive type int" when Im trying to compare the colors. How do I fix that. I also need to know how to implement the sort in the main.
Dec 17 '07 #12
BigDaddyLH
1,216 Expert 1GB
I keep getting this error "Cannot invoke compateTo(int) on the primitive type int" when Im trying to compare the colors. How do I fix that. I also need to know how to implement the sort in the main.
int is a primitive type, so ints are not objects. To compare ints I usually rely on a simple utility method like:

Expand|Select|Wrap|Line Numbers
  1. public static int compareInts(int x, int y) {
  2.     if (x < y)
  3.         return -1;
  4.     else if (x > y)
  5.         return 1;
  6.     else
  7.          return 0;
  8. }
Or you can use the fact that the wrapper class Integer is comparable.
Dec 18 '07 #13
Ok, but how would I incorporate that to my comparator? (I'm really bad at this lol)
Dec 18 '07 #14
Nvm, I figured out how to incorporate it, I just need help with getting the sort to run in the main. How would I do that
Dec 18 '07 #15
If someone can IM me on BiG DoGG 536, this could go by alot quicker.
Dec 18 '07 #16
Here is my entire code. The thing looks fine, but I get a small error all the way down below in the main, where it says Collections.sort(circles, circleComp) (I've bolded and underlined where Eclipse gives me the error warning). The error reads: "The method sort(List<T>, Comparator<? super T>) in the type Collections is not applicable for the arguments (ArrayList<Circle>, SortCircle)"

I dont know how to fix this and I think this is the only error preventing me from making this code work, so please, can someone just take a look at it and tell me whats wrong with it? Im so close yet so far lol.

//Code
package trials;

import java.awt.Color;
import java.awt.Point;
import java.io.Serializable;

public class Circle implements Serializable{

private static final long serialVersionUID = -9207159802160528525L;
public Point center;
public int radius;
public Color color;

public Circle(Point center, int radius, Color color){
this.center = center;
this.radius = radius;
this.color = color;
}

public Point getCenter() {
return center;
}

public Color getColor() {
return color;
}

public Integer getRadius() {
return radius;
}
}
---------------------------------------------------------------------------------------

package trials;

import java.util.ArrayList;
import java.util.Comparator;


public class CircleSort {

private static final long serialVersionUID = -9207159802160528525L;
public static int compareInts(int x, int y){
if (x > y)
return -1;
else if (y > x)
return 1;
else
return 0;
}

public static void SortCircle (ArrayList<Circle> circles, Comparator<Circle> compare){

class CircleComparator implements Comparator<Circle> {

public int compare(Circle cOne, Circle cTwo) {

int result = compareInts(cOne.getRadius(), cTwo.getRadius());
if (cOne.getRadius()== cTwo.getRadius())
{
result = compareInts(cOne.getColor().getGreen(), cTwo.getColor().getGreen());
}
else if (cOne.getColor().getGreen() == cTwo.getColor().getGreen())
{
result = compareInts(cOne.getColor().getBlue(), cTwo.getColor().getBlue());
}
else if(cOne.getColor().getBlue() == cTwo.getColor().getBlue())
{
result = compareInts(cOne.getColor().getRed(), cTwo.getColor().getRed());
}

return result;
}
}
}
}
-----------------------------------------------------------------------------------------------
package trials;

import java.awt.Color;
import java.awt.Point;
import java.io.FileOutputStream;
import java.io.ObjectOutputStream;
import java.util.ArrayList;
import java.util.List;
import java.util.Random;
import java.util.Collections;

public class CircleSortMain {

public static void main(String[] args){

ArrayList<Circle> circles = new ArrayList<Circle>();
Random rint = new Random();
for(int i = 0; i < 5000; ++i){
circles.add(
new Circle(
new Point(rint.nextInt(500),rint.nextInt(500)),//sets center
rint.nextInt(500),//sets radius
new Color(rint.nextInt(256),rint.nextInt(256),rint.nex tInt(256))));//sets color
}
ObjectOutputStream out = new ObjectOutputStream(new FileOutputStream("circles.arraylist"));
out.writeObject(circles);

SortCircle circleComp = new SortCircle();
Collections.sort(circles, circleComp);
System.out.println(circles + "/n");
}
}
Dec 18 '07 #17
BigDaddyLH
1,216 Expert 1GB
Things are going wrong in class CircleSort. It has a method called SortCircle that takes two parameters (circles and compare) that are never used. All this method does is declare a local class which implements Comparator. That's too tricky. I suggest you keep it simple -- define the comparator as a top-level class - not nested in anything.

The logic of the comparator is also wrong. If should be
- compare radius
- if tied, compare green components
- if still tied compare red components,
- if still tied, compare blue components
(I may have the order wrong there, but I hope the intent is clear.)
Dec 18 '07 #18
The logic of the comparator is exactly the way you said it should be isnt it? it first compares the radius, if equal, then compare the green color components and so forth. I took out the Sort circle method, but i still get an error in the main. How can I fix this error?
Dec 18 '07 #19
BigDaddyLH
1,216 Expert 1GB
Looking back on your original assignment, I'm not certain about the requirements:
Your job is to:
(a) Sort the circles by radius, smallest first
(b) Sort the circles by the red component of their color, largest first, and for those with the same red component by the blue (largest first) and if the red and blue is the same, then by green (largest first). This requires three sorts, the last two of which need to be stable. First sort by green, then blue (stable) and finally by red( stable). Note that merge sort is fast and stable. Quick sort is fast, but not stable.
That reads to me as a requirement that you are able to carry out two separate sorts: by radius and by color. Are you sure you are meant to only write one comparator: order by radius, then break ties by ordering by color?

Assuming that, the logic in your comparator (reply #17) is wrong:
Expand|Select|Wrap|Line Numbers
  1. int result = compareInts(cOne.getRadius(), cTwo.getRadius());
  2. if (cOne.getRadius()== cTwo.getRadius()) {
  3.     result = compareInts(cOne.getColor().getGreen(), cTwo.getColor().getGreen());
  4. } else if (cOne.getColor().getGreen() == cTwo.getColor().getGreen()) {
  5.  
This reads:

Compare radii; if they are equal, compare green else if green is equal... But if radii are different, you should be done!
Also note that the original requirement was to sort by red, then blue, then green, and your code is (attempting) green, then blue, then red.

I suggest you look more closely at my example in reply #9 -- note that my code does not have a single else in the comparator!!!

As for writing a comparator class, reply #9 shows how to do that as well. Understand that code and you are done.
Dec 18 '07 #20

Sign in to post your reply or Sign up for a free account.

Similar topics

2
by: Terry | last post by:
I have a text file with an unknown number of entries in it. The data in the text file is in this format: 22.9,"June",2004 6.7,"July",2003 18.3,"June",2004 dblIndex, strMonth, intYear
8
by: ianaré | last post by:
Hey all, if i use a os.walk() to append files to a list like so... files = root = self.path.GetValue() # wx.TextCtrl input filter = self.fileType.GetValue().lower() # wx.TextCtrl input...
1
by: Jeff | last post by:
ok gang. I have this code to get the data from mssql db set standings1 = conn.execute("select points, team, wins, losses, win_pct from tblStats order by wins desc, points desc, team asc")...
1
by: oshna1985 | last post by:
how to accept a value from user without importing any package and without using io stream....... for eg. we have to calculate area of a circle by accepting value of radius from the user.....and...
0
by: CSharpguy | last post by:
has anyone been able to sort a gridview without using a sqlobjectdatasource or typed dataset? My problem is that my method to bind my datagrid takes parameterts from dropdowns, then the user clicks...
3
by: Don | last post by:
I have a "Report" that is created from a "Form". It prints a list of items, you may consider it a shopping list. In any event I use to run this in alphabetical order but have since decided to run...
1
by: rjddude1 | last post by:
I need to only get the first line from the file (until it encounters first period ) and also sort the output in descending order. could you help me out here? //function declaration void...
5
by: jrod11 | last post by:
hi, I found a jquery html table sorting code i have implemented. I am trying to figure out how to edit how many colums there are, but every time i remove code that I think controls how many colums...
1
by: suniMyjava | last post by:
using Treeset to sort numbers .But sorting is not happening properly.Below is the code IDataCursor pipelineCursor = pipeline.getCursor(); String keyName = IDataUtil.getString( pipelineCursor,...
1
by: CloudSolutions | last post by:
Introduction: For many beginners and individual users, requiring a credit card and email registration may pose a barrier when starting to use cloud servers. However, some cloud server providers now...
0
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 3 Apr 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome former...
0
by: ryjfgjl | last post by:
In our work, we often need to import Excel data into databases (such as MySQL, SQL Server, Oracle) for data analysis and processing. Usually, we use database tools like Navicat or the Excel import...
0
by: Charles Arthur | last post by:
How do i turn on java script on a villaon, callus and itel keypad mobile phone
0
by: aa123db | last post by:
Variable and constants Use var or let for variables and const fror constants. Var foo ='bar'; Let foo ='bar';const baz ='bar'; Functions function $name$ ($parameters$) { } ...
0
by: ryjfgjl | last post by:
If we have dozens or hundreds of excel to import into the database, if we use the excel import function provided by database editors such as navicat, it will be extremely tedious and time-consuming...
0
by: ryjfgjl | last post by:
In our work, we often receive Excel tables with data in the same format. If we want to analyze these data, it can be difficult to analyze them because the data is spread across multiple Excel files...
0
BarryA
by: BarryA | last post by:
What are the essential steps and strategies outlined in the Data Structures and Algorithms (DSA) roadmap for aspiring data scientists? How can individuals effectively utilize this roadmap to progress...
1
by: Sonnysonu | last post by:
This is the data of csv file 1 2 3 1 2 3 1 2 3 1 2 3 2 3 2 3 3 the lengths should be different i have to store the data by column-wise with in the specific length. suppose the i have to...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.