Java by Example - sorting and shuffling

back 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21

Two of the most needed algorithms (not only) for game programming are sorting and shuffling of a series (an array) of numbers. The following applet combines them in an easy to understand and pleasant to look at manner. It also features three custom drawn buttons, for sorting, shuffling and drawing new numbers. On every draw 77 new numbers (represented by the int MAX) in the range 1 to 200 are drawn: getNewNumbers() and are stored in the array number[]. In this method it is also made sure that the same number is never drawn twice, to demonstrate this algorithm here too (although it is by no means advisable to use this technique always. A series of truely random numbers almost always includes doubles!). To get the array sorted, we use the method sortArray() and the helper method sort(int, int). Since simple data types cannot be passed by reference (as they can in C/C++), we need to declare two separate int variables a and b to hold the values of the sorting in every loop we call the sort(int,int) method.

To (re)shuffle the array, we use the method shuffle, which replaces every element of the array with a randomly selected other element.
In the method drawStuff() we use a tricky piece of code to draw the content of each array element in a neatly arranged table, whenever the array is sorted:

int j=15;
int k=10;

for(i=0;i<MAX;i++)
{
    if(sorted)
        gBuffer.drawString(""+number[i],k,j);

    if((i+1)%11==0){k=10;j+=10;}
        else {k+=20;}
}

i+1%11==0 means, "whenever the rest of a division of i+1 with 11 is 0". Since we have 77 array elements, I arranged the numbers in 11 columns and 7 rows. So, when the 11th element in a row is drawn, the y coordinate for the next row is incremented by 10 pixels and the x coordinate is assigned the value 10, for the first column. Else, the x value for the numbers is incremented by 20 pixels in each round of the loop.

In order for the custom drawn buttons (the Java buttons are just plain ugly and cannot be placed where you want) to react on mouseMove and mouseDown events, we place methods of our FancyButton class inside our according applet methods. This way we can submit the mouse coordinates to our button objects and can submit mouse clicks within the button rectangles, to set the public boolean flag variable "pressed" and to make the button appear pressed (last argument in the draw3DRect method).

//Sourcecode

import java.awt.*;
import java.applet.*;

class FancyButton
{
    private String text;
    public boolean over, pressed;
    private Rectangle r=new Rectangle();
    private Graphics g;
    private Font font;
    private Color color=new Color(180,180,65);

    public FancyButton(String s, int x, int y, int w, int h)
    {
        text=s;
        r.x=x;
        r.y=y;
        r.width=w;
        r.height=h;

        font=new Font("Dialog", Font.PLAIN, 10);
    }

    public void reportMouseMovement(int x, int y)
    {
        if(r.inside(x,y))
            over=true;
        else
            over=false;
    }

    public void reportMouseDown(int x, int y)
    {
        if(r.inside(x,y))
            pressed=true;
    }

    private void drawButton()
    {
        g.setColor(color);

        if(!over)
        {
            g.drawRect(r.x,r.y,r.width,r.height);
        }
        else
        {
            g.draw3DRect(r.x,r.y,r.width,r.height,!pressed);
        }

        //measure the size of the string to center it
        FontMetrics fm = g.getFontMetrics(font);
        int stringWidth=fm.stringWidth(text);
            int stringHeight=g.getFontMetrics().getAscent()+6;

        g.setFont(font);
        g.setColor(Color.black);

        //center the string inside the button
        g.drawString(text, (r.x+r.width/2)-stringWidth/2,
        r.y+r.height-stringHeight/2);
    }

    public void paint(Graphics gr)
    {
        g=gr;
        drawButton();
    }
}

public class Project43 extends Applet
{
    Image Buffer;
    Graphics gBuffer;
    Font font;
    int a,b,i,j,number[];
    final static int MAX=77;
    boolean sorted;
    FancyButton fb1,fb2,fb3;

    public void init()
    {
        Buffer=createImage(size().width,size().height);
        gBuffer=Buffer.getGraphics();
        font=new Font("Helvetica", Font.PLAIN, 10);

        fb1=new FancyButton("Sort",50,215,80,25);
        fb2=new FancyButton("Shuffle",150,215,80,25);
        fb3=new FancyButton("New Numbers",250,215,100,25);

        number = new int[MAX];

        getNewNumbers();
    }

