Untitled
unknown
plain_text
2 years ago
2.6 kB
3
Indexable
package divideAndConquer; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.util.ArrayList; import java.util.List; import java.util.Scanner; public class Test { public static double calculateGravitationalForce(double x, double m1, double m2, double d) { double G = 6.67e-11; return G * m1 * m2 / Math.pow((d - x), 2); } public static double sumForcesFromLeft(double x, List<Double> xList, List<Double> mList) { int n = xList.size(); double fSum = 0; for (int i = 0; i < n; i++) { if (xList.get(i) < x) { fSum += calculateGravitationalForce(x, mList.get(i), 1, xList.get(i)); } } return fSum; } public static double sumForcesFromRight(double x, List<Double> xList, List<Double> mList) { int n = xList.size(); double fSum = 0; for (int i = 0; i < n; i++) { if (xList.get(i) > x) { fSum += calculateGravitationalForce(x, mList.get(i), 1, xList.get(i)); } } return fSum; } public static List<Double> findBalance(List<Double> xList, List<Double> mList) { int n = xList.size(); List<Double> balancePoints = new ArrayList<>(); for (int i = 0; i < n - 1; i++) { double a = xList.get(i); double b = xList.get(i + 1); double tol = 1e-9; int maxIter = 100; int iter = 0; while (Math.abs(a - b) > tol && iter < maxIter) { double c = (a + b) / 2; if (sumForcesFromLeft(c, xList, mList) == sumForcesFromRight(c, xList, mList)) { break; } else if (sumForcesFromLeft(c, xList, mList) > sumForcesFromRight( c, xList, mList)) { a = c; } else { b = c; } iter++; } balancePoints.add((a + b) / 2); } return balancePoints; } public static void main(String[] args) throws FileNotFoundException { System.setIn(new FileInputStream("Text")); Scanner sc = new Scanner(System.in); for (int i = 1; i <= 10; i++) { // Read the number of magnetic materials int n = sc.nextInt(); double[] x = new double[n]; double[] m = new double[n]; List<Double> xList1 = new ArrayList<>(); List<Double> mList1 = new ArrayList<>(); for (int j = 0; j < n; j++) { x[j] = sc.nextDouble(); xList1.add(x[j]); } for (int j = 0; j < n; j++) { m[j] = sc.nextDouble(); mList1.add(m[j]); } List<Double> balancePoints1 = findBalance(xList1, mList1); System.out.print("#1 "); for (Double point : balancePoints1) { System.out.printf("%.10f ", point); } System.out.println(); } sc.close(); } }
Editor is loading...