Register a SA Forums Account here!
JOINING THE SA FORUMS WILL REMOVE THIS BIG AD, THE ANNOYING UNDERLINED ADS, AND STUPID INTERSTITIAL ADS!!!

You can: log in, read the tech support FAQ, or request your lost password. This dumb message (and those ads) will appear on every screen until you register! Get rid of this crap by registering your own SA Forums Account and joining roughly 150,000 Goons, for the one-time price of $9.95! We charge money because it costs us money per month for bills, and since we don't believe in showing ads to our users, we try to make the money back through forum registrations.
 
  • Post
  • Reply
bartkusa
Sep 25, 2005

Air, Fire, Earth, Hope
If you shuffle the list before you sort it, doesn't that give you random output without needing a randomized Comparator?

Adbot
ADBOT LOVES YOU

The Laplace Demon
Jul 23, 2009

"Oh dear! Oh dear! Heisenberg is a douche!"

bartkusa posted:

If you shuffle the list before you sort it, doesn't that give you random output without needing a randomized Comparator?

Do this. A randomized comparator isn't going to actually be random. For example, if you use a stable sort, then it'll be biased towards keeping same-valued elements in their original order.

Max Facetime
Apr 18, 2009

supermikhail posted:

I have need of the following clever algorithm:

There is an ArrayList of Entries, wherein each Entry has associated with it a Date which can also be null. I'd like the "oldest" entry from the list, or, if there are several entries with the same Date, a random one from them. Except that they also can belong to another Skipping Collection, in which case look for another entry unless there are only entries belonging to that Skipping Collection. Whew...

I'm thinking about sorting by Date, but how to pick a random one then, especially with nulls (which, I think, should be randomly interspersed with non-skipped entries)?

For clarity, I guess:

code:
class Entry{

    Date date;

    public Entry(){ Date = null; } //created with null, only later set to a particular date; at least right now

    public void setDate(Date date){ this.date = date; }

}

HashMap<Entry, Integer> skippedEntries; //entries are skipped for a number of "turns"

public Entry getNextEntry(ArrayList<Entry> entries){

    ?

}

Java code:
  static class Entry {
    Date date;
  }

  static Entry find(List<Entry> entries, Map<Entry, Integer> skippedUntilTurn) {
    ToIntFunction<Entry> skippedComeAfter =
      (Entry entry) -> skippedUntilTurn.getOrDefault(entry, 0);
    ToLongFunction<Entry> olderComeFirst =
      (Entry entry) -> entry.date.getTime();
    Comparator<Entry> entryOrder =
      Comparator.comparingInt(skippedComeAfter).thenComparingLong(
        olderComeFirst);
    Predicate<Entry> keepEntriesWithDates = (Entry entry) -> entry.date != null;

    return entries
      .parallelStream().sorted(entryOrder).filter(keepEntriesWithDates)
      .findFirst().orElseThrow(NoSuchElementException::new);
  }
This might do what's required, but I didn't test it or anything. There's no explicit randomization: in the unlikely event that several Entries have the same UTC millisecond timestamp it's unspecified which one of them Stream#findFirst is going to pick. Needs Java 8 which will be released soon.

Jabor
Jul 16, 2010

#1 Loser at SpaceChem

Max Facetime posted:

There's no explicit randomization: in the unlikely event that several Entries have the same UTC millisecond timestamp it's unspecified which one of them Stream#findFirst is going to pick.

Keep in mind that "unspecified" is not the same as "random" - in fact it's very likely that the determination does not involve randomness at all.

