somjit{} 60 Junior Poster in Training Featured Poster

i suppose then your not using some IDE etc. if you have recently started java , its good practise to do java in command line. but , i have eclipse , if you want , you can attach the class file here , ill open it in eclipse and post the code back for you. :)

somjit{} 60 Junior Poster in Training Featured Poster

individual question with a class to run both of them

sorry, i didnt get you there...

regarding your code , your creating isPerfect as a separate class , so when you want to use it inside your allPerfect class , you have to create a reference to it. since your calling it directly , it says it cannot find the class, as java doesnt know where to look for the isPerfect method.

also in this line System.out.println(ap.allPerfect(num)); this wont work as allPerfect()'s return type is void. you cannot print something when its not there!

somjit{} 60 Junior Poster in Training Featured Poster

first of all , welcome to daniweb. :)

now, regarding your code, when you say linked list as an array , im supposing this to be an implementation of a singly linked list. in which case , as you said , one array will hold the data , and another array will hold the "next" feild of a traditional linked list.

in that case , im having some doubts regarding your find() method:

      for(int i = 0; i <= numItems; i++)
        {
            if(next[i] == index)
            {
                return i;
            }
        }

this seems unnecessary. the disadvantage of linked list is in random access , finding/returning any "node" at random requires you to search from the head (in case of singly linked list) or either of the two ends (doubly linked list)... which you are doing here. But as you are using array ,you can just use the values from the arra that holds the "next" feilds to reference any data element directly.

also , it would be helpful if you post your code for the pageUsage[] class.
its easier to test for errors in debuggers and IDE's when the full code is available. :)

edit: i saw bguild had already posted after i posted.
a lot of the code looks like what it would do if the data structure was linked list , but its not , its arrays. i cant compile and check the code as the pageUsage class is missing , but regarding the …

somjit{} 60 Junior Poster in Training Featured Poster

your code has an allperfect , isperfect , and possibly a main method right? it would be helpful if your post it here , then we might know what is causing the problem.

somjit{} 60 Junior Poster in Training Featured Poster

your code will be slow for large "end" parameter, as it has to check for every number because of the for() loops.
a faster method will be this :

from the wiki page for perfect numbers , ull get a formula with a variable p that all perfect numbers (48 of them) follow.

now , in ur code , ur allPerfect() class will take in "end" parameter. and this will keep calling the isPerfect method untill the isPerfect method returns a perfect number value bigger than "end".

going to ur isPerfect() class, it will contain an array of 48 p values that ull get from the wiki page. and in each iteration it will use one value from the p array and return the calculated perfect number based on the formula from the wiki page.

thus the code will work like this :

allPerfect() gets end , and calls isPerfect
isPerfect() returns ith perfect number taking the ith p value from p array
if returned number is greater than end , allperfect no longer calls isPerfect(), and the code exits with the required prints etc.

its hard to write math in daniweb , so i couldnt write the formulas directly here.

if you want a more do it myself sort of code , one option is using seive of erasthosenes to find primes upto "end" , then for each prime , check if (2^p) - 1 is prime or not , if it is prime , …

somjit{} 60 Junior Poster in Training Featured Poster

is there any particular reason ur keeping your readlines method static?

edit : didnt see that james already posted there....

somjit{} 60 Junior Poster in Training Featured Poster

dont have much of a sweet tooth , i like hot spicy stuff ... but thats generally reserved for luch or dinner. as a snack , i might like some fresh peas , chilled mangoes , and some grated fresh coconut topped with some sugar. simple and light. :)

somjit{} 60 Junior Poster in Training Featured Poster

if you had looked at what you didnt want to see,
you might have felt less of what you didnt want to feel.

somjit{} 60 Junior Poster in Training Featured Poster

I hope they weren't "Americanized".

in dragon ball z , what happens at my place ( country rather ) they get to a really interesting point in the show , like where majinboo hatches and then poof... back around 100 episodes... and the loop continues 3 or 4 times! it killed my interest in the show...

Dialog is destroyed (I prefer the original with subtitles)

absolutely! only exception i think is dragon ball z. but that may be partially because i started seeing the dubbed version from the very start , and liked it.

However i recently watched a few dubbed versions of bleach... the way they say "bankai" makes me laugh :D ! the original japanese version is WAY WAY better ... keeps the whole feel intact... plus got to learn a few japanese words as well :)

cartoon network is dead... but i have fond memories of justice league... and the all the other MARVEL comic avatars. i loved dexter! i wish dee dee wasnt a pest :P poor boy :D

