John Mercier

java programming and scjp

  • Blog
  • Projects

Testing .equals()

Posted on June 12, 2011 by John J Mercier

Filed under Programming | 0 Comments

I've recently been reading Effective Java, by Joshua Bloch, and the section about the equals() method has sparked my interest. The book explains that there are 5 properties that equals must enforce. equals() must be reflexive, symmetric, transitive, consistent, and non-null. While I was reading I though about how easy it would be to make methods that tests all of these attributes for any object in java. Each property can have its own test, and there can be one method to test all attributes. Before starting this I tried to see what netbeans comes up with for the generated equals test. Unfortunately, it does not test for all these properties. Here is what I came up with.[Read More]

Share |

Storing 24 Game data

Posted on October 12, 2010 by John J Mercier

Filed under 24 Game | 0 Comments

So what good is knowing all of the card combinations that have a solution of 24 without actually doing something with them. Well maybe this will eventually become a game. So I need to store this data so I can use it in the future. From the perspective of making a game it would be nice to pick a random combination (from 1 to 2133) and get the cards for that number. My first thought was to print these to a random access file with 4 integers per record but it kind of seems like a waste of space with numbers from 1 to 9 doesn't it? I mean a value of 9 takes 4 bits to represent while an integer is 32 bits. 4 cards will only take 16 bits rather than 128. Even if you use bytes for the cards it will take 32 bits, twice as much storage space. Here is a table:

Number Size

Record Size(x4)

File Size(x2133)

Saved

32 bit

128 bit

273024 bit (267kb)

0

16 bit

64 bit

136512 bit (133kb)

136512 bit (133kb)

8 bit

32 bit

68256 bit (67kb)

68256 bit (67kb)

4 bit

16 bit

34128 bit (33kb)

34128 bit (33kb)

There is a total savings of 238896 bit (233kb).

So this brings me to the point of this post, how to compress the 4 cards. Since I am dealing with 4 bit numbers and java does not have a 4 bit type I'm going to have to do some bit twiddling. There are two methods one called encode4Bit and the other called decode4Bit. encode4Bit takes 4 integers and encodes them into one short. decode4Bit takes a short and returns the 4 original integers.

Keep in mind that each integer can only have a value between 0 and 15 for this to work. So some validation code would be ideal (remember the illegal argument exception in java).

