Java Online Compiler
Example: DisjointArrayBruteForce in Java
C
C++
C#
Java
Python
PHP
Main.java
STDIN
Run
// DisjointArrayBruteForce import java.util.Scanner; // Main class containing the entry point of the program public class Main { /** * Checks if two integer arrays are disjoint using a brute-force approach. * @param arr1 The first array. * @param arr2 The second array. * @return true if the arrays are disjoint (no common elements), false otherwise. */ public static boolean areArraysDisjointBruteForce(int[] arr1, int[] arr2) { // Step 1: Iterate through each element of the first array. for (int i = 0; i < arr1.length; i++) { // Step 2: For each element in arr1, iterate through all elements of the second array. for (int j = 0; j < arr2.length; j++) { // Step 3: Compare the current elements. if (arr1[i] == arr2[j]) { // Step 4: If a common element is found, the arrays are not disjoint. return false; } } } // Step 5: If no common elements are found after all comparisons, the arrays are disjoint. return true; } public static void main(String[] args) { // Test Case 1: Disjoint arrays int[] arr1_case1 = {1, 2, 3}; int[] arr2_case1 = {4, 5, 6}; System.out.println("Arrays: {1, 2, 3} and {4, 5, 6}"); System.out.println("Are disjoint (Brute-Force)? " + areArraysDisjointBruteForce(arr1_case1, arr2_case1)); // Expected: true // Test Case 2: Non-disjoint arrays int[] arr1_case2 = {1, 2, 3}; int[] arr2_case2 = {3, 4, 5}; System.out.println("\nArrays: {1, 2, 3} and {3, 4, 5}"); System.out.println("Are disjoint (Brute-Force)? " + areArraysDisjointBruteForce(arr1_case2, arr2_case2)); // Expected: false // Test Case 3: Empty arrays int[] arr1_case3 = {}; int[] arr2_case3 = {1, 2, 3}; System.out.println("\nArrays: {} and {1, 2, 3}"); System.out.println("Are disjoint (Brute-Force)? " + areArraysDisjointBruteForce(arr1_case3, arr2_case3)); // Expected: true } }
Output
Clear
ADVERTISEMENTS