i saw a few comic-con videos in you tube... man there were some beautiful ladies !! :P ( im still a college kid , so i guess i can still say that without being gross or anything :P )

somjit{} 60 Junior Poster in Training Featured Poster

sorry for that.

somjit{} 60 Junior Poster in Training Featured Poster

james and radhakrishna already pointed out the things you should be doing.. i just saw that in ur isSolvable() method , ur doing this :

            if(((a*d) - (b*c)) == 0)
                return 0;
            else
                return 1;

you dont need to have a if else structure for return.. once return is called , the method exits. so the above code can be compressed down to

 if(((a*d) - (b*c)) == 0) return 0;
 return 1;

makes code look more compact , especially when your doing more complicated stuff. learnt about this recently , so id thought id share :)

somjit{} 60 Junior Poster in Training Featured Poster

I forgot to mention Cowboy Be-Bop.

i forgot all about that too! simply loved it. dragon ball z is was and will be a classic . only cartoon network keeps repeating the episodes to death! i wish i had a fast unlimited download scheme net connection... would have downloaded the shows!

i had watched a few episodes of fairyTail when we used to get animax back in my school days, i liked it then , but recently , the new episode version has started airing... and it looks a bit silly :/ a chicken guy who shoots eggs from his mouth ... :P

have anyone watched heidi? its an old one.. and if i watch it i dont know how ill feel about it , but back in my 3rd-4th grade days... it was simply beautiful . loved it. even my mom would sit with me and watch heidi :)

somjit{} 60 Junior Poster in Training Featured Poster

i woke up and i thought i should also mention this , last one month or so , iv used buffered reader for my parsing stuff , and it ran ok. i just used scanner here as im only allowed to import java.util and java.lang. . ill be trying to work this around now again... i wrote another tiny code , which takes the same file as input , uses the same nextInt() , and this one seems to run just fine, whereas the previous code i posted , despite having the same methods , throws exception...

this is the code i tested for scanner

import java.util.Scanner;
import java.io.File;
import java.io.FileNotFoundException;


public class scanTester {

    public static void main(String[] args){
        String filename = args[0];
        try {
            Scanner is = new Scanner(new File(filename));
            while(is.hasNext()){
                System.out.println(" " + is.nextInt());
            }
        } catch (FileNotFoundException e) {
            System.out.println(e);
            e.printStackTrace();
        }

    }


}
somjit{} 60 Junior Poster in Training Featured Poster

im down with

Exception in thread "main" java.util.InputMismatchException
    at java.util.Scanner.throwFor(Unknown Source)
    at java.util.Scanner.next(Unknown Source)
    at java.util.Scanner.nextInt(Unknown Source)
    at java.util.Scanner.nextInt(Unknown Source)
    at equalityTester.setup(equalityTester.java:16)
    at equalityTester.<init>(equalityTester.java:12)
    at equalityTester.main(equalityTester.java:48)

apparantly this seems to be a very popular error , but i didnt find any solution to it on the web.

my input file is this :

8
10000 0
0 10000
3000 7000
7000 3000
20000 21000
3000 4000
14000 15000
6000 7000

and my class is this :

import java.util.ArrayList;
import java.util.Scanner;
import java.util.Collections;

public class equalityTester{

    ArrayList<Point> p = new ArrayList<Point>();
    Scanner is;

    public equalityTester(String filename){
        is = new Scanner(filename);
        setup();
    }

    private void setup(){
        int num = is.nextInt();
        Point pt;
        int loop = 0;
        while(loop < num){
            pt = new Point(is.nextInt(), is.nextInt());
            p.add(pt);
        }

        System.out.println(" entered points are : ");
        for(Point point : p){
            System.out.println(point);
        }

        Collections.sort(p); // sort acc to internal ordering
        ArrayList<Line> L = new ArrayList<Line>();
        Line line1 = new Line(p);
        Collections.sort(p, p.get(0).SLOPE_ORDER);
        Line line2 = new Line(p);

        L.add(line1);
        L.add(line2);

        int comparison = line1.compareTo(line2);
        if(comparison == 0)
            System.out.println("equal");

        // dont know what to do next , as i cant figure out the compareTo of line class


    }
    public static void main(String[] args){
        String filename = args[0];
        equalityTester et = new equalityTester(filename);
        System.out.println("\n\n\n\n done executing ");
    }
}

iv modified the line class as you mentioned in the last post. i didnt post it to save space and clutter.

somjit{} 60 Junior Poster in Training Featured Poster

this is the compareTo() code i came up with , havent yet run the whole code , coz i still have some other parts to look into ... but can you take a look at this and suggest if this is ok or not ? i would be a bit releived on atleast this part then...

