give code for this in the format shown in image
تم الإنشاء في: ١٢ يوليو ٢٠٢٥
تم الإنشاء في: ١٢ يوليو ٢٠٢٥
Here’s a drop-in replacement for the skeleton you see in the screenshot (Java 8).
Just copy-paste it over the template and run the tests.
javaimport java.util.*; public class TestClass { /*----------------------------------------------------------- Returns the number of DISTINCT straight lines that pass through at least three of the N given points. ------------------------------------------------------------*/ public static int maxLines(int N, int[] x, int[] y) { /* We encode each line in reduced-integer form (A,B,C) for ax + by + c = 0, with gcd(|A|,|B|,|C|) = 1 and a canonical sign, so every pair that defines the same geometric line maps to the same key. */ class LineKey { final int A, B, C; LineKey(int A, int B, int C) { this.A = A; this.B = B; this.C = C; } @Override public boolean equals(Object o) { if (this == o) return true; if (!(o instanceof LineKey)) return false; LineKey k = (LineKey) o; return A == k.A && B == k.B && C == k.C; } @Override public int hashCode() { return Objects.hash(A, B, C); } } Map<LineKey, Set<Integer>> ptsOnLine = new HashMap<>(); for (int i = 0; i < N; ++i) { for (int j = i + 1; j < N; ++j) { int A = y[j] - y[i]; // Δy int B = x[i] - x[j]; // –Δx (so Ax + By is constant) int C = x[j] * y[i] - x[i] * y[j]; /* reduce (A,B,C) to lowest terms */ int g = gcd(gcd(Math.abs(A), Math.abs(B)), Math.abs(C)); if (g != 0) { A /= g; B /= g; C /= g; } /* canonical sign: first non-zero coefficient positive */ if (A < 0 || (A == 0 && B < 0) || (A == 0 && B == 0 && C < 0)) { A = -A; B = -B; C = -C; } LineKey key = new LineKey(A, B, C); ptsOnLine.computeIfAbsent(key, k -> new HashSet<>()).add(i); ptsOnLine.get(key).add(j); } } int answer = 0; for (Set<Integer> s : ptsOnLine.values()) { if (s.size() >= 3) answer++; } return answer; } /* simple iterative gcd */ private static int gcd(int a, int b) { while (b != 0) { int t = a % b; a = b; b = t; } return a; } /*-----------------------------------------------------------*/ public static void main(String[] args) { Scanner sc = new Scanner(System.in); int N = sc.nextInt(); int[] x = new int[N]; int[] y = new int[N]; for (int i = 0; i < N; ++i) { x[i] = sc.nextInt(); y[i] = sc.nextInt(); } System.out.print(maxLines(N, x, y)); } }
How it works (quick recap)
(A,B,C)
signature for the line.Set
.