Writing a string in a spiral

后端 未结 11 1036
别那么骄傲
别那么骄傲 2020-12-30 11:29

I had recently participated in coding competion sponsored by an company and there was this one question which I did not understood, as to what was it asking.

Here i

11条回答
  •  失恋的感觉
    2020-12-30 11:45

    First you fill a 6x6 matrix with point characters.Then you set direction to 1.Then you change direction each time the next character in the direction is not a point character.

    public class Spiral {
    static String phrase="paypalisthefastersaferwaytosendmoney";
    static int deltax,deltay,direction;
    
    public static void setDelta(){
    if(direction==1){
        deltax=1;
        deltay=0;
    }else if(direction==2){
        deltax=0;
        deltay=1;
    }else if(direction==3){
        deltax=-1;
        deltay=0;
    }else if(direction==4){
        deltax=0;
        deltay=-1;
    }
    }
    
    public static void main(String[] args) {
    int index=0,x,y,N=6;
    char[][] MATRIX=new char[N][N];
    for(y=0;y=0 && y=0){
                MATRIX[y][x]=phrase.charAt(index);
                System.out.print(MATRIX[y][x]);
                index++;
    
                    if(direction==1 && MATRIX[y][x+1]!='.' || x+1==N-1) break;
                    if(direction==2 && MATRIX[y+1][x]!='.' && y=0) break;
    
                x+=deltax;
                y+=deltay;
            }
            if(direction==4) direction=1;
            else direction++;
            setDelta();
    
            x+=deltax;
            y+=deltay;
        }   
    }
    
    }
    

提交回复
热议问题