This site requires JavaScript, please enable it in your browser!
Greenfoot back
JasonZhu
JasonZhu wrote ...

2014/5/9

Int openCorner() method

JasonZhu JasonZhu

2014/5/9

#
I'm writing an int openCorner() method that returns the position of the board. I have it working I believe, but I need help simplifying it. Thanks. The position is the same as row * 3 + col.
    private int openCorner()
    {
        boolean topLeft = false;
        boolean topRight = false;
        boolean bottomLeft = false;
        boolean bottomRight = false;

        if(board[0][0].isAvailable()){
            topLeft=true;
        }
        if(board[0][2].isAvailable()){
            topRight=true;
        }
        if(board[2][0].isAvailable()){
            bottomLeft=true;
        }
        if(board[2][2].isAvailable()){
            bottomRight=true;
        }

        ArrayList<Integer> pos = new ArrayList<Integer>();
        if(topLeft==true){
            pos.add(0);
        }
        if(topRight==true){
            pos.add(2);
        }
        if(bottomLeft==true){
            pos.add(6);
        }
        if(bottomRight==true){
            pos.add(8);
        }

        Random gen = new Random();

        if(pos.size()==0){
            return -1;
        }else{
            return pos.get(gen.nextInt(pos.size()));
        }
    }
JasonZhu JasonZhu

2014/5/9

#
I broke it down to this:
    private int openCorner()
    {
        boolean topLeft = board[0][0].isAvailable();
        boolean topRight = board[0][2].isAvailable();
        boolean bottomLeft = board[2][0].isAvailable();
        boolean bottomRight = board[2][2].isAvailable();

        ArrayList<Integer> pos = new ArrayList<Integer>();
        if(topLeft) pos.add(0);        
        if(topRight) pos.add(2);
        if(bottomLeft) pos.add(6);
        if(bottomRight) pos.add(8);
        
        Random gen = new Random();
        if(pos.size()==0){
            return -1;
        }else{
            return pos.get(gen.nextInt(pos.size()));
        }
    }
danpost danpost

2014/5/9

#
How about this:
private int openCorner()
{
    for (int c=0; c<4; c++)
    {
        if (board[(c/2)*2][(c%2)*2].isAvailable()) break;
        if (c == 3) return -1;
    }
    int n = Greenfoot.getRandomNumber(4);
    while (!board[(n/2)*2][(n%2)*2].isAvailable()) n = Greenfoot.getRandomNumber(4);
    return (n/2)*6+(n%2)*2;
}
You need to login to post a reply.