Friday, August 15, 2008

One of the reasons I love my job

I love the different types of problems I get to solve with logic every day. For example today I had x amount of buttons that I had to distribute equally between 2 panels.

My original loop looked like:
JPanel addTo = leftPanel;
for( StatusType type : StatusType.values() )
        {
           int half = StatusType.values().length/2;
            if (type.warnClient)
            {
                StatusCheckBox cb = new StatusCheckBox( type );
                //alternate panels so we get an equal distribution
                if(type.ordinal() > half )
                {
                    addTo = rightPanel;
                }
                addTo.add( cb );
            }
        }
This loop yielded an unequal distribution of 3 buttons of the left and 5 on the right because most of the type.warnClient == true types were in the end of the array. That distribution looked like crap:


To better the distribution the first idea was to iterate through the loop twice, once to figure out how the warnClient==true values in the loop are distributed (i.e. where the actual half way point is) and then once I have the actual correct half value iterate the loop again with the correct halfway point. This is obviously not the best route.

In my case I don't care about the order of the buttons so instead I changed the loop algorithm to this:
for( StatusType type :StatusType.values() )
        {
            if (type.warnClient)
            {
                StatusCheckBox cb = new StatusCheckBox( type );
                //alternate panels so we get an equal distribution
                if(addTo == leftPanel)
                {
                    addTo = rightPanel;
                }
                else
                {
                    addTo = leftPanel;
                }
                addTo.add( cb );
            }
        }

This loop simply alternates putting a checkbox first on the leftPanel and then on the rightPanel guaranteeing proper distribution and I only have to iterate the loop once. Woot, a properly distributed set of checkboxes!

0 comments:

Buy Prints

Search darrickcoleman.com

Blog Archive

  © Blogger template 'Photoblog II' by Ourblogtemplates.com 2008

Back to TOP