If you want to choose randomly when presented with multiple entries that have identical timestamps, you can assign each entry a random value and use that as a third tier to the comparator (phoneposting so no code, but it's fairly straightforward).

Max Facetime
Apr 18, 2009

Jabor posted:

Keep in mind that "unspecified" is not the same as "random" - in fact it's very likely that the determination does not involve randomness at all.

Well, sufficiently bad pseudo-randomness is indistinguishable from "unspecified" (as you could always use the Stream as a replacement for your source of bad pseudo-randomness).

supermikhail
Nov 17, 2012


"It's video games, Scully."
Video games?"
"He enlists the help of strangers to make his perfect video game. When he gets bored of an idea, he murders them and moves on to the next, learning nothing in the process."
"Hmm... interesting."
I've realized something, and now I'm completely confused. By the way,

Max Facetime posted:

Java code:
  static class Entry {
    Date date;
  }

  static Entry find(List<Entry> entries, Map<Entry, Integer> skippedUntilTurn) {
    ToIntFunction<Entry> skippedComeAfter =
      (Entry entry) -> skippedUntilTurn.getOrDefault(entry, 0);
    ToLongFunction<Entry> olderComeFirst =
      (Entry entry) -> entry.date.getTime();
    Comparator<Entry> entryOrder =
      Comparator.comparingInt(skippedComeAfter).thenComparingLong(
        olderComeFirst);
    Predicate<Entry> keepEntriesWithDates = (Entry entry) -> entry.date != null;

    return entries
      .parallelStream().sorted(entryOrder).filter(keepEntriesWithDates)
      .findFirst().orElseThrow(NoSuchElementException::new);
  }

:psypop: Is Java 8 this crazy with operators, or is it just pseudocode?

Anyway. I remembered that the exact Date is not relevant for me; and how to select a random entry from several that are near each other in date... that's a whole other bag of worms.

ulmont
Sep 15, 2010

IF I EVER MISS VOTING IN AN ELECTION (EVEN AMERICAN IDOL) ,OR HAVE UNPAID PARKING TICKETS, PLEASE TAKE AWAY MY FRANCHISE

supermikhail posted:

:psypop: Is Java 8 this crazy with operators, or is it just pseudocode?

-> is the lambda syntax.

http://docs.oracle.com/javase/tutorial/java/javaOO/lambdaexpressions.html#syntax

Gravity Pike
Feb 8, 2009

I find this discussion incredibly bland and disinteresting.
I'm leaning heavily on Guava here, but maybe use Optional<Date> in a Multimap?
Java code:
public class EntryPicker {
    Random rand = new Random();
    Set<Optional<Date>> dates = Sets.newTreeSet(new Comparator<Optional<Date>>() {
        public int compare(Optional<Date> o1, Optional<Date> o2) {
            if (o1.equals(o2)) return 0;
            if (!o1.isPresent()) return -1;
            if (!o2.isPresent()) return 1;
            return (o1.get().compareTo(o2.get()));
        }
    });

    Multimap<Optional<Date>, Entry> entryMap = HashMultimap.create();

    public void add(Entry e) {
        Optional<Date> optDate = Optional.fromNullable(e.date);
        dates.add(optDate);
        entryMap.put(optDate, e);
    }

    public Entry get() {
        Iterator<Optional<Date>> dateIt = dates.iterator();
        if (!dateIt.hasNext()) {
            return null;
        }

        Optional<Date> firstDate = dateIt.next();
        Collection<Entry> entries = entryMap.get(firstDate);
        int randIndex = rand.nextInt(entries.size());
        Iterator<Entry> entryIt = entries.iterator();
        Entry returnEntry = null;
        for (int i = 0; i <= randIndex; i++) {
            returnEntry = entryIt.next();
        }

        if (entries.size() == 1) {
            dates.remove(firstDate);
        }
        entryMap.remove(firstDate, returnEntry);

        return returnEntry;
    }
}
Didn't fill out the "skipping" section, but it should be a pretty straightforward loop inside your "get."

Max Facetime
Apr 18, 2009

supermikhail posted:

I've realized something, and now I'm completely confused. By the way,


:psypop: Is Java 8 this crazy with operators, or is it just pseudocode?

Anyway. I remembered that the exact Date is not relevant for me; and how to select a random entry from several that are near each other in date... that's a whole other bag of worms.

Oh it compiles fine, but there's at least one runtime bug. The call Stream#sorted() is stateful so the filter() method has to be called before sorted() is called to avoid a NullPointerException.

I added grouping of the Entries at 1 day resolution and then selecting properly randomly from them, so all cases are handled now, I think? Still no test runs but I made it a one-liner instead!

Java code:
  static Entry findWithWholeDayGranularity(List<Entry> entries,
    Map<Entry, Integer> skippedUntilTurn) {
    return entries
      .stream()
      .filter((Entry entry) -> entry.date != null)
      .collect(
        Collectors.groupingBy(
          (Entry entry) -> skippedUntilTurn.getOrDefault(entry, 0),
          (Collector<Entry, ?, Map<Instant, List<Entry>>>) Collectors
            .groupingBy((Entry entry) -> entry.date.toInstant().truncatedTo(
              ChronoUnit.DAYS))))
      .entrySet()
      .stream()
      .min(
        Comparator
          .comparing((Map.Entry<Integer, Map<Instant, List<Entry>>> e) -> e
            .getKey()))
      .orElseThrow(NoSuchElementException::new)
      .getValue()
      .entrySet()
      .stream()
      .min(
        Comparator.comparing((Map.Entry<Instant, List<Entry>> e) -> e.getKey()))
      .map(
        (Map.Entry<Instant, List<Entry>> e) -> e.getValue().get(
          ThreadLocalRandom.current().nextInt(e.getValue().size())))
      .orElseThrow(NoSuchElementException::new);
  }

supermikhail
Nov 17, 2012


"It's video games, Scully."
Video games?"
"He enlists the help of strangers to make his perfect video game. When he gets bored of an idea, he murders them and moves on to the next, learning nothing in the process."
"Hmm... interesting."
I should have been clearer in my previous post. It's (practically) impossible to have two identical dates (except nulls), so the original question doesn't apply anymore. Instead, I'm trying to come up with a method that would retrieve the entries by approximate date (and random if they are nearby). But I don't want to manually set the margin of approximation. What would happen if I just took some percentage of random entries and selected the oldest from them? Maybe that's a question for the Math thread.

baka kaba
Jul 19, 2003

PLEASE ASK ME, THE SELF-PROFESSED NO #1 PAUL CATTERMOLE FAN IN THE SOMETHING AWFUL S-CLUB 7 MEGATHREAD, TO NAME A SINGLE SONG BY HIS EXCELLENT NU-METAL SIDE PROJECT, SKUA, AND IF I CAN'T PLEASE TELL ME TO
EAT SHIT

Wouldn't that skew all your choices to the older side of the distribution, and make the newer ones never come up at all? Since they'd always be ignored in favour of the older picks

I'm still not entirely sure what you want to do - like this thing about not manually setting the margin of approximation... what does determine it? It might help to lay out a step by step example of what you want to happen

supermikhail
Nov 17, 2012


"It's video games, Scully."
Video games?"
"He enlists the help of strangers to make his perfect video game. When he gets bored of an idea, he murders them and moves on to the next, learning nothing in the process."
"Hmm... interesting."

baka kaba posted:

Wouldn't that skew all your choices to the older side of the distribution, and make the newer ones never come up at all? Since they'd always be ignored in favour of the older picks

I'm still not entirely sure what you want to do - like this thing about not manually setting the margin of approximation... what does determine it? It might help to lay out a step by step example of what you want to happen

So the entries that do come up can either be updated to "now" (as the date), or "skipped". In any case they are in a different place the next time. This could for example be useful when you have many physical exercises to work on, and want to work on them uniformly. I've found that simple randomness can leave periods between reappearances of entries that are too long, and I'm trying to compensate for it. (The example is, by the way, just an example.) Basically, I'd like the method to watch out that entries do not get too old, but the definition of too old is problematic, considering that it should be relative to all the entries.

Hope this explanation helps.

So, as step-by-step as I know: from the collection get an entry randomly, or, if some are especially old, get one of those -> option a) move the entry to the newest end of the collection; option b) set the entry aside for a while, then (or when you run out of other entries) insert it back into the oldest entries -> repeat until tired.

