Robotics sum-2
Problem the input "R","L","U","D" denotes to right, left, up and down respectively. The integer that nearer to the above charecters are the points that move towards the graph.
Input: n="R10L5U5D10"
- If the input consists of R10 we should move 10 points towards right.
- If the input consists of L5 we should move 5 points towards left.
- If the input consists of U5 we should move 5 points towards up.
- If the input consists of D10 we should move 10 points towards down.
output
- After performing all the process print the X and Y coordinates.
Example-1:
Input : n = "R10L5U5D10" Output : 5 -5 Explain : The final output is x=5 and y=-5.
Example-2:
Input : n = "R7R3L4L2U12" Output : 4 12 Explain : The final output is x=4 and y=12.
Example-3:
Input : n = "U10L20R10" Output : -10 10 Explain : The final output is x=-10 and y=10.
Solution
public class Main { public static void main(String[] args) { String s = "R10L5U5D10"; char before = s.charAt(0); int num = 0; int x = 0,y = 0; for (int i=0;i<s.length();i++) { if(s.charAt(i)>='0' && s.charAt(i)<='9') { num = (num*10) + Character.getNumericValue(s.charAt(i)); } if(!(s.charAt(i) >= '0' && s.charAt(i) <= '9')||i == s.length()-1) { if(before=='R') x = x + num; else if(before=='L') x = x-num; else if(before=='D') y = y-num; else { y = y + num; } num = 0; before=s.charAt(i); } } System.out.print(x+" "+y); } }
import re n = "R10L5U5D10" x1 = [] x2 = [] y1 = [] y2 = [] r = re.findall("R+[0-9]+",n) l = re.findall("L+[0-9]+",n) u = re.findall("U+[0-9]+",n) d = re.findall("D+[0-9]+",n) for i1 in range(len(r)): k1 = r[i1] a1 = int(k1[1:]) x1.append(a1) for i2 in range(len(l)): k2 = l[i2] a2 = int(k2[1:]) x2.append(a2) for i3 in range(len(u)): k3 = u[i3] a3 = int(k3[1:]) y1.append(a3) for i4 in range(len(d)): k4 = d[i4] a4 = int(k4[1:]) y2.append(a4) x = sum(x1)-sum(x2) y = sum(y1)-sum(y2) print(x,y)
Output
5 -5