Tools: VSCode | Source Code: GitHub
The ArrayCodeProjectTwo
program includes various methods that manipulate and analyze arrays in Java. The code covers several common operations like summing array elements, finding the maximum and minimum values, counting positive, negative, and zero elements, and reversing the array. Each method is self-contained, performing a specific task, and the program employs loops and conditional statements to achieve the desired results.
For example, the sumOfElements
method calculates the sum of all integers in the array. It initializes a sum
variable to zero and then iterates over the array, adding each number to the sum. The method then returns the total sum.
The findMaxMin
method finds both the maximum and minimum values in the array. It starts by assuming the first element is both the maximum and minimum. As it iterates over the array, it compares each element to the current maximum and minimum, updating them as needed.
Similarly, the countNumbers
method counts how many positive, negative, and zero elements exist in the array. It uses simple if-else statements to categorize each element.
Other methods perform operations like reversing the array, finding the second-largest element, and checking if the array is sorted. For example, the reverseArray
method uses a two-pointer technique, swapping elements from both ends of the array until the pointers meet in the middle.
The program also includes functionality to handle duplicate elements using the removeDuplicates
method, which uses a LinkedHashSet
to ensure only unique elements are kept. Additionally, it includes methods like rotateArrayInPlace
, which rotates the array by a specified number of positions, and findPairsWithSum
, which finds pairs of numbers that add up to a given target.
In the main
method, user input is handled via a Scanner
object. The user is prompted to enter an array, and then the program calls various methods on that array, such as finding prime numbers, the longest increasing subsequence, rotating the array, and performing binary search. The results are printed to the console after each operation, providing feedback to the user. The program concludes by finding the intersection of two arrays and displaying the common elements.
import java.util.*; public class ArrayCodeProjectTwo { // 1. Sum of Elements public static int sumOfElements(int[] arr) { int sum = 0; for (int num : arr) { sum += num; } return sum; } // 2. Maximum and Minimum Finder public static void findMaxMin(int[] arr) { int max = arr[0], min = arr[0]; for (int num : arr) { if (num > max) max = num; if (num < min) min = num; } System.out.println("Max: " + max + ", Min: " + min); } // 3. Count Positive, Negative, and Zero Elements public static void countNumbers(int[] arr) { int pos = 0, neg = 0, zero = 0; for (int num : arr) { if (num > 0) pos++; else if (num < 0) neg++; else zero++; } System.out.println("Positive: " + pos + ", Negative: " + neg + ", Zero: " + zero); } // 4. Reverse the Array public static void reverseArray(int[] arr) { int left = 0, right = arr.length - 1; while (left < right) { int temp = arr[left]; arr[left] = arr[right]; arr[right] = temp; left++; right--; } System.out.println("Reversed Array: " + Arrays.toString(arr)); } // 5. Find the Second Largest Element public static int secondLargest(int[] arr) { int first = Integer.MIN_VALUE, second = Integer.MIN_VALUE; for (int num : arr) { if (num > first) { second = first; first = num; } else if (num > second && num != first) { second = num; } } return second; } // 6. Check if an Array is Sorted public static boolean isSorted(int[] arr) { for (int i = 1; i < arr.length; i++) { if (arr[i] < arr[i - 1]) { return false; } } return true; } // 7. Find the Mode (Most Frequent Element) public static int findMode(int[] arr) { Map<Integer, Integer> countMap = new HashMap<>(); for (int num : arr) { countMap.put(num, countMap.getOrDefault(num, 0) + 1); } int mode = arr[0]; int maxCount = 0; for (Map.Entry<Integer, Integer> entry : countMap.entrySet()) { if (entry.getValue() > maxCount) { maxCount = entry.getValue(); mode = entry.getKey(); } } return mode; } // 8. Merge Two Sorted Arrays public static int[] mergeSortedArrays(int[] arr1, int[] arr2) { int len1 = arr1.length; int len2 = arr2.length; int[] merged = new int[len1 + len2]; int i = 0, j = 0, k = 0; while (i < len1 && j < len2) { if (arr1[i] < arr2[j]) { merged[k++] = arr1[i++]; } else { merged[k++] = arr2[j++]; } } while (i < len1) { merged[k++] = arr1[i++]; } while (j < len2) { merged[k++] = arr2[j++]; } return merged; } // 9. Calculate the Average of Elements public static double average(int[] arr) { int sum = 0; for (int num : arr) { sum += num; } return sum / double (arr.length); } // 10. Remove Duplicates from an Array public static int[] removeDuplicates(int[] arr) { Set<Integer> set = new HashSet<>(); for (int num : arr) { set.add(num); } int[] uniqueArr = new int[set.size()]; int i = 0; for (Integer num : set) { uniqueArr[i++] = num; } return uniqueArr; } // 11. Swap Two Elements in an Array public static void swapElements(int[] arr, int index1, int index2) { int temp = arr[index1]; arr[index1] = arr[index2]; arr[index2] = temp; } // 12. Check if an Array is Palindromic public static boolean isPalindrome(int[] arr) { int left = 0, right = arr.length - 1; while (left < right) { if (arr[left] != arr[right]) { return false; } left++; right--; } return true; } // 13. Rotate Array Elements public static void rotateArray(int[] arr, int k) { int len = arr.length; k %= len; int[] temp = new int[len]; for (int i = 0; i < len; i++) { temp[i] = arr[i]; } for (int i = 0; i < len; i++) { arr[i] = temp[i]; } } // 14. Convert Array to List public static List<Integer> arrayToList(int[] arr) { List<Integer> list = new ArrayList<>(); for (int num : arr) { list.add(num); } return list; } // 15. Find the Intersection of Two Arrays public static int[] intersection(int[] arr1, int[] arr2) { Set<Integer> set1 = new HashSet<>(); Set<Integer> set2 = new HashSet<>(); for (int num : arr1) { set1.add(num); } for (int num : arr2) { set2.add(num); } set1.retainAll(set2); int[] intersection = new int[set1.size()]; int i = 0; for (Integer num : set1) { intersection[i++] = num; } return intersection; } // 16. Count Occurrences of an Element in an Array public static int countOccurrences(int[] arr, int target) { int count = 0; for (int num : arr) { if (num == target) { count++; } } return count; } // 17. Find the Longest Word in a String Array public static String longestWord(String[] arr) { String longest = ""; for (String word : arr) { if (word.length() > longest.length()) { longest = word; } } return longest; } // 18. Reverse a String public static String reverseString(String str) { StringBuilder reversed = new StringBuilder(str); reversed.reverse(); return reversed.toString(); } // 19. Convert a List to an Array public static int[] listToArray(List<Integer> list) { int[] arr = new int[list.size()]; for (int i = 0; i < arr.length; i++) { arr[i] = list.get(i); } return arr; } // 20. Find the Smallest Element in an Array public static int findSmallest(int[] arr) { int smallest = arr[0]; for (int num : arr) { if (num < smallest) { smallest = num; } } return smallest; } }