Maybe a solution lies in this reworking of my problem.

Max Facetime
Apr 18, 2009

Maybe turn it around? If some old entries don't get picked often enough then it means newer entries get picked too often. This might be easier to track. To compensate it might be enough to add a random change to skip such an entry, proportional to how many times it's been chosen recently.

Nippashish
Nov 2, 2005

Let me see you dance!
It looks likely that I will need to start writing Java code in the not too distant future. I am a competent developer in C++ and python but I haven't touched Java since CS101. What should I read to bring myself up to speed on how to Java properly? In the near term I will need to write library, which should be distributable on its own, and also some code that uses that library inside of Hadoop.

I feel like I can probably muddle my way though the actual writing code part, but I know nothing about how a Java development workflow is supposed to work. Is Eclipse still the go-to IDE? What about build systems? How do I package code into a distributable library? How do I manage dependencies between projects? What things don't I know that I don't even know I don't know?

Gravity Pike
Feb 8, 2009

I find this discussion incredibly bland and disinteresting.
Eclipse or IntelliJ are the preferred Java IDEs. Maven in an incredibly popular dependency-management/build system; however, it suffers from being a dependency-management and a build system. I've heard good things about Gradle, but never used it myself.

If you want to learn idiomatic Java, I'd check out Java Concurrency in Practice. It would probably also be helpful to familiarize yourself with the Apache Commons and Guava libraries; these include the functionality that core Java doesn't, but should.

