Page 3 of 3 FirstFirst 123
Results 41 to 53 of 53
  1. #41
    gcalvin is offline Senior Member
    Join Date
    Mar 2010
    Posts
    953
    Rep Power
    5

    Default

    Sonny, don't worry a bit about this esoteric discussion on the Java for-each loop and the enum's inherent values() method. In any case, it has nothing to do with your deal() method. To the extent it has anything to do with your DeckOfCards() constructor, trust me, you don't need to worry about it for the slightest fraction of a second. What you have now is exactly what is recommended by the Java documentation and tutorial writers, and we have no evidence that it is not optimal -- only speculation. This is the same kind of speculation that suggests that
    Java Code:
            for (int i = 0; i < myString.length(); i++) {
                    ...
            }
    is less efficient than
    Java Code:
            int z = myString.length();
            for (int i = 0; i < z; i++) {
                    ...
            }
    because "length() has to be computed each time through the loop!!!" I say superstition, hogwash, humbug, and prove it. This is the very definition of premature optimization. Don't fall prey to it. I would gladly trade a little efficiency for improved readability, for one thing, and for another, I don't believe we're paying even the slightest performance penalty, and won't believe it until it's demonstrated to me with hard numbers.

    Anyway, back to your deal() method. This is so, so, so, so, so simple that you're going to kick yourself when you solve it. Big hint: it involves adding one more instance variable to your DeckOfCards class -- an int. As for what your deal() method should do when there are no cards left to be dealt, it seems to me the reasonable choices are:
    1. return null
    2. throw an Exception
    and I'm pretty sure I would choose #1.

    -Gary-

  2. #42
    JosAH's Avatar
    JosAH is offline Moderator
    Join Date
    Sep 2008
    Location
    Voorschoten, the Netherlands
    Posts
    13,519
    Blog Entries
    7
    Rep Power
    20

    Default

    Quote Originally Posted by gcalvin View Post
    This is the same kind of speculation that suggests that
    Java Code:
            for (int i = 0; i < myString.length(); i++) {
                    ...
            }
    is less efficient than
    Java Code:
            int z = myString.length();
            for (int i = 0; i < z; i++) {
                    ...
            }
    because "length() has to be computed each time through the loop!!!" I say superstition, hogwash, humbug, and prove it.
    Java Code:
    
    public class AAA {
    
    	public static void main(String[] args) {
    
    		StringBuffer sb= new StringBuffer();
    		String s;
    		
    		for (int i= 0; i < 10000000; i++)
    			sb.append("x");
    		
    		s= sb.toString();
    		
    		for (int i= 0; i < 10; i++) {
    			
    			long start, end;
    			
    			sb.setLength(0);
    			
    			start= System.currentTimeMillis();
    			for (int j= 0; j < s.length(); j++)
    				sb.setLength(0); // do something
    			end= System.currentTimeMillis();
    			
    			System.out.print((end-start)+" ");
    			
    			start= System.currentTimeMillis();
    			for (int j= 0,n= s.length(); j < n; j++)
    				sb.setLength(0);  // do something
    			end= System.currentTimeMillis();
    
    			System.out.println((end-start)+" ");
    		}
    			
    	}
    }
    The results:

    Java Code:
    525 517 
    516 505 
    510 505 
    510 506 
    511 505 
    512 505 
    511 504 
    509 505 
    513 508 
    512 510
    Yup, it's a bit faster not to call that method all the time.

    kind regards,

    Jos

  3. #43
    gcalvin is offline Senior Member
    Join Date
    Mar 2010
    Posts
    953
    Rep Power
    5

    Default

    Quote Originally Posted by JosAH View Post
    Yup, it's a bit faster not to call that method all the time.

    kind regards,

    Jos
    Looks like you're right, but it's not nearly enough to worry about, especially for "normal"-sized Strings. Looks like it was around a six-millisecond average difference on your run, and closer to nine-millisecond average on mine, at ten-million-character Strings. So we're talking about an average difference of about a nanosecond. I'll take that hit in the name of readability.
    Java Code:
    public class AAA {
    
    	public static void main(String[] args) {
    
    		StringBuffer sb= new StringBuffer();
    		String s;
    		int[] stringSize = {10, 100, 1000, 10000, 100000, 1000000, 10000000};
    		for (int ss : stringSize) {
    			for (int i= 0; i < ss; i++)
    				sb.append("x");
    
    			s= sb.toString();
    
    			for (int i= 0; i < 10; i++) {
    
    				long start, end;
    
    				sb.setLength(0);
    
    				start= System.currentTimeMillis();
    				for (int j= 0; j < s.length(); j++)
    					sb.setLength(0); // do something
    				end= System.currentTimeMillis();
    
    				System.out.print((end-start)+" ");
    
    				start= System.currentTimeMillis();
    				for (int j= 0,n= s.length(); j < n; j++)
    					sb.setLength(0);  // do something
    				end= System.currentTimeMillis();
    
    				System.out.println((end-start)+" ");
    			}
    		}
    	}
    }
    Java Code:
    10 character String
    0 0 
    0 0 
    0 0 
    0 0 
    0 0 
    0 0 
    0 0 
    0 0 
    0 0 
    0 0 
    100 character String
    0 0 
    0 0 
    0 0 
    0 0 
    0 0 
    0 0 
    0 0 
    0 0 
    0 0 
    0 0 
    1000 character String
    1 0 
    0 0 
    1 0 
    0 0 
    6 0 
    0 0 
    0 0 
    0 0 
    0 0 
    0 0 
    10000 character String
    1 1 
    1 0 
    0 0 
    1 1 
    1 1 
    [COLOR="Red"]1 2 
    [/COLOR]1 0 
    1 1 
    1 0 
    1 0 
    100000 character String
    5 4 
    5 4 
    5 4 
    [COLOR="Red"]4 5 
    4 5 
    4 5 [/COLOR]
    6 6 
    7 4 
    5 4 
    5 4 
    1000000 character String
    44 43 
    47 43 
    46 45 
    46 44 
    45 44 
    45 43 
    47 44 
    49 44 
    44 44 
    45 45 
    10000000 character String
    457 443 
    447 437 
    453 437 
    447 437 
    444 440 
    446 437 
    444 440 
    443 442 
    446 439 
    448 437
    -Gary-

  4. #44
    JosAH's Avatar
    JosAH is offline Moderator
    Join Date
    Sep 2008
    Location
    Voorschoten, the Netherlands
    Posts
    13,519
    Blog Entries
    7
    Rep Power
    20

    Default

    Quote Originally Posted by gcalvin View Post
    Looks like you're right, but it's not nearly enough to worry about, especially for "normal"-sized Strings. Looks like it was around a six-millisecond average difference on your run, and closer to nine-millisecond average on mine, at ten-million-character Strings. So we're talking about an average difference of about a nanosecond. I'll take that hit in the name of readability.
    Yup, method calls are fast in Java and the length() method doesn't have to count all those characters in the String (unlike C's strlen() function) so it doesn't matter much here; I still have the funny habit to write this:

    Java Code:
    for (int i= 0, n= s.length(); i < n; i++)
       ...
    I find that quite readable as well ...

    kind regards,

    Jos (old C sod ;-)

  5. #45
    gcalvin is offline Senior Member
    Join Date
    Mar 2010
    Posts
    953
    Rep Power
    5

    Default

    Yep, it's quite a different story with C's strlen(). And I'm certainly not one of those who says "Forget performance! Forget conserving memory! Computers are fast and have lots of RAM now!" Optimization, proper algorithm selection, conservation of resources, all of these things are important, but perspective is even more important, especially while learning. I see too many beginners trying to cram all their code into main(), and I suspect they think a method call is "inefficient". Wasting time trying to decipher code logic six indent-levels deep is what's really inefficient.

    As you have pointed out, one doesn't want to get lost in the gory details, at least not until your overall program is working. Then, by all means, put it under a profiler, stress test it, identify the bottlenecks and fix them.

    Kudos for doing the legwork and coming up with numbers!

    -Gary-

  6. #46
    JosAH's Avatar
    JosAH is offline Moderator
    Join Date
    Sep 2008
    Location
    Voorschoten, the Netherlands
    Posts
    13,519
    Blog Entries
    7
    Rep Power
    20

    Default

    Quote Originally Posted by gcalvin View Post
    Yep, it's quite a different story with C's strlen(). And I'm certainly not one of those who says "Forget performance! Forget conserving memory! Computers are fast and have lots of RAM now!" Optimization, proper algorithm selection, conservation of resources, all of these things are important, but perspective is even more important, especially while learning. I see too many beginners trying to cram all their code into main(), and I suspect they think a method call is "inefficient". Wasting time trying to decipher code logic six indent-levels deep is what's really inefficient.
    Ever so true; most people don't realize that methods simply increase your 'vocabulary' and methods are ideal to split all that convoluted control flow in manageable pieces. So they cram everything in wallpaper sized main( ... ) methods that make everyone dizzy ;-)

    Quote Originally Posted by gcalvin View Post
    As you have pointed out, one doesn't want to get lost in the gory details, at least not until your overall program is working. Then, by all means, put it under a profiler, stress test it, identify the bottlenecks and fix them.
    Ever so true again and an efficient algorithm pays back big time over early (micro) optimizations; except for those little thingies that are burned in my fingers (so I'm innocent) such as that String.length() little thing ;-)

    Quote Originally Posted by gcalvin View Post
    Kudos for doing the legwork and coming up with numbers!
    I didn't do anything; my laptop did all the dirty work, I only typed the source code, Eclipse whined and ran the code for me ;-)

    kind regards,

    Jos

  7. #47
    sonny's Avatar
    sonny is offline Senior Member
    Join Date
    Feb 2010
    Location
    North West England
    Posts
    146
    Rep Power
    0

    Thumbs up And Oh yes Dealing :-p

    Quote Originally Posted by gcalvin View Post
    Sonny, don't worry a bit about this esoteric discussion on the Java for-each loop and the enum's inherent values() method.
    LOL i skimmed through the posts earlier on my iphone and kinda got the wrong end of the stick... tiny mobile screens whilst convenient are not particularly practical for long technical threads...whilst being dragged round the shopping center... when i got home, i had few hours before the kids got in so i spent a while reading the docs, with a strange idea in my mind about copies of Arraylists,, a wild goose chase yes,, but not a completely pointless exercise,:)

    there are some interesting points about performance and algorithms and conserving memory etc by doing things the right way I dont understand it all of course but some of the points certainly make sense, like not trying to cram everything into one method,, ah yes ,, and taking the vast amounts of RAM for granted.

    but back to the dealing

    i'd declared an Ivar for an index
    Java Code:
    /* create an instance variable for the current card */
    	private int cardIndex;
    and then intialised it to zero at the end of my constuctor,, and / or i could initialise in my shuffle method.

    but within deal method i think i need to include something like

    Java Code:
    int theCard = cardIndex
    cardIndex++
    return theCard.
    but this is just an int that represents the number of the card in the deck i'm referring to.
    PlayingCard.get(theCard) will get me the object

    and now the kids are in bed i should accomplish this quite easily.

    and if i can avoid the interesting distractions in the forum, hopefully, get through that eclipse tutorial.
    :p I still have my "L" plates on...... directions and explanations are far more help than blaring your Horn! :p Watching:CS106a on YouTube \Reading The Art & Science of Java by Eric S Roberts

  8. #48
    Singing Boyo is offline Senior Member
    Join Date
    Mar 2009
    Posts
    552
    Rep Power
    6

    Default

    Quote Originally Posted by JosAH View Post
    import sun.misc.SharedSecrets;
    Try looking here - sun.misc: public class: SharedSecrets

    I can't get over the fact that they named a class SharedSecrets though... Sounds like a class from a bad diary app :p
    If the above doesn't make sense to you, ignore it, but remember it - might be useful!
    And if you just randomly taught yourself to program, well... you're just like me!

  9. #49
    sonny's Avatar
    sonny is offline Senior Member
    Join Date
    Feb 2010
    Location
    North West England
    Posts
    146
    Rep Power
    0

    Default

    The dealing was easy once i emptied my head of copying arrays and stuff & nonsense, but i get errors and eclipse throws a wobbler if you try to deal 53 times
    im calling deal 53 times with a for loop
    Java Code:
    for (int i = 0; i<53;i++){
    		println(one.dealCard());
    and ive tried rearranging the if else various differnt ways to no avail
    why does not it just return null and be done with it??? :confused:

    with this arrangement of the if else it does print null on the last line which i dont think it did with other arrangements

    Java Code:
    public PlayingCard dealCard(){
    		int theCard = cardIndex;
    		cardIndex++;
    		if(theCard>cards.size())return null;
    		else {
    			PlayingCard card = cards.get(theCard);
    			return card;
    		}
    	}
    ive even been looking round the debug windows:confused:
    i can see this
    Thread [main] (Suspended)
    The top two are telling me that 52 is not in the array i think
    but why is it even looking in the array
    ArrayList<E>.RangeCheck(int) line: not available
    ArrayList<E>.get(int) line: not available
    DeckOfCards.dealCard() line: 40 (( int theCard = cardIndex;))
    this DeckOfCards (id=30)
    cardIndex 53
    cards ArrayList<E> (id=29)
    rgen RandomGenerator (id=48)
    then it has a box with value null in it

    RandomCards.run() line: 22
    RandomCards(Program).runHook() line: 1592
    RandomCards(Program).startRun() line: 1581
    RandomCards(Program).start(String[]) line: 838
    RandomCards(Program).start() line: 1250
    Program.main(String[]) line: 1340

    EDIT
    err okay really simple... but am bit confussed
    Java Code:
    if(theCard[COLOR="Red"]>=[/COLOR]cards.size())
    if its equal to the cards.size (card.size is 0 to 51)
    if its 51 and returns Null,
    sureley the last card should not come out..
    but it does??
    and i now have no errors even if i deal 60 cards:confused:

    but it works!!!!!!!!!!!!!!
    YES!

    @ Gary, Jos and Tolls,, thanks a bunch guys
    who would have thought a simple little exercise that i solved with a horrible if else in one class, would lead to me discovering enums array lists the efficiency of for loops and all sorts of other crazy stuff besides...
    kind regards,

    Sonny
    Last edited by sonny; 04-01-2010 at 11:58 PM.
    :p I still have my "L" plates on...... directions and explanations are far more help than blaring your Horn! :p Watching:CS106a on YouTube \Reading The Art & Science of Java by Eric S Roberts

  10. #50
    gcalvin is offline Senior Member
    Join Date
    Mar 2010
    Posts
    953
    Rep Power
    5

    Default

    Very good. We still need to get you to simplify, simplify (to abuse Thoreau), but you've basically got it.

    I'm not sure why you're knocking around with 53 and 51, but it's not too surprising really -- off-by-one errors, or "fencepost" errors are some of the most frustrating, and just seem to be really baffling to the human mind. But you'll get the hang of it like we all did.

    So the simpler form is basically this:
    Java Code:
            public PlayingCard dealCard() {
                    if (cardIndex >= cards.size()) return null;
                    return cards.get(cardIndex++);
            }
    Your other code is responsible to check for that null when it calls dealCard(), and if it doesn't, it should expect an Exception (except that the only method we're likely to call on a PlayingCard is toString(), and toString() works fine on null).

    Nice job! Tackle that Mark Dexter tutorial, and tell me what you think.

    -Gary-

  11. #51
    sonny's Avatar
    sonny is offline Senior Member
    Join Date
    Feb 2010
    Location
    North West England
    Posts
    146
    Rep Power
    0

    Thumbs up Mehran, eat your heart out! Mark Dempster ROCKS!

    i got a bit annoyed downloading the Mark Dempster tutorials
    sourceforge. makes you go back and forth re extending the list every time, i download a few in hungarian cos i wasn't paying attention.. Doh!

    my evening didnt go as planned so only managed three and just about to take in four and maybee five WOW!
    scrapbook thats brilliant
    wizards to set stuff out will certainly help to organise my thinking more clearly.
    ive just been using a stanford package template, i hadn't even considered how to create packages myself.

    I like the way he is approaching it straight away with writing a simple practical class which is a different perspective for me, and while i have seen this approach in a few books it didn't seem to make a lot of sense, having done BASIC many moons ago, and possibly because the books use quite silly example ideas like explorer robot class and stuff as their first example. but, it makes better sense now, and i can certainly see myself using these together with cs106a


    Java Code:
     public PlayingCard dealCard() {
                    if (cardIndex >= cards.size()) return null;
                    return cards.get[COLOR="Red"](cardIndex++)[/COLOR];
            }
    i like that its clever,, but it looks like the first cardIndex value it will get is 1 rather than 0,, but i'll come back to that another time along with the O.B.O.E.
    in fact i can test it scrapbook..:cool: but after I watch Marks' four and five, ive had enough of cards for a day or two LOL
    kind regards
    Sonny
    :p I still have my "L" plates on...... directions and explanations are far more help than blaring your Horn! :p Watching:CS106a on YouTube \Reading The Art & Science of Java by Eric S Roberts

  12. #52
    m00nchile is offline Senior Member
    Join Date
    Feb 2010
    Location
    Ljubljana, Slovenia
    Posts
    470
    Rep Power
    5

    Default

    Quote Originally Posted by sonny View Post
    Java Code:
     public PlayingCard dealCard() {
                    if (cardIndex >= cards.size()) return null;
                    return cards.get[COLOR="Red"](cardIndex++)[/COLOR];
            }
    i like that its clever,, but it looks like the first cardIndex value it will get is 1 rather than 0,, but i'll come back to that another time along with the O.B.O.E.
    Sonny
    Nope, it all depends on where the ++ (or --) sign is.
    Java Code:
    int a = 5, b = 3;
    int c = (a++) + (++b);
    the resulting variable c would get the value of 9. a++ means use first, then increment, ++b means increment first, then use. So in the case a++, it does the calculation with the value 5, and then increments it to 6, b on the other hand has the ++ operator as a prefix, so it is incremented to 4, then used in the calculation. If you consider the dealCard() method, the ++ operator is postfix, so it returns the card with the current cardIndex, then increments it.
    Last edited by m00nchile; 04-02-2010 at 06:41 AM.

  13. #53
    sonny's Avatar
    sonny is offline Senior Member
    Join Date
    Feb 2010
    Location
    North West England
    Posts
    146
    Rep Power
    0

    Thumbs up Cheers

    Quote Originally Posted by m00nchile View Post
    Nope, it all depends on where the ++ (or --) sign is.
    Java Code:
    int a = 5, b = 3;
    int c = (a++) + (++b);
    the resulting variable c would get the value of 9. a++ means use first, then increment, ++b means increment first, then use. So in the case a++, it does the calculation with the value 5, and then increments it to 6, b on the other hand has the ++ operator as a prefix, so it is incremented to 4, then used in the calculation. If you consider the dealCard() method, the ++ operator is postfix, so it returns the card with the current cardIndex, then increments it.
    @ m00chile

    thanks mate
    yet another cool thing i learden from one one little question:cool:

    and there was I, looking forward to doing a Junit test....
    @ Gary lesson 5 & 6 how cool are they!!!
    Last edited by sonny; 04-02-2010 at 10:58 AM.
    :p I still have my "L" plates on...... directions and explanations are far more help than blaring your Horn! :p Watching:CS106a on YouTube \Reading The Art & Science of Java by Eric S Roberts

Page 3 of 3 FirstFirst 123

Similar Threads

  1. round to two decimal places
    By javaMike in forum New To Java
    Replies: 3
    Last Post: 12-24-2011, 02:01 AM
  2. stopping second time round
    By silverspoon34 in forum New To Java
    Replies: 0
    Last Post: 11-20-2009, 02:04 PM
  3. How to Draw Round Rectangles in SWT
    By Java Tip in forum SWT Tips
    Replies: 0
    Last Post: 06-28-2008, 09:25 PM
  4. How to round a double?
    By Valeriano in forum New To Java
    Replies: 1
    Last Post: 05-31-2007, 03:50 PM

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •