Array Program 1: Find the Evenly Repeated number from an Array
Input: int[] a = {1,1,5,4,8,1,5,8,3,9,15,15,16,2,8,7,9,1};
Output : [1, 5, 9, 15]
Input: int[] a = {1,1,5,4,8,1,5,8,3,9,15,15,16,2,8,7,9,1};
Output : [1, 5, 9, 15]
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 | package JavaPractice; import java.util.ArrayList; import java.util.Arrays; import java.util.List; public class ArraysEvenOccurance { public static void main(String arg[]){ int[] input = {1, 1, 5, 4, 8, 1, 5, 8, 3, 9, 15, 15, 16, 2, 8, 7, 9, 1}; int[] output = new int[input.length]; // sort input array Arrays.sort(input); int counter = 1, k = 0, j=0; for (int i = 1; i < input.length; i++) { if (input[k] == input[i]) { // check for same number counter++; } else { // check even number of counter if (counter % 2 == 0) { output[j] = (input[k]); j++; } counter = 1; k = i; } } // Removing Extra appended element (sub array) output = Arrays.copyOfRange(output, 0, j); // Print Result array System.out.println(Arrays.toString(output)); } } |
No comments:
Post a Comment