Edit: vv +1 Effective Java. It is the book whose name I was trying to remember but couldn't.

Gravity Pike fucked around with this message at 01:20 on Feb 13, 2014

Janitor Prime
Jan 22, 2004

PC LOAD LETTER

What da fuck does that mean

Fun Shoe
The answer to like 50 of your questions is Maven! Seriously read the docs and it will solve your dependencies, execute your build, run your tests, and create a neat and tidy package that is then callable from other maven projects.

Eclipse is still the goto IDE, but I prefer Netbeans since it has tighter Maven integration out of the box. Another tool I hear good praise for is IntelliJ, you really can't go wrong with any of them, try em out and pick the one that least offends you.

Also read Effective Java by Joshua Bloch once you're past the syntax to get some some deeper insight into Java design.

e: Yeah also Java Concurrency in Practice is a must if you're writing any kind of multi threaded code.

Volmarias
Dec 31, 2002

EMAIL... THE INTERNET... SEARCH ENGINES...

Janitor Prime posted:

The answer to like 50 of your questions is Maven! Seriously read the docs and it will solve your dependencies, execute your build, run your tests, and create a neat and tidy package that is then callable from other maven projects.

Eclipse is still the goto IDE, but I prefer Netbeans since it has tighter Maven integration out of the box. Another tool I hear good praise for is IntelliJ, you really can't go wrong with any of them, try em out and pick the one that least offends you.

Also read Effective Java by Joshua Bloch once you're past the syntax to get some some deeper insight into Java design.

e: Yeah also Java Concurrency in Practice is a must if you're writing any kind of multi threaded code.

I'm going to second Gradle over Maven if you have the choice. The problem with Maven is that he only asked a few questions, but maven will still answer 50 of them like it or not.

