[랜덤 마라톤] Logo(4197)

lhs's avatar
Nov 29, 2024
[랜덤 마라톤] Logo(4197)
notion image
notion image

1. 문제 풀이 아이디어

  • 위치와 각도를 저장하는 객체를 만들어 Math 라이브러리의 삼각 함수(sin, cos)를 활용하면 문제를 해결할 수 있다.
  • 위치와 각도를 별도의 변수로 저장하는 것보다 객체로 관리하면 코드가 더 깔끔하고 유지보수가 용이할 것 같아 객체를 사용했다.

2. 나의 정답 코드

public class Main { public static void main(String[] args) throws IOException { BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(System.in)); StringBuilder stringBuilder = new StringBuilder(); int t = Integer.parseInt(bufferedReader.readLine()); for (int i = 0; i < t; i++) { int n = Integer.parseInt(bufferedReader.readLine()); Turtle turtle = new Turtle(); for (int j = 0; j < n; j++) { StringTokenizer stringTokenizer = new StringTokenizer(bufferedReader.readLine()); String command = stringTokenizer.nextToken(); int value = Integer.parseInt(stringTokenizer.nextToken()); switch (command) { case "bk": value *= -1; case "fd": turtle.move(value); break; case "rt": value *= -1; case "lt": turtle.turn(value); break; } } stringBuilder.append(turtle.getDistance()).append('\n'); } System.out.print(stringBuilder); bufferedReader.close(); } } class Turtle { private double x, y, degree; public void move(int dist) { x += Math.cos(Math.toRadians(degree)) * dist; y += Math.sin(Math.toRadians(degree)) * dist; } public void turn(int degree) { this.degree += degree; } public long getDistance() { return Math.round(Math.sqrt(x * x + y * y)); } }

3. 정리

  • 위치와 각도를 저장하는 Turtle 객체를 구현하고, Math의 sin과 cos 함수를 사용해 위치를 계산한다.
  • 뒤로 이동(bk)이나 오른쪽 회전(rt) 명령어는 -1을 곱해 처리한다.
  • 마지막에 거리를 계산해 반환하며 문제를 해결한다.
Share article

LHS's Study Space