    void getNewNumbers()
    {
        //fill our array with random numbers
        //guarantee different numbers to be drawn!
        for (i=0;i<MAX;i++)
        {
            //Random number from 1 to 200
            int rnd = ((int)(Math.random()*200)+1);

            number[i]=rnd;

            if (i>0)
            {
                for (j=i;j>0;j--)
                {
                    if (number[i]==number[j-1])
                        i--;
                }
            }
        }
    }

    void sort(int k, int l)
    {
        if(k>l)
        {
            int temp=k;
            k=l;
            l=temp;
        }
        a=k;
        b=l;
    }

    void sortArray()
    {
        for(i=0; i<MAX; i++)
        {
            for(j=i+1;j<MAX;j++)
            {
                sort(number[i],number[j]);

                number[i]=a;
                number[j]=b;
            }
        }
    }

    void shuffle()
    {
        for(i=0; i<MAX; i++)
        {
            j=(int)(Math.random()*MAX);

            if(i!=j)
            {
                int temp=number[i];
                number[i]=number[j];
                number[j]=temp;
            }
        }
    }

    public void drawStuff()
    {
        gBuffer.setColor(new Color(235,235,210));
        gBuffer.fillRect(0,0,size().width,size().height);

        gBuffer.setColor(Color.black);
        gBuffer.drawRect(0,0,size().width-1,size().height-1);

        for(i=0;i<MAX;i++)
        {
            gBuffer.setColor(Color.red);
            gBuffer.fill3DRect(i*5+8,205-number[i],4,number[i],true);
        }

        fb1.paint(gBuffer);
        fb2.paint(gBuffer);
        fb3.paint(gBuffer);

        gBuffer.setFont(font);
        gBuffer.setColor(Color.blue);

        j=15;
        int k=10;

        for(i=0;i<MAX;i++)
        {
            if(sorted)
                gBuffer.drawString(""+number[i],k,j);

            if((i+1)%11==0){k=10;j+=10;}
                else {k+=20;}
        }
    }

    public boolean mouseMove(Event evt,int x,int y)
    {
        fb1.reportMouseMovement(x,y);
        fb2.reportMouseMovement(x,y);
        fb3.reportMouseMovement(x,y);

        repaint();
        return true;
    }

    public boolean mouseDown(Event evt,int x,int y)
    {
        fb1.reportMouseDown(x,y);
        fb2.reportMouseDown(x,y);
        fb3.reportMouseDown(x,y);

        if(fb1.pressed){sortArray();sorted=true;}
        if(fb2.pressed){shuffle();sorted=false;}
        if(fb3.pressed){getNewNumbers();sorted=false;}

        repaint();
        return true;
    }

    public boolean mouseUp(Event evt,int x,int y)
    {
        fb1.pressed=fb2.pressed=fb3.pressed=false;

        repaint();
        return true;
    }

    public void update(Graphics g)
    {
        paint(g);
    }

    public void paint(Graphics g)
    {
        drawStuff();

        g.drawImage (Buffer,0,0, this);
    }
}

back 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21

0 - setup - getting your tools ready
1 - basic graphics functions
2 - simple methods and basic data types
3 - IF, ELSE and SWITCH: basic control structures
4 - introducing the operators
5 - methods with and without a return value
6 - using methods and basic mouse functions
7 - fonts, random numbers and timers
8 - flicker free graphics, GIF and JPEG display
9 - animation with GIF pictures, sprite animation
10 - loops, advanced color functions
11 - random colors and arrays
12 - digital clocks, HTML page parameters
13 - introducing classes and objects
14 - using the Vector class
15 - using mouseMove and mouseDrag
16 - keyboard commands and playing sound
17 - detecting collisions and intersections
18 - a Bouncing Balls applet
19 - fun with letters and words
20 - rotating lines and polygons
21 - sorting and shuffling


© 2000 by Johannes Wallroth
www.programming.de

watson@programming.de