Encoding the integers is the easy part. Take each integer and use “or” to add it to a short. At each iteration move the bits left by 4. Here is the code:

    public static short encode4Bit(int... c) {
        short code = 0;
        if (c.length <= 4) {
            for (int i : c) {
                if (i < 0 || i > 15) {
                    throw new IllegalArgumentException("encode9Cards only accepts cards from 0 to 15");
                }
            }
        } else {
            throw new IllegalArgumentException("encode9Cards only accepts up to 4 integers");
        }
        Arrays.sort(c);
        System.out.println(Arrays.toString(c));
        int move = 0;
        for (int i : c) {
            i = i << move;
            move += 4;
            code = (short) (code | i);

        }

One thing you may have noticed is I added a sort before encoding the integers. This is so I can be absolutely sure I have no duplicate sets of 4 cards down the road. If any of the encoded numbers are the same then I know there are duplicates. I have a feeling that when the ordering of numbers does not matter there will be duplicate combinations. An example would be when all the operations are the same such as 1*1*3*8 and 9+9+4+2. So before saving these 16bit numbers I can make sure each one is unique.

Decoding the short into 4 integers gave me some trouble. For some reason right shifting with shorts does not work as expected. Here is some code as an example:

        System.out.println("number = " + number);
        number = (short) (number << 12);
        System.out.println("number = " + number);
        number = (short) (number >>> 12);
        System.out.println("number = " + number);
        number = (short) (number << 12);
        System.out.println("number = " + number);
        number = (short) (number >>> 12);
        System.out.println("number = " + number);

        int number2 = 15;
        System.out.println("number = " + number2);
        number2 = number2 << 12;
        System.out.println("number = " + number2);
        number2 = number2 >>> 12;
        System.out.println("number = " + number2);
        number2 = number2 << 12;
        System.out.println("number = " + number2);
        number2 = number2 >>> 12;
        System.out.println("number = " + number2);

The output is:

number = 15

number = -4096

number = -1

number = -4096

number = -1 <--- should be 15!

number = 15

number = 61440

number = 15

number = 61440

number = 15

So as you can see using shorts does not work. Right now I'm not sure why this is happening. I have a feeling it has something to do with everything with less bits than an integer always being promoted to a short. When you right shift the 0s are put in front of an integer instead of a short and are lost once the cast is made.

Here is the decode method:


    public static int[] decode4Bit(short c) {
        int cards[] = {0, 0, 0, 0};
        int card = 0;
        for (int j = 0; j <= 3; j++) {
            card = c;
            card = card >>> (4 * j + 16);
            card = card << (12 + 16);
            card = card >>> (12 + 16);
            cards[j] = card;
        }
        return cards;
    }

I had to add 16 to the shifts so the card is still treated like a short.

Overall this works the way it should. I have also tested it with all of the combinations. Now all I have to do is write the file... and the game.

Share |

24 Output

Posted on October 11, 2010 by John J Mercier

Filed under 24 Game | 0 Comments

This is the output for 24.[Read More]

Share |

24 Game

Posted on October 11, 2010 by John J Mercier

Filed under Projects | 0 Comments

Does anyone remember the 24 card game? It's played with a deck of cards minus the face cards and 10. So there are four suits of 1(ace) to 9. Then the cards are divided between two players and each player lays two cards on the table. The first player to use those cards, along with addition, subtraction, multiplication, and division, to get to 24 wins the pile. The game is fun and easy but how can you calculate if four numbers are solvable? How many combinations of the 40 cards have solutions?

Yesterday I wrote a program that there are 6561 possible combinations and 2133 card combinations with solutions of 24. First the program loops through each combination of cards. Then it checks each combination to see of there is a solution of 24. I also wrote a method that will print the solution with parenthesis to keep the precedence of each operator correct. There are also options to customize the game. You can change the low and high cards, check for solutions other than 24 and even check for a range of solutions. Instead of putting this project in a jar file I'm just going to post the code here and the output here.

[Read More]

Share |

How to edit Places in the ubuntu menu

Posted on October 04, 2010 by John J Mercier

Filed under General | 0 Comments

Editing Places is easy. They come from nautilus bookmarks. Open nautilus, select Bookmarks then edit bookmarks. This is very helpful to me because I use DropBox and all of my places are actually in the dropbox folder.

Share |

How to fix minimize, maximize, and close in ubuntu

Posted on October 04, 2010 by John J Mercier

Filed under General | 0 Comments

Hello, I know it's been a while so I'm going to share this. In ubuntu the window buttons to minimize, maximize and close the window are in the upper left corner. I guess they are trying to steer away from the Microsoft way of doing things. To fix this you have to edit the gnome configuration.

  1. Go to a terminal and type gconf-editor.
  2. select /apps/metacity/general in the folder pane
  3. double click button_layout
  4. change the value to "menu:minimize,maximize,close"

The change should be instant. This should work in any linux distribution that uses gnome.

Share |

Favorite Posts for the Week #3

Posted on May 17, 2010 by John J Mercier

Filed under General | 0 Comments

Well, I haven't been reading my google reader as much as I should so I only have a few links to share.

MDA posted a fitness challenge.

Modern Paleo posted a recipe for greek chicken and another for pork in yellow curry.

NoodleFood made a good comment on the genocidal muslim student.

Sorry, for the short list and lack of comments. The next one should be better.

Share |

SCJP Master Exam Notes

Posted on May 16, 2010 by John J Mercier

Filed under Programming | 0 Comments

I recently took a Master Exam from the Sierra and Bates SCJP book and got a 53%. While I was answering questions I noted any problem I had with a question. Today, I'm going through these notes and the exam report to see what needs work. Also, why not make a blog entry out of it? The following list are things I need to remember for the next exam.

HashMap.size() returns the number of key-value mappings in this map.

The rules for overriding equals() and hashCode()

must consistently return the same integer, provided no information used in equals() is modified

if two objects are equal using equals() then they must return the same hashCode()

if two objects are not equal using equals() then they can have the same hashCode(), or a different hashCode()

calling method((short)7) with method(short x) and method(short... x) in the class will always use method(short x) instead of method(short... x).

Is-A relationships always rely on polymorphism!

Comparator

an interface

override compare(T o1, T o2);

returns 0 if o1.equals(o2)

returns negative if o1 is less than o2

returns positive if o1 is greater than o2

Static variables are not serialized (not sure if I need to know this on the new version of SCJP)

Interfaces cannot have static methods. Interface methods cannot have a body so a static method doesn't make sense. Interface methods are alway public abstract. Interface variables are always public static and final.

What is the difference between high cohesion and loose coupling?

High cohesion is how strong a class's responsibilities are related and focused. For SCJP questions member variables and methods should be related. If a method doesn't interact with a member variable then it is probable not a cohesive method.

Loose coupling is how much information one class needs from another to perform methods. Loose coupling in SCJP would be one class using accessors rather than public member variables.

Encapsulation encourages loose coupling by not sharing member variables directly to other classes or subclasses. Instead public setters and getters are used.

Learn the different variations in generics. <T> input<T>(), <? extends T> <? super T>. All of that.

Can abstract come after a class name? No. I thought this was false but decided I should look it up.

Is TreeSet sorted? Yes according to my Java pocket guide, it is. I believe this means it must implement the comparable interface, or be constructed with a comparator.

Can an Integer constructor take "17" as a param? Yes. Darn, I think I got this one wrong on the exam.

What is the regex "." metacharacter? It matches with any single character. I'm guessing this means in the alphabet.

What does subMap() do? The subMap() method returns a NavigableMap that is linked to the original map. There are some catches.

  • Any new entries can be added to the original Map. new entries added to the submap must be within the range used to create the submap.
  • New entries added to the original map within the range of the submap are also added to the submap.
  • New entries added to the original map outside the range of the submap are not added to the submap.
  • New entries added to the submap are also added to the original map.
  • Using pollFirstXxx() on the original map will only remove from the submap if the entry polled is in the range of the submap.
  • Using pollFirstXxx() on the submap will remove the entry from the original map.
  • One other thing to remember is that the boolean values of headMap, tailMap, and subMap will include the arguments in the submaps.
  • Also, all of these ideas are the same for the Set collections.

Can TreeSet.ceiling() return the argument? Yes. from the javadoc "Returns the least element in this set greater than or equal to the given element, or null if there is no such element." So, if the argument is equal to an entry that entry will be returned.

How to get DateFormat with Locales? Use DateFormat.getDateInstance(DateFormat.LONG, Locale.FRANCE);

  • Also Only one DateFormat is needed to format many Date objects.

What are FileReader and BufferedReader classes? How are they different classes?

FileReader is an InputStreamReader which is a subclass of Reader. BufferedReader is a subclass of Reader as well. They both read characters from a source into a character array or CharBuffer. The major differences are FileReader reads only files, InputStreamReader can read any InputStream (ie file or network stream), and BufferedReader can Buffer any Reader using the Is-A and Has-A relationships similar to the InputStream and BufferedInputStream. I believe this is called the Decorator design pattern.

Share |

javaranch scjp roundup

Posted on May 11, 2010 by John J Mercier

Filed under Programming | 0 Comments

This post is a roundup of all the interesting posts I have found on javaranch along with my comments. Expect to see more of these as I continue to study for SCJP.

Magic! Magic! The way this works should be obvious. When you start your program with * as a command line argument it will get a list of filenames.

Master exam question. A good question about binarySearch in the Arrays class. You have to understand how an insertion point is returned if the Object is not in the array. Insertion point (-(insertion point) - 1) "The insertion point is defined as the point at which the key would be inserted into the array: the index of the first element greater than the key, or a.length if all elements in the array are less than the specified key. Note that this guarantees that the return value will be >= 0 if and only if the key is found."

serialization. Well it's not the serialization part that is important. The second question in the post talks about the JavaBeans naming convention. For SCJP getVariable, setVariable, addListener, removeListener, and isTrue are valid names.

Method Local Inner classes. It is true that method variables need to be marked final when they are used in method local classes.

http://www.coderanch.com/t/493547/java-programmer-SCJP/certification/Local-variables-type-mismatch-int

The problem here is compile-time constants. When an int is less than or equal to 127 and declared as such, final int i = 127, it is a compile-time constant. It is also able to be assigned to a byte without a cast because the compiler knows it is small enough. This also works with short.

pattern matching. In regex there is a key difference between the patterns "a*" and "aa*" The first looks for zero or more "a" at each index, and the second looks for an "a" followed by zero or more "a".

Share |

Favorite Posts for the Week #2

Posted on May 11, 2010 by John J Mercier

Filed under General | 2 Comments

Sorry this is late but nobody is really reading it anyway.

Health

Mark's Daily Apple has a good post, The Difinitive Guide to Sugar, that describes in detail the different kinds of sugar and their effects on health. The best part is where he explains why you should avoid sugar.

  • Sugar stimulates a physiological stressor-reaction cascade that provokes adrenaline and cortisol release and thickens the blood.
  • Sugar effectively disables your immune system by impairing white blood cells’ functioning.
  • Sugar decreases your body’s production of leptin, a hormone critical for appetite regulation.
  • Sugar induces significant oxidative stress in the body.
  • Sugar appears to fuel cancer cells. (Check out Free the Animal for much more on the cancer connection.)
  • Sugar promotes fat storage and weight gain.
  • Sugar disrupts the effective transfer of amino acids to muscle tissue.
  • Sugar intake over time spurs insulin resistance, subsequent Type II diabetes and the entire host of related health issues like nerve damage and cardiovascular disease.
  • I also found a post on artificial sweeteners that you may want to look at. Also, isn't lactose a sugar? I would like to see more info on that.

    Meatza is pizza that uses groud beef for the crust.

    On The Paleo Diet there is a Q&A that talks about lectins, saponins, and gliadin. I broke them down in this table.

     Antinutrient  Found In  Why it is not healthy
     lectins cereal grains and legumes  increasing intestinal permeability, resistant to digestive enzymes, deposited in the internal organs
     saponins  legume sprouts  affect the gut barrier and by extension immune system function, may also increase the risk of autoimmune diseases in genetically susceptible individuals
     gliadins  wheat  resistant to digestive enzyme degradation, arrives intact when it comes into contact with intestinal epithelial cells, increases intestinal permeability
     phytate  bran and seeds inhibits the intestinal absorption of iron, magnesium, calcium and zinc

     Diana Hsieh wrote a nice post with links to making paleo friendly foods.

    and here is A Story on Circumcision.

    Philosphy

     Mistaking fact with opinion. I like to read threads like this because they point out something that can really cause problems with reasoning. The idea is that arguing with opinions rather than facts is a huge mistake. In a society it will lead to mass uncertainty.

    Politics

    Arguments for government spending. People take this seriously.

    1) The political push to reduce government deficits is economically misguided, based on an irrational "phobia" of deficits.

    2) If we want economic growth, we need more spending. Only banks and governments can stimulate spending because, "Governments and banks are the two entities with the power to create something from nothing."

    3) Increasing spending by having the government do it is preferable to having the private greedy selfish bankers do it. And the real reason bankers oppose government spending is because it competes with their private lending.

    4) We shouldn't worry about the so-called impending bankruptcy of Social Security or Medicare or of the US government itself. The government is the source of money and therefore can't run out.

    5) Nor is government debt a "burden on future generations", because it never has to be repaid. Each generation can just pass it onto the next generation, so there's no problem.

    A real example of lobbying doing terrible things.

    I do think at a certain point you become a socialist!

    Share |

    Main | Next page »
    • General (12)
    • Projects (3)
    • Programming (14)

    Search

    Tag Cloud

    activism addthis.com data_structure downloading facebook google google-buzz introduction java javablackbelt jdbc johnmercier.com jsp linux model-1 netbeans nvidia objectivism official-english programming projects pti roller scjp server sql theme uncertainty velocity welfare-state

    Friends

    • Ed
    • Shane

    Links

    • Glazed Lists
    • JGoodies
    • Java Specialists
    • Swing 2.0
    • Swing Generics
    • ideone
    • pircbot

    Feeds

    • All
    • /General
    • /Projects
    • /Programming
    • Comments

    Referrers

    • direct (121)
    • keflex.tr.gg/KEFLEX- (10)
    • pheromones-to-attrac (8)
    • www.beeplog.com/2609 (6)
    • softbanhtc.info/site (5)
    • softaxianhtc.info/si (5)
    • softbanhtc.info/site (5)
    • softbanhtc.info/site (5)
    • softbanhtc.info/site (5)
    • softcelandroid.info/ (5)
    • softaxianhtc.info/si (5)
    • softbanhtc.info/site (5)
    • softcelandroid.info/ (5)
    • softcelandroid.info/ (5)
    • softcelandroid.info/ (5)
    • softaxianhtc.info/si (5)
    • softcelandroid.info/ (5)
    • softcelandroid.info/ (5)
    • softcelandroid.info/ (5)
    • softaxianhtc.info/si (5)
    • softcelandroid.info/ (5)
    • softcelandroid.info/ (5)
    • softcelandroid.info/ (5)
    • softcelandroid.info/ (5)
    • softaxianhtc.info/si (5)
    • softcelandroid.info/ (5)
    • softcelandroid.info/ (5)
    • softcelandroid.info/ (5)
    • softaxianhtc.info/si (5)
    • softcelandroid.info/ (5)

    Navigation

    • John Mercier
    • Weblog
    • Login

    ©2010 John J Mercier.

    Designed by Free CSS Templates. Template by E. Strokin. Powered by Roller Weblogger 4.0.1.