Eclipse has a not-entirely-undeserved reputation for severe bloat, although the IntelliJ debugger had some obnoxious tics when I last used it (What's that? You want to step per thread instead of stepping in a way that steps all threads simultaneously? Why would you possibly want to do that? :downs:)

You should probably take a look at both for each, then choose whatever your team is using.

Janitor Prime
Jan 22, 2004

PC LOAD LETTER

What da fuck does that mean

Fun Shoe
Seeing as how this is the Java thread this is probably the best place to start a serious discussion on Gradle. I've seen it brought up numerous times in other discussions and it seems to be gaining traction (especially with the Android stack), but from my quick glance I can't understand what problem it's trying to solve that Maven doesn't handle; other than it's not XML and it's not Maven.

Please enlighten me!

The Laplace Demon
Jul 23, 2009

"Oh dear! Oh dear! Heisenberg is a douche!"

Janitor Prime posted:

I can't understand what problem it's trying to solve that Maven doesn't handle; other than it's not XML and it's not Maven.

That's not enough for you? :v:

Woodsy Owl
Oct 27, 2004
I recently took up using Maven and it's great so far. My only grievance so far is that the documentation is a little schizophrenic. It is a bit overwhelming in it's usage scope though.

How's the Gradle documentation?

Volguus
Mar 3, 2009

Janitor Prime posted:

Seeing as how this is the Java thread this is probably the best place to start a serious discussion on Gradle. I've seen it brought up numerous times in other discussions and it seems to be gaining traction (especially with the Android stack), but from my quick glance I can't understand what problem it's trying to solve that Maven doesn't handle; other than it's not XML and it's not Maven.

Please enlighten me!

The good thing about maven is that it enforces its structure (good for new projects). The bad thing about maven is that it enforces its structure (bad for old projects looking to migrate to maven).
If you want to do anything in maven that other people didnt provide a plugin for you have to write your own plugin. In gradle, you can achieve your crazy ideas with a few lines of groovy.
Gradle plays well with the maven structure so if you like it you can keep on using it.

This is just from the top of my head, there are obviously lots of other more serious reasons why one should use one over the other.

pigdog
Apr 23, 2004

by Smythe
I'm not an expert on Gradle, but from what I've learned one of the main reasons is that it is, or can be, smarter about recompiling only the code that does need recompiling, which could save time in larger projects.

Posting Principle
Dec 10, 2011

by Ralp
Related to the book recommendations above, I really enjoyed The Well Grounded Java Developer. It covers additions to java concurrency that weren't in Java Concurrency In Practice, as well as giving an intro to a lot of other Java topics.

supermikhail
Nov 17, 2012


"It's video games, Scully."
Video games?"
"He enlists the help of strangers to make his perfect video game. When he gets bored of an idea, he murders them and moves on to the next, learning nothing in the process."
"Hmm... interesting."
If you know a more elegant solution, share!
code:
        Graphics graphics = getGraphics();
        FontMetrics metrics = graphics.getFontMetrics(taskL.getFont());

        int textWidth = metrics.stringWidth(text);

        int viewWidth = taskScrollpane.getViewport().getWidth();

        if (textWidth > viewWidth) {
            while (textWidth > viewWidth) {
                text = text.substring(0, text.length() - 1);
                textWidth = metrics.stringWidth(text + "...");
            }
            text = text + "...";
        }
        return text;
Context: In the effort to prevent the label taskL breaking the layout, I've put it in the taskScrollPane and the latter goes through the preceding code when resizing, and it also happens when I change the text.

Volguus
Mar 3, 2009

supermikhail posted:

If you know a more elegant solution, share!
code:
...
Context: In the effort to prevent the label taskL breaking the layout, I've put it in the taskScrollPane and the latter goes through the preceding code when resizing, and it also happens when I change the text.

The jlabel automatically puts ellipsis if the text it has to display is longer than its bounds. To make a jlabel wrap the text it should put between <html></html> tags.

What kind of layout do you have there that a jlabel can break? I can see that you have a JScrollPane, to which I presume you have disabled the vertical scrollbar. And then I presume the JPanel that is a child of that JScrollPane is Scrollable, so you have control over the width/height of the component.

I can't really imagine how can a layout be broken, but if that's the case and there's nothing that can be done about it, probably your code is the best way to go.

supermikhail
Nov 17, 2012


"It's video games, Scully."
Video games?"
"He enlists the help of strangers to make his perfect video game. When he gets bored of an idea, he murders them and moves on to the next, learning nothing in the process."
"Hmm... interesting."
Oh, no. (Maybe my Java is broken.)

The thing is thus:

JPanel ( JScrollpane ( JLabel ) )

And I'm using the scrollpane to find out if the panel is about to be pierced by the label. For some reason if I stuffed a long text in the label before that, the panel resized out of the frame which didn't (and in any case I don't think resizing the frame for changing text is practical). So I guess I could just try to set the size of the label directly and it would do the magic without touching the fonts themselves.

Or maybe it's just Netbeans.

Volguus
Mar 3, 2009

supermikhail posted:

Oh, no. (Maybe my Java is broken.)

The thing is thus:

JPanel ( JScrollpane ( JLabel ) )

And I'm using the scrollpane to find out if the panel is about to be pierced by the label. For some reason if I stuffed a long text in the label before that, the panel resized out of the frame which didn't (and in any case I don't think resizing the frame for changing text is practical). So I guess I could just try to set the size of the label directly and it would do the magic without touching the fonts themselves.

Or maybe it's just Netbeans.

So you have a JLabel in a JScrollPane? That sounds a bit weird. Why not use a JTextArea? And make it readonly (or disabled) and then it can properly handle multiline text for you. The layout of the panel handles the scrollpane, and the component in it. What layout manager are you using? GridBagLayout is a very flexible layout manager, it can handle pretty much any kind of layout you throw at it.

supermikhail
Nov 17, 2012


"It's video games, Scully."
Video games?"
"He enlists the help of strangers to make his perfect video game. When he gets bored of an idea, he murders them and moves on to the next, learning nothing in the process."
"Hmm... interesting."
Well, call me weird, but I don't want multiline text. I think design would be better for it. Anyway, labels really put ellipses in automatically, except you have to do some uncommon things to the properties. That'll sure clear some clutter. Thanks for your help.

supermikhail
Nov 17, 2012


"It's video games, Scully."
Video games?"
"He enlists the help of strangers to make his perfect video game. When he gets bored of an idea, he murders them and moves on to the next, learning nothing in the process."
"Hmm... interesting."
I feel that the probable inefficiency of this code is going to haunt me, so here is a bunch of it. If anyone could be bothered to take a look and post a comment, I would be very grateful.
code:
    public Task getNextInCategories(Collection<String> categories) {        
        ArrayList<Task> temp = getRemainingInCategories(categories); //method not shown but it's fairly reasonable

        //some fairly reasonable code

        //refer to the methods below
        Date recentDate = getMostRecentCompletionDate(temp);
        Date oldestDate = getOldestCompletionDate(temp);

        //First I convert dates into calendars because they allow to add days
        //The idea is basically to find out if the top of the list is too far from the bottom of the list (too far here being the arbitrary two days)

        Calendar oldestPlusDayCalendar = Calendar.getInstance();
        oldestPlusDayCalendar.setTimeInMillis(oldestDate.getTime());
        oldestPlusDayCalendar.add(Calendar.DATE, +2);

        Calendar recentCalendar = Calendar.getInstance();
        recentCalendar.setTimeInMillis(recentDate.getTime());

        Random rand = new Random();

        if (oldestPlusDayCalendar.compareTo(recentCalendar) >= 0) {
            nextTask = temp.get(rand.nextInt(temp.size()));
        } else {
            TaskByDateComparator comparator = new TaskByDateComparator();
            Collections.sort(temp, comparator);
            Date oldestPlusDay = new Date(oldestPlusDayCalendar.getTimeInMillis());

            //look for the method "lastIndex" below
            int lastOldIndex = lastIndex(oldestPlusDay, temp);
            if (lastOldIndex == 0) {
                nextTask = temp.get(0);
            } else {
                List<Task> subList = temp.subList(0, lastOldIndex);
                nextTask = subList.get(rand.nextInt(subList.size()));
            }
        }

        //some fairly reasonable code

        return nextTask;
    }

    private Date getMostRecentCompletionDate(Collection<Task> tasks) {
        Task t = Collections.max(tasks, new TaskByDateComparator());
        return t.getLastTimeDone();
    }

    private Date getOldestCompletionDate(Collection<Task> tasks) {
        Task t = Collections.min(tasks, new TaskByDateComparator());
        return t.getLastTimeDone();
    }

    private int lastIndex(Date date, List<Task> sortedTasks) {
        Task t;
        for (int i = 0; i < sortedTasks.size(); i++) {
            t = sortedTasks.get(i);
            if (t.getLastTimeDone().compareTo(date) > 0) {
                return i;
            }
        }
        return -1;
    }
Dang, I'm still calling it "PlusDay" even though it is "PlusTwo". Also, maybe it'd be better to store dates as longs? I hope that's not too much code. :ohdear:

Brain Candy
May 18, 2006

supermikhail posted:

:words: with Calendar and Date in it

Use JodaTime.

supermikhail
Nov 17, 2012


"It's video games, Scully."
Video games?"
"He enlists the help of strangers to make his perfect video game. When he gets bored of an idea, he murders them and moves on to the next, learning nothing in the process."
"Hmm... interesting."

Brain Candy posted:

Use JodaTime.

Nice. That's going to make the code much clearer, if nothing else.

No Safe Word
Feb 26, 2005

Brain Candy posted:

Use JodaTime.

This should be in the OP, if not be the entirety of the OP.

Gravity Pike
Feb 8, 2009

I find this discussion incredibly bland and disinteresting.
*Scroll down*
*See Calendar*

Ah! I know how he can make this-

Brain Candy posted:

Use JodaTime.

Yeah. Java's built-in date/time implementation is pretty crap.

Woodsy Owl
Oct 27, 2004
Does anyone feel that JavaFX is ready for production?

Zorro KingOfEngland
May 7, 2008

I like what I've seen of JDK 8's new java.time package, but I haven't had a chance to try it out yet. It looks like they took a lot of inspiration from JodaTime.

Posting Principle
Dec 10, 2011

by Ralp
That's because it was written mainly by the same person behind JodaTime. He keeps a blog of the work he's being doing on it http://blog.joda.org/

FAT32 SHAMER
Aug 16, 2012



Okay, so I'm having a bit of trouble with Linked Lists. Here's my assignment:

quote:

A circular list is a linked list in which the last link points back to the first link.
There are many ways to design a circular list.
Sometimes there is a pointer to the “start” of the list. However, this makes the list less like a real
circle and more like an ordinary list that has its end attached to its beginning.
  • Make a class for a singly linked circular list that has no end and no beginning.
  • The only access to the list is a single reference, current, that can point to any link on the list. This reference can move around the list as needed.
  • Your list should handle insertion, searching, and deletion.
  • You may find it convenient if these operations take place one link downstream of the link pointed to by current.
  • (Because the upstream link is singly linked, you can’t get at it without going all the way around
    the circle.)
  • You should also be able to display the list (although you will need to break the circle at some arbitrary point to print it on the screen). A step() method that moves current along to the next link might come in handy too.

They gave me this class to use to check to make sure the two classes I must make work
Java code:
package CircList;

public class CircApp
{
    public static void main(String[] args)
    {
        Link f, d;
        CircList theList = new CircList();
        
        theList.insert( 10 );
        theList.insert( 20 );
        theList.insert( 30 );
        theList.insert( 40 );
        theList.insert( 50 );
        theList.insert( 60 );
        theList.insert( 70 );
        
        theList.displayList();
        
        f = theList.find( 30 );
        if( f != null )
        {
            System.out.println( "Found link with key " + f.iData );
        }
        else
        {
            System.out.println( "Can't find linke with key 30." );
        }
        
        System.out.println( "Inserting the link with key 80." );
        theList.insert( 80 );
        theList.displayList();
        
        d = theList.delete( 60 );
        if( d != null )
        {
            System.out.println( "Deleted link with key " + d.iData );
        }
        else
        {
            System.out.println( "Can't delete link with key 60" );
        }
        theList.displayList();
        
        f = theList.find( 99 );
        if( f != null )
        {
            System.out.println( "Found link with key " + f.iData );
        }
        else
        {
            System.out.println( "Can't find link with key 99" );
        }
        theList.displayList();
        
        d = theList.delete( 13 );
        if( d!= null )
        {
            System.out.println( "Deleted link with key " + d.iData );
        }
        else
        {
            System.out.println( "Can't delete link with key 13" );
        }
        theList.displayList();
        
        System.out.println( "Stepping through the list" );
        for( int j = 0; j < theList.getSize(); j++ )
        {
            theList.step();
            theList.displayList();
        }
        
        System.out.println( "Will delete and step one by one" );
        while( theList.isEmpty() == false )
        {
            theList.delete();
            theList.step();
            theList.displayList();
        }
    }
}

Here is the first class I must make, I'm pretty sure what I have is good:
Java code:
package CircList;

public class Link
{
    public long iData;
    public Link next;
    
    public Link( long id )
    {
        this.iData = id;
    }
    
    public void displayLink()
    {
        System.out.println( iData );
    }
}

Now here is where I'm getting confused. Each method I have here is laid out in the assignment, I just have to populate it with code.
Java code:
package CircList;

public class CircList
{
    private Link current;
    private int count = 0;
    
    public CircList()
    {
        
    }//constructor
    
    public boolean isEmpty()
    {
        if( current == null )
        {
            return true;
        }
        else
        {
            return false;
        }
    }
    
    public int getSize()
    {
        return count;
    }
    
    public void insert( long id )
    {
        
    }//insert after current link
    
    public Link delete()
    {
        
    }//delete one beyond current
    
    public Link find( long key )
    {
        
    }//find link with given key
    
    public Link delete( long key )
    {
        
    }//delete link with given key
    
    public void displayList()
    {
        
    }//display the list
    
    public void step()
    {
        while( current != null && current.next != null )
        {
            current = current.next;
        }
    }
    
    public Link peek()
    {
        
    }
}

The lecture that was supposed to be on linked lists was cancelled due to a snow storm, which wasn't a big deal until I realised that the professor didn't upload the lecture slides and she assigned us hw due tomorrow that involves a relatively complex linked list. I get that with a circular linked list, the last node must also be the first, so I assume that it has to equal whatever the first node is. However, what I'm not getting is how to create the node itself. In all the examples of it I've seen online, it's a class/method explicitly called "somethingNode". I'm guessing that the node creation in my assigment is supposed to occur in method insert() and the node removal is supposed to occur in method delete() or method delete( long key ) based on whether we want to delete a specific node or the node that is next up in the list.

I'm also not sure what to do with method peek() and what to do with the constructor for the CircList class nor am I exactly sure what the class Link is supposed to do much less why some of the methods in class CircList are of type Link. I managed to get a pretty solid understanding of stacks yesterday in time for an assignment, but Linked Lists are throwing me for a loop and any insight would be extremely appreciated.

edit: I did make an attempt to populate some of the methods with code, how well I did it or if it's even the right idea remains to be seen.

FAT32 SHAMER fucked around with this message at 22:21 on Feb 20, 2014

Janitor Prime
Jan 22, 2004

PC LOAD LETTER

What da fuck does that mean

Fun Shoe
Basically in this assignment your Nodes are called Link, see how CircList has a next element of type Link in it? In your insert method you just create a new Link with the given id and attach it to the other links.

The methods aren't of type Link, they return a Link! So the peek method should just return current Link, delete will remove current from the chain and return it etc..

Janitor Prime fucked around with this message at 23:43 on Feb 20, 2014

FAT32 SHAMER
Aug 16, 2012



Janitor Prime posted:

Basically in this assignment your Nodes are called Link, see how CircList has a next element of type Link in it? In your insert method you just create a new Link with the given id and attach it to the other links.

The methods aren't of type Link, they return a Link! So the peek method should just return current Link, delete will remove current from the chain and return it etc..

Okay, that makes WAY more sense! What should I do for the constructor since the current = new Link( id ) is in the insert method? Call method insert( long id )?

Adbot
ADBOT LOVES YOU

Janitor Prime
Jan 22, 2004

PC LOAD LETTER

What da fuck does that mean

Fun Shoe
I think an empty constructor is appropriate for that data structure, you normally use it to set initial values for your variables but there really isn't anything to do here.

  • 1
  • 2
  • 3
  • 4
  • 5
  • Post
  • Reply