class Line implements Comparable<Line>{
    ArrayList<Point> lineOfPoints;
    double slope = slope(this);
    double b = b(this);
    double x0 = -1*(b/slope);
    double y0 = b;

    public Line(ArrayList<Point> line){
        this.lineOfPoints = line;
    }

    // y = mx + b , where b is a constant
    public double b(Line anyLine){
        Point anyPoint = anyLine.lineOfPoints.get(0);
        int x1 = anyPoint.x();
        int y1 = anyPoint.y();
        double constant = y1 - slope*x1;
        return constant;
    }

    public double slope(Line anyLine){
        Point p1 = anyLine.lineOfPoints.get(0);
        Point p2 = anyLine.lineOfPoints.get((lineOfPoints.size() - 1));
        double slope = p1.slopeTo(p2);
        return slope;
    }
    @Override
    public int compareTo(Line that) {


        if(this.slope > that.slope ) return +1;
        if(this.x0 > that.x0 ) return +1;
        if(this.y0 > that.y0 ) return +1;
        if(this.slope < that.slope ) return -1;
        if(this.x0 < that.x0 ) return -1;
        if(this.y0 < that.y0 ) return -1;
        return 0;


    }
}

You need equals as well

i read in the java API that it takes in Object as argument . so do i need any casting or anything as such to convert that to the particular stuff im working with?
also , as you mentioned equals is just the return 0 part of the compareTo() , so …

somjit{} 60 Junior Poster in Training Featured Poster

the slope and intercept method sounds great. should be easy to implement too i think. no need for looping through arraylists anymore :)

however if i do use that method , i really dont need the return +1 , -1 parts of a compareTo method anyways do i? as im just testing for equality... so in that case what to do? if i use a compareTo() i guess i have to keep stuff for -1 and +1 , the only thing i can think of regarding returning +1 -1 , is that it might be based on slopes being more or less than that of the invoking point.

if im only cencerned with the return 0 part , can i use something else instead of a compareTo() ?

somjit{} 60 Junior Poster in Training Featured Poster

i was writting a small testcode for checking these arraylist comparison stuff. my basic goal was to sort the same array in two different orders , and each sorted array in essence will be like a line , they will have same member points , but at different locations. then i would compare them using the compareTo method as you pointed out, and thus check if they are equal or not. but , im stuck again... i cant understand what to do... and this is a very sinking feeling...

my test code :

import java.util.ArrayList;
import java.util.Scanner;
import java.util.Collections;

public class equalityTester{

    ArrayList<Point> p = new ArrayList<Point>();
    Scanner is;

    public equalityTester(String filename){
        is = new Scanner(filename);
        setup();
    }

    private void setup(){
        int num = is.nextInt();
        Point pt;
        int loop = 0;
        while(loop < num){
            pt = new Point(is.nextInt(), is.nextInt());
            p.add(pt);
        }

        System.out.println(" entered points are : ");
        for(Point point : p){
            System.out.println(point);
        }

        Collections.sort(p); // sort acc to internal ordering
        ArrayList<Line> l = new ArrayList<line>();
        l.add(p);
        Collections.sort(p, p.get(0).SLOPE_ORDER); // sort acc. to slope
        l.add(p);

        // dont know what to do next , as i cant figure out the compareTo of line class


    }
}

class line implements Comparable<line>{
    ArrayList<Point> line;
    public line(ArrayList<Point> line){
        this.line = line;
    }
    @Override
    public int compareTo(line that) {
        // dont know what to do here        
    }
}
somjit{} 60 Junior Poster in Training Featured Poster

pretty much grew up with dexter , scooby doo and the likes...
back in my high school days loved get backers , inu yasha, and full metal alchemist. i never got to see the ending of any of them as the channel stopped airing suddenly. got the channel back a few months ago.. loved the bleach series, and currently loving full metal brotherhood :)

somjit{} 60 Junior Poster in Training Featured Poster

thank you for keeping up with me .

Since nobody seems to know exactly where this is going

basically a code which takes in points from a input file , sorts them in a certain order by using comparables and comparators , and then analyses the collection of points and prints out in command line the points which are collinear, without repition. i originally made the thread as i was confused with comparators . I apologise if iv bloated the thread up.

regarding comparing the two lines ,
will i be correct in saying Arrays.equals(line1, line2) will compare the two arraylists of points , and will return as equal even if ordering of points are different? i was reading here where it was mentioned that .equals() is badly broken.. ill have to read more into this though..

somjit{} 60 Junior Poster in Training Featured Poster

