Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to avoid the repeated code in java?

Tags:

I'm just beginner in programming. uf is a union-find class with the method union which connects the roots of two node. This piece of code is responsible for opening a site of a grid and union the site with its neighbor if any of neighbor is opened. And if one of its neighbors is full, then fill all nodes that connected with the site. This is the actual code:

        if(i == 1){
            uf.union(len*len, xyTo1D(i,j));
            if(existAndOpen(i+1,j)){
                uf2.union(xyTo1D(i+1,j), xyTo1D(i,j));
                uf.union(xyTo1D(i,j), xyTo1D(i+1,j));
            }
            if(existAndOpen(i-1,j)){
                uf2.union(xyTo1D(i-1,j), xyTo1D(i,j));
                uf.union(xyTo1D(i,j), xyTo1D(i-1,j));
            }
            if(existAndOpen(i,j-1)){
                uf2.union(xyTo1D(i,j-1), xyTo1D(i,j));
                uf.union(xyTo1D(i,j), xyTo1D(i,j-1));
            }
            if(!(j == len && i == len)){
                if(existAndOpen(i,j+1)){
                    uf2.union(xyTo1D(i,j+1), xyTo1D(i,j));
                    uf.union(xyTo1D(i,j), xyTo1D(i,j+1));
                }
            }
        }
        else{
        if(existAndFull(i+1,j)){
            uf2.union(xyTo1D(i+1,j), xyTo1D(i,j));
            uf.union(xyTo1D(i,j), xyTo1D(i+1,j));
        }
        if(existAndFull(i-1,j)){
            uf2.union(xyTo1D(i-1,j), xyTo1D(i,j));
            uf.union(xyTo1D(i,j), xyTo1D(i-1,j));
        }
        if(existAndFull(i,j-1)){
            uf2.union(xyTo1D(i,j-1), xyTo1D(i,j));
            uf.union(xyTo1D(i,j), xyTo1D(i,j-1));
        }
        if(!(j== len && i == len)){
            if(existAndFull(i,j+1)){
                uf2.union(xyTo1D(i,j+1), xyTo1D(i,j));
                uf.union(xyTo1D(i,j), xyTo1D(i,j+1));
            }
        }
        if(existAndOpen(i+1,j)){
            uf.union(xyTo1D(i,j), xyTo1D(i+1,j));
        }
        if(existAndOpen(i-1,j)){
            uf.union(xyTo1D(i,j), xyTo1D(i-1,j));
        }
        if(existAndOpen(i,j-1)){
            uf.union(xyTo1D(i,j), xyTo1D(i,j-1));
        }
        if(!(j== len && i == len)){
            if(existAndOpen(i,j+1)){
                uf.union(xyTo1D(i,j), xyTo1D(i,j+1));
            }
        }
    }
    }

How can I simplify the code?