kanetaiの二次記憶装置

プログラミングに関するやってみた、調べた系のものをQitaに移して、それ以外をはてブでやる運用にしようと思います。http://qiita.com/kanetai

Treasure Hunt(AOJ No.0016)

リポジトリ

Treasure Hunt(AOJ No.0016)

初めは、座標0,0で、北(90°)を向いている。
整数のペア(r,t)が与えられて、r前進し、時計方向にt度回転する。
これを繰り返し、(0,0)が入力された時の座標の整数部を出力する。
制約
 0\leq r \leq 100
 -180\leq t \leq 180

アルゴリズム

 x' = x + r \cos \theta
 y' = y + r \sin \theta
前進し、t回転する。
ただし、上のように更新する場合 \thetaは反時計回りが正方向なので、 \theta ' = \theta - t
で更新する。

コード

ただthetaを-=tするだけだと、オーバフローする可能性があるので毎回%=360して大きさを抑える。

import java.util.*;
public class aoj0016 {
	static final Scanner stdin = new Scanner(System.in);
	static double x,y;
	static int theta; //degree
	public static void main(String[] args) {
		x = y = 0.0;
		theta = 90; //north
		while(true){
			String[] s = stdin.next().split(",");
			int r = Integer.parseInt( s[0] );
			int t = Integer.parseInt( s[1] );
			if( r==0 && t==0 ) break;
			solve(r,t);
		}
		System.out.printf("%d\n%d\n", (int)x, (int)y);
	}
	static void solve(int r, int t){ //t clockwise -> positive
		x += r*Math.cos(Math.PI/180*theta);
		y += r*Math.sin(Math.PI/180*theta);
		theta -= t; //theta clockwise -> negative
		theta %= 360;
	}
}