PostAddsense


Planets Topcoder



import java.text.DecimalFormat;

public class Planets
{
    public String[] locations(String[] planets, int time) {
        double G = 6.673E-11;
        double t = 3600;

        int n = planets.length;

        double[] f = new double[3];
        double[] m = new double[n];
        double[][] v = new double[n][3];
        double[][] p = new double[n][3];
        
        for (int i = 0; i < n; i++) {
            String[] sp = planets[i].split(" ");
            p[i][0] = Double.parseDouble(sp[0]);
            p[i][1] = Double.parseDouble(sp[1]);
            p[i][2] = Double.parseDouble(sp[2]);
            v[i][0] = Double.parseDouble(sp[3]);
            v[i][1] = Double.parseDouble(sp[4]);
            v[i][2] = Double.parseDouble(sp[5]);
            m[i] = Double.parseDouble(sp[6]);
        }

        for (int i = 0; i < time; i++) {
            for (int j = 0; j < n; j++) {
                for (int k = 0; k < n; k++) {
                    if (j == k) continue;
                    double xd = p[k][0] - p[j][0];
                    double yd = p[k][1] - p[j][1];
                    double zd = p[k][2] - p[j][2];
                    double d = Math.sqrt(xd*xd + yd*yd + zd*zd);
                    double F = (G*m[k]*m[j]) / (d*d);
                    f[0] = F*(xd/d);
                    f[1] = F*(yd/d);
                    f[2] = F*(zd/d);
                    for (int l = 0; l < 3; l++)
                        v[j][l] += f[l]/m[j]*t;
                }
            }
            for (int j = 0; j < n; j++)
                for (int l = 0; l < 3; l++)
                    p[j][l] += v[j][l]*t;
        }

        String[] res = new String[n];

        for (int i = 0; i < n; i++) {
            res[i] = "";
            for (int j = 0; j < 3; j++) {
                if(j != 0) res[i] += " ";
                String s = new DecimalFormat("0.000E0").format(p[i][j]);
                if (Math.abs(p[i][j]) < 1)
                    s = new DecimalFormat("0.000").format(p[i][j]) + "E0";
                if (s.equals("-0.000E0"))
                    s = "0.000E0";
                res[i] += s;
            }
        }

        return res;
    }
}


Explanation

  • F를 각 거리 비만큼 분산시키기 위해 f[0,1,2] = F * (xd,yd,zd / d) 를 사용한다.
  • DecimalFormat에 숫자를 넣고 변환시 자동으로 반올림 된다.


References