iv been trying to figure a part out but so far have been unsuccessful.

success so far :
All the sorting and everything is done , got a better hang of comparators , am able understand the gui parts , and figured a few ways to use a pre built StdDraw code that we are supposed to use too. also , changed the Point class to fit the given API.

problem now is how to display the collinear points in a per line basis , without repetition. ie , no two permutations of the same line points should be printed.

im posting my tester method below :

import java.io.File;
import java.io.FileNotFoundException;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Scanner;

public class pointTester {

    public static void main(String[] args) throws FileNotFoundException {
        String file = args[0];
        Scanner h = new Scanner(new File(file));
        int num = h.nextInt();

        ArrayList<Point> p = new ArrayList<Point>();

        // draw each point.
        StdDraw.setCanvasSize(800, 800);
        StdDraw.setXscale(0, 30000);
        StdDraw.setYscale(0, 30000);
        StdDraw.setPenRadius(.009);
        StdDraw.setPenColor(StdDraw.BLUE);
        for (int i = 0; i < num; i++) {
            p.add(new Point(h.nextInt(), h.nextInt()));
            p.get(i).draw();
        }

        //sort the points based on lowest y and print
        Collections.sort(p);
        for (Point pt : p) {
            System.out.println(pt);

        }

        //creates a copy of the arraylist
        ArrayList<Point> test = new ArrayList<Point>(p);

        // made this one to hold collinear points , but not too sure how to use it 
        ArrayList<Point> col;


        //and the confusion starts here onwards: 

        for(int i = 0; i < num ; i++){
            //sort the arraylist accoring to slope wrt lowest …
somjit{} 60 Junior Poster in Training Featured Poster

welcome to daniweb. :)

how can i make my 10 different program as one program

would be good if you could explain a bit more about these "programs" . if you have written some code , post them here , that would speed up the problem solving procedure. :)

somjit{} 60 Junior Poster in Training Featured Poster

@ mostlydangerous

use the edit post button , consecutive posts look a bit cluttered... and odd.

@pvn29 : use indentation on your code , else will look cluttered.

i edited your code a little bit.
this one is indentated , and as soon as size equals initialCapacity , it exits the program.

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.ArrayList;

public class UserList {
    public static void main(String[] args) throws Exception {
        String str1, str2 = "username";
        int index;
        int initialCapacity = 3;

        BufferedReader dataIn = new BufferedReader(new InputStreamReader(System.in));
        ArrayList<String> users = new ArrayList<String>();
        System.out.print("Enter a user name: ");
        str1 = dataIn.readLine();

        while (str1.length() > 0) {
            boolean containsString = users.contains(str1);
            if (str1.equals(str2))
                System.out.println("That user name is NOT allowed!");
            else if (!containsString) {
                users.add(str1);
                System.out.println("User \"" + str1 + "\" added to user list.");
            }
            else if(containsString){
                System.out.println("User \"" + str1 + "\" already in user list.");
            }
            if (users.size() == initialCapacity) {
                    System.out.println("List is full!");
                    System.out.println("Last entry is " + users.get(initialCapacity - 1));
                    break;
            }
            System.out.print("\nEnter a user name: ");
            str1 = dataIn.readLine();
        }

        System.out.println("Program complete.");
    }
}
somjit{} 60 Junior Poster in Training Featured Poster

grapes :P waiting for dinner... hungry..

somjit{} 60 Junior Poster in Training Featured Poster

i grew up with cartoon network and animax... cartoon network has gone bogus , but i dont feel the same for animax. i saw that SOS , the admin from the java forum has baen nido (from Get Backers ) in his display pic, a character who used to be my fav during school days.. so i thought id ask if there are other people who love cartoons/anime too?

somjit{} 60 Junior Poster in Training Featured Poster

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;

it seems you didnt import java.util.ArrayList. without doing so , it arraylist wont work.

System.out.println("Last entry is "+users.get(initialCapacity));

this should be System.out.println("Last entry is "+users.get(initialCapacity - 1)); as arraylists an arrays have the same convention regarding indices.

else
{
    if(users.size() == initialCapacity)
    {

why not just use else if(){} .. ?

also , your code waits for user input after the arraylist is full , maybe you should change it so that when size becomes intialCapacity , the loop exits and the program finishes.

somjit{} 60 Junior Poster in Training Featured Poster

Just use the public accessor methods x() and y()

i completely overlooked that part! i guess my eyes was serching for some method whose name began with a "get.." . being able to access point2d's co ords should make things simpler :)

i did as you said , and i am getting the points as i should , although i had to change one line a bit.

i modified the line inside the foreach loop you gave with this g.fillOval((int)point.x()*25, (int)point.y()*25, 4, 4); but that was only because i gave points in the range of (2,2) to (6,7). wouldnt have needed the scale change for more spaced apart points.

but now thats done? any ways i can print out the co ordinates beside each point on the plot? that would make the plot more make it more readable i guess...

somjit{} 60 Junior Poster in Training Featured Poster

i tried implementing the code from the link you gave , but as the Point2D class holds the point co ordinates as private , i couldnt do the for loop like you said above. i did a bit of an experiment , and learned a bit of basic GUI from the book Head First Java , and wrote a few lines of code. however , even though im getting the frame , the points arent showing up...

i created a new frame , from within which i call a new panel. in my panel class , i keep an inner class myPoints . each myPoints point has integer x and y as the co ordinates , there is a setter that takes in a String array from the loop where the original inputs from the file are read and parsed. finally i keep an arraylist of such points, on which i call the foreach loop you described above.

this is the resultant code:

import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Collections;

import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.Graphics;

import javax.swing.SwingUtilities;
import javax.swing.JFrame;
import javax.swing.JPanel;

public class Point {

    ArrayList<Point2D> p = new ArrayList<Point2D>();
    BufferedReader is = null;

    public Point() throws IOException{

        is = new BufferedReader(new FileReader("C:/Documents and Settings/Somjit/Desktop/points.txt"));
        String line;
        try{
            Point2D pt;
            myDrawPanel outer = new myDrawPanel();

            while((line = is.readLine())!= null){
                String[] parsed = line.split(" ");
                assert parsed.length == 2 : "line has more than two coords : not allowed";
                pt = new Point2D(Double.parseDouble(parsed[0]), Double.parseDouble(parsed[1])); …
somjit{} 60 Junior Poster in Training Featured Poster

Try timing a sort on thousands of random points

that would be great if coupled with some gui stuff.. like having a frame that would display on it the points created. i would have a visual understanding of the points created and if the code is doing what it should.

however , i have zero gui experience , and although there is a princeton draw() class that we are supposed to use for gui functions , im only just starting to get the hang of Point2D , and that draw() code has exactly 1126 lines .... so... its not for me right now ... :P

can you suggest some simpler things/links that will be good enough for just the needs above?

somjit{} 60 Junior Poster in Training Featured Poster

i did some basic stuff , and ran a simple test. looks good so far. however , even with a simple set of around 10 points , the whole process is taking around 16 milliseconds to finish... and im getting a feeling that this is too slow...

this is the test code i made , is there some ways to make it faster?

import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Collections;

public class Point{

    ArrayList<Point2D> p = new ArrayList<Point2D>();
    BufferedReader is = null;

    public Point() throws IOException{

        is = new BufferedReader(new FileReader("C:/Documents and Settings/Somjit/Desktop/points.txt"));
        String line;
        try{
            Point2D pt;
            while((line = is.readLine())!= null){
                String[] parsed = line.split(" ");
                assert parsed.length == 2 : "line has more than two coords : not allowed";
                pt = new Point2D(Double.parseDouble(parsed[0]), Double.parseDouble(parsed[1]));
                p.add(pt);
            }
        }catch(IOException e){
            System.out.println(e);
        }finally{
            is.close();
        }

        System.out.println(" sorting for lowest point");
        Collections.sort(p);
        System.out.println(" lowest point obtained: " + p.get(0));
        Collections.sort(p, p.get(0).POLAR_ORDER);
        System.out.println(" after sorting wrt lowest point");
        for(Point2D point : p){
            System.out.print(" " + point);
        }

    }
}

// and the tester
import java.io.IOException;

public class pointTester {

    public static void main(String[] args) throws IOException{
        final long startTime = System.currentTimeMillis();
        Point p = new Point();
        final long duration = System.currentTimeMillis() - startTime;
        System.out.println("\n\n\n running duration in milli seconds : " + duration);
    }

}
somjit{} 60 Junior Poster in Training Featured Poster

The sort algorith selects a pair of objects the asks the Comparator which comes first.

im getting it now.. and thanks to eclipse , i also got somewhat an idea about the syntax to use. let me try this now.. :)

somjit{} 60 Junior Poster in Training Featured Poster

you'll have to repeat that process using each point in turn as the "particular point"

thats exactly what i want to do.. but i just wrote that code as an example to show what i want to do with each of the points.

If you're using the Princeton algorithms Point2D class, as opposed to the standard JDK Point2D, (wich I assume you are becuase of the ref to POLAR_ORDER)

that is what im using , but the problem is , im all messed up with comparators and comparables. that particular class has so many different types that im just scratching my head with them trying to understand which ones to use and where!

i understand the part about using area. the area2 variable you spoke of falls in the ccw() method , which is itself called from within POLAR_ORDER under a special case.... which i dont understand either ! :(

all i do understand about the collinearity using the area procedure and the ccw() method is that it calculates area based on cross operation .
cross operation on 3 points return the area of the parallelogram that can be obtained using three points, and since area of triangle that shares a base with a side of a parallelogram is half the parallelograms area , cross product of 3 points give twice the triangles area , and using this , ccw() returns

-1 for point being in clockwise order with respect to the particular point being …

somjit{} 60 Junior Poster in Training Featured Poster

i want to sort a list of two dimensional points based on their polar angles with respect to a particular point. this will a part of a bigger code to find collinear objects from a set of points.
the method i thought of for doing this is is:

  1. create an arraylist of Point2D points
  2. use the POLAR_ORDER comparator of the above Point2D class.

the code i thought of for this is :

// setting things up and stuff

ArrayList<Point2D> p = new ArrayList<Point2D>();

// more code that i'll have to think of

Collections.sort(p, p.get(0).POLAR_ORDER);

// other stuff

will the above two lines work? i really dont know what to put in between them yet, so im yet to run simple tests...
if the above two lines work then ill proceed in the way that iv thought of, else back to the drawing board..

edit: im intending to sort the points according to polar angle it makes with the 1st point contained in the arraylist. im assuming p.get(0) gives the 1st element... ??

somjit{} 60 Junior Poster in Training Featured Poster

thank you :)

somjit{} 60 Junior Poster in Training Featured Poster

perhaps this isnt a good place to post this query , but im doing so as my doubt relates to the if-else structure that has been talked about here...

in this code

    // compare by y-coordinate, breaking ties by x-coordinate
    public int compareTo(Point2D that) {
        if (this.y < that.y) return -1;
        if (this.y > that.y) return +1;
        if (this.x < that.x) return -1;
        if (this.x > that.x) return +1;
        return 0;
    }

Point2D is a class that deals with x,y co ordinates in a 2D plane , and it implements comparable() . my question is , that if one condition gets satisfied , lets suppose the 1st one, then will the next ones be checked?
i dont know if doing executing a return exits that method , hence this post. by the way, is return a method? i tried to google for it , but in every case, the return google thought im asking for wasnt what i was asking for.. i got stuff like returning arrays etc , but not what return means in java... so no luck there...

my apologies if im being vague , and making a post in the wrong place...

somjit{} 60 Junior Poster in Training Featured Poster

@stultuske : yes , i should have elaborated that part more.

@bobit : although ur using getters and setters , all the instance variables of your code are open and exposed. you should change them to private. like , instead of double radius , it should be private double radius

reason? well , When you write your code , if all the variables are exposed , they can get accessed and changed from anywhere in the code during run time, and you might find that ur output is quite different from one you hoped for.. the very reason we use public getters and setters is such that the instance variables can stay private, protected from any outside influence , and can only be modified by calling the respective getters and setters for that particular variable. this whole "protect your instance variable " thingy is the famous java concept of encapsulation.

apart from making your code safer through encapsulation, getters and setters also lets you put in checks , like

public void setRadius(int r){
    if( radius < 0 ) System.out.println("negative values not allowed");
    else if(r > 10) radius = r; 
    else radius = 5; // provide a default value of 5 to radius
}

so here, not only is radius not allowed to be zero , and is changed to default value of 5 if a value less than 10 is passed , you also get a warning if negative values are passed to it. you might not need …

stultuske commented: there you go :) +14
somjit{} 60 Junior Poster in Training Featured Poster

I belive a bubble sort on an already sorted list will terminate after exactly one pass, which must be the best case.

insertion sort too :) in fact , for a partially sorted array , insertion sort runs in linear time. which is the best case for any compare based sorting model.

somjit{} 60 Junior Poster in Training Featured Poster

i agree with james , but then again , school/college teachers rarely follow the best practises...

keep a circle class , it will have ONE variable only : radius.
the methods will be setRadius() , getArea() , and if you need it, keep a getRadius() too. all these methods should be public. and all your variables should be private, thats the whole point with using public getters n setters.

figure{} class doesnt make any sense.

somjit{} 60 Junior Poster in Training Featured Poster

does this code do atleast some part of what you hoped it would? since your reading from a file , bufferedReader is a faster way of doing things.

a part of a code i wrote for parsing purposes :

        try {
            is = new BufferedReader(new FileReader(fileName));
            while ((line = is.readLine()) != null) {
                String[] parsedLine = line.split(" ");
                wordCount += parsedLine.length;
                lineCount++;
            }
        } catch (IOException e) {
            System.out.println(e);
        } finally {
            is.close();
        }

here , the condition in the while() loop takes care of checking if the end has been reached , and the split method keeps each word of each line in an array of strings.

so since you want to output each line , print the lineCount followed by the line read through the readLine() method of buffered reader. since you dont have to worry about word counts, you can omit the lines where the split() has been used. and just use a print statement and print the line.

somjit{} 60 Junior Poster in Training Featured Poster

@michael : you see , apparantly , the results will look like they are giving random numbers , but lets go through a simple case:

suppose you have 3 cards from a deck , so number of diff permutations will be 3! = 6 , lets see this in a bit detail :

'__________' '_________' '_________'

the above are 3 slots, where you can put the cards.

for the 1st slot , you have 3 options.
for the 2st slot , you have 2 options left.
for the 3st slot , you have 1 option left.

thus 3*2*1 = 6 total number of ways you can arrange the cards.

if you want to do this in code , you will have to reduce the population from where your taking the cards by 1 in every turn , thus resulting in 2 options down from 3 , and then 1 option down from 2 in the 2nd and 3rd runs.

if you dont do this , and take a random number from the whole population , ie 3 on each turn, you would get 3*3*3 = 27 combinations , which isnt correct, and will give you biased results. You can check that with the naked eye as well as the result obtained here(27) isnt divisible by 6 ( the correct result ) . So some arrangements will turn up a greater number of times than others.

i had posted a link on one of my earlier replies... there you …

somjit{} 60 Junior Poster in Training Featured Poster

is there a standard best/worst case for sorting algorithms?

there are hundreds of sorting algorithms out there... some of them have different variations of themselves as well. they all have their own standard best/worst case complexity.

example : considering two classic algorithms : quicksort and mergesort, quicksort has time complexity higher than mergesort (both in the region of NlogN ), but generally a standard quicksort algorithm works faster than mergesort .. why? because mergesort requires more space in the form of an auxillary array in its algorithm, so for huge data structures , moving values from one array to another eats up the time complexity advantage it had over quicksort.

notice i say generally , because the original quicksort can go and run in quadratic time in presence of duplicate keys, but this error was eventually solved by implementing random shuffle at the begining , and then using a 3 way partioning method to keep the duplicates grouped in order.

so I was thinking a vector where all elements are the same would be the worst case scenario, and that a vector filled with randomly generated numbers would be the average scenario, and the best case scenario would be on an already sorted vector,

mergesort is an optimal sorting algorithm , meaning that its upper and lower bounds are both in the region of NlogN.. so it doesnt matter how the data is arranged to mergesort , it will take more or less equal time anyways.

somjit{} 60 Junior Poster in Training Featured Poster

@thetechie , welcome to daniweb :)

regarding the problem above , have you tried writing some code? or do you want some algorithm of sorts? if you have some code, you can post it here , it would help the members to help you...

to answer your question , try using this method :

r^n = x.
therefore , ln r = ( ln x )/n
therefore , r = exp ((ln x)/n)

where : x = number , r = nth root.
hope it helps.

somjit{} 60 Junior Poster in Training Featured Poster

this will not return unique random number.

Yes. i read recently that choosing a random number from an entire array wont give you correct results. which is what you said above as well.. knuth shuffle works around this problem by choosing randomly between 0 and i , or in some cases (n-1) to i , but not from 0 to (n-1).

edit : found this to be an interesting read.

somjit{} 60 Junior Poster in Training Featured Poster

thankyou so much for the detailed answer !

ill practice this method.. thanks again :)

somjit{} 60 Junior Poster in Training Featured Poster

will this work?

  1. create an array of size 1000 to start.
  2. with every new Node created , hold the address of the node in the array
  3. getRanPointer() method will return the value (address) stored at a particular element at random , and assign that elemnt now with a value -1
  4. deque() works with the returned address
  5. when linked list size becomes greater than the array size, double the array, when its size becomes less than 1/4 the array size, reduce array size by 1/2 . ( these i can do in amortized time )

at step 3 , there will be some checks to see whether or not the array element chosen at random holds value -1 , if it doesnt , it will return the value and assign -1 to it , else iterate again till it finds a valid element.

somjit{} 60 Junior Poster in Training Featured Poster

this is a code i came up for randomized deque. its all good , except its failing in timing tests... my code takes up too much time, and its because i put up a getRanPointer() method that takes linear time to get each random node from the linked list...

if you could give some solutions on how to make the whole process run in constant amortized time (thats what is required) , it would be great...

import java.util.Iterator;

public class RandomizedQueue<Item> implements Iterable<Item> {

    private int size;
    private Node head, tail;

    private class Node {
        Item item;
        Node next;
        Node prev;
    }

    public RandomizedQueue() {
        head = new Node();
        head.next = null;
        head.prev = null;
        head.item = null;
        tail = head;
    }

    public boolean isEmpty() {
        return tail == head;
    }

    public int size() {
        return size;
    }

    public void enqueue(Item item) {
        if (item == null)
            throw new java.lang.NullPointerException(
                    " adding null values is not allowed ");
        else {
            Node oldTail = tail;
            tail = new Node();
            tail.item = item;
            tail.next = null;
            tail.prev = oldTail;
            oldTail.next = tail;
            size++;
        }
    }

    private Node getRanPointer() {
        int ran = 1 + StdRandom.uniform(size); // since head is a sentinel, so
                                                // actual database starts after
                                                // head , hence 1 is added
        Node pointer = head.next;
        for (int i = 1; i < ran; i++) { // as data starts from index 1 instead
                                        // of index 0 (which denotes the head)
            pointer = pointer.next;
        }
        return pointer;
    } …
somjit{} 60 Junior Poster in Training Featured Poster

In other words, in each iteration, the odds of choosing the current value are:
(number of values still needed) / (number of values left to choose from)

i took it from there....
if:

randomNum = random.nextInt()
odds = (number of values still needed) / (number of values left to choose from)
range being the range from which the samples have to be taken

then what i meant was that will

( odds x randomNum x range ) + min

this formula above , iterated over K times , give K sample units , such that no two sample units are the same?

im saying about this, because i feel that if this is possible, then the OP can put the range as 78 , and then keep a count , and when the count matches any of the numbers generated through this sampling process , he keeps that particular value , else disregards n and iterates again...

somjit{} 60 Junior Poster in Training Featured Poster

and store value in Set.If added successfully(means unique as set doesnot support duplicacy) means it is unique.

that sounds good... but what about the expense of storing the data in the set... ? if that isnt too expensive, then i guess its going to be a pretty good solution.
i talk about expense here coz i have a feeling that the Original poster wanted to use that particular method to reduce memory requirement from O(N) to O(K) , where N = total population, ie 78 , and K = sample size , ie 5 .

somjit{} 60 Junior Poster in Training Featured Poster

In other words, in each iteration, the odds of choosing the current value are:
(number of values still needed) / (number of values left to choose from)

so if i have to find 'k' non reapeating numbers from a certain 'range' , and if i do this:

((obtained random num).(odds).(range)) + min

will this be good?

also, if it does give good results, then that would mean the results are in uniform distribution, so calculating standard deviation over each sample should give a high value right ? my apologies if im being vauge, i havent touched statistics in over four years.. gone quite rusty..

somjit{} 60 Junior Poster in Training Featured Poster

that sounds like total rubbish to me

i also wanted to go with linked list, as its easy to code, and doesnt involve all the low level issues that you mentioned. .. really needed that clarification :D the only reason i made this post was to clear up the confusion i was having after reading a few of those posts over the web where they were making those claims...

But yes, this is an algorithm assignment, and the course involves in making algorithms to increase performance of codes in real world applications. so it probably will be tested for speed, with im assuming some pretty large queue size. Also, just like you mentioned, we have to keep our implementation private, such that the client doesnt have to know how the data structure is implemented, and design the code keeping in mind that it will be a part of a bigger application, as stacks and queues are fundamental datastructures.

So the part you talked about writing a small class to encapsulate the functionality, if you could tell more about that, it would really help me out a lot...

somjit{} 60 Junior Poster in Training Featured Poster

i have to create a queue where the dequeue operations will be random. that is , a random location will be chosen, and deleted after returning the data stored at that location.

i was going through the two underlying datastructures that im allowed to use : linked list , and arrays. ( i cant use any prebuilt java api like the prebuilt LinkedList or ArrayList classes for the task, and have to create the data structure on my own. )

my question is, which datastructure implementation would be the overall faster process? linked lists are faster in adding and deleting elements, also doesn't need resizing, but arrays are faster at random accessing. I wanted to go with linked list as i feel it will be easier to code, but im reading in a lot of places over the web at linkedlists being old, unfashioned n stuff... and arrays are the way to go.

any suggestion , and some explanations if possible, would be great..

thanks for your help. :)
somjit.