java - How to navigate a Barbie in a grid system? -
i'm trying solve interesting problem navigating barbie doll inside grid system. initially, barbie in [0,0] position, means in intersection of x , y axis. barbie has 3 operations on movement 'f' forward, 'r' right turn (90 degree) , 'l' left turn (90 degree). say, if pass direction string of "ff", position should [0,2]. solve problem , current state of code following,
public static void barbieposition(string str ){ if( str == null || str.length() == 0) return; int [] initial = {0,0}; boolean xpos = false, xneg = false, ypos = true, yneg = false; char[] ch = str.tochararray(); for( char c: ch){ // initial postion of robot towards positive y axis if(c == 'l'){ if(xpos){ xpos = false; ypos = true; } else if ( xneg){ xneg = false; yneg = true; } else if(ypos){ xneg = true; ypos = false; } else if (yneg){ yneg = false; xpos = true; } } else if ( c == 'r'){ if(xpos){ xpos = false; yneg = true; } else if ( xneg){ ypos = true; xneg = false; } else if(ypos){ ypos = false; xpos = true; } else if (yneg){ yneg = false; xneg = true; } } else if (c == 'f'){ if(xneg){ initial[0] -= 1; } else if (xpos){ initial[0] += 1; } else if (yneg){ initial[1] -=1; } else if( ypos){ initial[1] += 1; } } } system.out.println(arrays.tostring(initial)); } the thing don't solution it's feels ugly. there better way design algorithm ?
what constitutes 'forward' in application function of previous move. forward means repeat last move.
if forward first move need pick convention says "barbie moving right".
Comments
Post a Comment