I got a partition problem for which I need advice. I'm given a 1D array whose length is even. I need to write a boolean method to determine whether the array can be divided into 2 equally sized subarrays with equal sum, no loops are allowed.
For example, array #1 {-3,5,-12,14,-9,13} will return false, because -3 + 5 -12 + 14 = -9 + 13, however on the left side there are 4 elements and on the other side 2.
array #2 will return true:
{-3,14,12,5,-9,13} : -3 + 5 + 14 = 12 - 9 + 13
Here's what I've done so far:
public static boolean canBeDividedEqually(int[] arr)
{
if (arr.length %2 ==0){
return canBeDividedEquallyHelper(arr, 0, 0, 0);
}
return false;
}
public static boolean canBeDividedEquallyHelper(int[] arr, int i, int sum1, int sum2)
{
if (i == arr.length){
return sum1 == sum2;}
return canBeDividedEquallyHelper(arr, i+1, sum1 + arr[i], sum2) ||
canBeDividedEquallyHelper(arr, i+1, sum1, sum2 + arr[i]);
}
For case #2, it will return true as expected, but for case #1 it will also return true. I need to add a condition that will disqualify an array of type case #1.
You were almost there. In addition to the sums, pass the number of elements:
public class Solver
{
public static boolean canBeDividedEqually(int[] arr)
{
return canBeDividedEquallyHelper(arr, 0, 0, 0, 0, 0);
}
public static boolean canBeDividedEquallyHelper(int[] arr, int i, int nb1, int sum1, int nb2, int sum2)
{
if (i == arr.length)
return nb1 == nb2 && sum1 == sum2;
return canBeDividedEquallyHelper(arr, i+1, nb1+1, sum1 + arr[i], nb2, sum2) ||
canBeDividedEquallyHelper(arr, i+1, nb1, sum1, nb2+1, sum2 + arr[i]);
}
public static void main(String[] args)
{
System.out.println(canBeDividedEqually(new int[]{-3, 5, -12, 14, -9, 13})); // false
System.out.println(canBeDividedEqually(new int[]{-3, 14, 12, 5, -9, 13})); // true
}
}
Try this.
static boolean canPartitioning(int[] arr) {
return new Object() {
int length = arr.length, half = length / 2;
boolean partition(int i, int selected, int sum, int rest) {
if (i >= length)
return selected == half && sum == rest;
return selected < half && partition(i + 1, selected + 1, sum + arr[i], rest)
|| partition(i + 1, selected, sum, rest + arr[i]);
}
}.partition(0, 0, 0, 0);
}
public static void main(String[] args) {
System.out.println(canPartitioning(new int[] {-3, 5, -12, 14, -9, 13}));
System.out.println(canPartitioning(new int[] {-3, 14, 12, 5, -9, 13}));
}
output:
false
true
Here's a solution without using loops,
static int[] arrA, arrB;
public static boolean equalSplit(int[] arr) {
//Step 1
if (arr.length % 2 == 0) {
int sumA = 0, sumB = 0; // Two int variables to store the value of sum.
// Initializing the two new arrays with equal length.
arrA = new int[arr.length / 2];
arrB = new int[arr.length / 2];
// Copying the elements from the given array to the new arrays.
arrA = createArray(arrA, 0, arr, 0);
arrB = createArray(arrB, 0, arr, arr.length / 2);
//Calculating and storing the sum in the variables.
sumA = arraySum(arrA, arrA.length);
sumB = arraySum(arrB, arrB.length);
return sumA == sumB; // Checking the codition
} else {
return false;
}
}
private static int[] createArray(int[] arr, int index, int[] copyFrom, int copyFromIndex) {
if(index == arr.length) return arr;
arr[index] = copyFrom[copyFromIndex];
index++;
copyFromIndex++;
return createArray(arr, index, copyFrom, copyFromIndex);
}
private static int arraySum(int[] arr, int N) {
if (N <= 0) return 0;
return (arraySum(arr, N - 1) + arr[N - 1]);
}
My approach towards this question is,
Step 1 -> Checking whether can you split the given array into two equal arrays. If yes next comes the Step 2 or return false without any further steps.
Step 2 -> Copying the given array elements into two different but equal arrays using recursion.
Step 3 -> Sum the newly populated two arrays and store it in two different variable.
Step 4 -> If the Sum of both the newly populated arrays is equal then the function return true else false.
Explanation :
Create two new integer arrays which are going to get populated only if the given array can be divided into two equal parts. Here it is arrA and arrB.
Check whether if the length of given array can be divided by two and have 0 remainders because this can give the answer to the question "Can this array be divided into two equal parts ?". The piece of code in this answer is arr.length % 2 == 0. If the given array satisfies this condition only then the steps given below will be carried out else it will return false.
Initialize two integer variable to store the value of Sum of both the equally divided arrays.
Initialize the two newly created arrays with the array length of half the given array which is arr.length / 2.
Then copy first half of given array elements to the first newly initialized array then the second half to the second array. To achieve this createArray(int[] arr, int index, int[] copyFrom, int copyFromIndex) method is used. arr is the argument to pass the array which should be copied to, index should be 0 because it is used as the index of newly created arrays, copyFrom is a parameter for the given array which has all the elements, copyFromIndex is used to start copying the elements from the given index.
Then calculate the sum using recursive function and store it in separate variable which was created earlier. The function used here was arraySum(int[] arr, int N).
Return whether both the sum variables are equal.
If the change of elements order is allowed, you have to check every possible permutation of the array:
import java.util.Arrays;
public class Main {
public static void main(String[] args) {
int[] a = {-3, 5, -12,14,-9,13};
int[] b = {-3,14, 12, 5,-9,13};
System.out.println(isEquallySplittable(a));
System.out.println(isEquallySplittable(b));
}
public static boolean isEquallySplittable(int[] array){
long arraySum = arraySum(array);
if(arraySum % 2 != 0) return false; //can not split an even sum by half
return isEquallySplittable(array, 0, 0, arraySum);
}
public static boolean isEquallySplittable(int[] array, int indexFrom, int indexTo, long sumArray){
if(indexTo == indexFrom) {
indexTo++;
}
if(indexTo >= array.length) {
indexTo = 0;
indexFrom++;
}
if(indexFrom >= array.length) return false;
long sumHalfArray = arraySum(Arrays.copyOf(array, array.length/2)); //sum first half of the array
if(sumArray == sumHalfArray * 2 ){
System.out.println(Arrays.toString(array) + " can be split into 2 equal arrays");
return true;
}
//next permutation
int temp = array[indexTo];
array[indexTo] = array[indexFrom];
array[indexFrom] = temp;
return isEquallySplittable(array, indexFrom, ++indexTo, sumArray);
}
public static long arraySum(int[] arr) {
return arraySum(arr, 0, 0);
}
private static long arraySum(int[] arr, int index, long sum) {
if (index >= arr.length ) return sum;
sum += arr[index++];
return arraySum(arr,index,sum);
}
}
Here is Recursive solution in which elements need not be consecutive. This is simple recursive approach in which we take two lists named list1 and list2 respectively.
Then we check if it is possible to obtain a solution by adding this element in list1 (means nums[index] in context of program) if not it will check by adding the same in list2.
When the condition being true the the function recursively add element to respective list and if no solution is possible then function returns false.
The time complexity of the solution is O(2^n) as function tries each possible combination of elements adding to lists.
Here is code:
Example: int nums[] = new int[]{1, 1, 3, 4, 7};
For this resulting output would be [4, 3, 1] & [7, 1] order of elements get changed due to recursive calls.
import java.util.ArrayList;
public class SumPartition {
/**
* These are list that stores possible sum arrays
*/
ArrayList<Integer> list1 = new ArrayList<>();
ArrayList<Integer> list2 = new ArrayList<>();
public static void main(String[] args) {
int[] arr = new int[]{1, 1, 3, 4, 7};
SumPartition sumPartition = new SumPartition();
if(sumPartition.sameSumArrays(arr, 0, 0, 0)) {
System.out.println(sumPartition.list1);
System.out.println(sumPartition.list2);
}
else {
System.out.println("This is not possible");
}
}
/**
*
* #param nums is array of numbers
* #param index is index of nums array
* #param sum1 is sum1 which is sum of elements in list1
* #param sum2 is sum2 which is sum of elements in list2
*/
public boolean sameSumArrays(int nums[], int index, int sum1, int sum2) {
if(index == nums.length) {
return sum1 == sum2;
}
if(sameSumArrays(nums, index+1, sum1+nums[index], sum2)) {
list1.add(nums[index]);
return true;
}
else if(sameSumArrays(nums, index+1, sum1, sum2+nums[index])) {
list2.add(nums[index]);
return true;
}
return false;
}
}
Related
I have that method valorMaxim([1, 5, 252, 24, 7, 82, 3]) returns 252.
I don't know how to do it. I have been thinking if I could decrease the array length.
public static int valorMaxim(int arr[]){
int max;
if(arr.length==1)
return arr[0];
for (int i = 0; i < arr.length; i++) {
if (arr[i] < arr[i+1]) {
max=arr[i+1];
return arr[i+1];
}
}
return valorMaxim(arr);
//Retorna el valor màxim en un array no buit d’enters.
}
I modified the accepted answer to Finding Max value in an array using recursion.
As you suggested (i.e. decrease the array length with each recursive method invocation), I create a copy of the method parameter whose length is one less than the parameter and remove the first element. Then I recursively call the method with the array copy.
public class Main {
public static int valorMaxim(int arr[]){
if (arr.length == 1) {
return arr[0];
}
else {
int[] tmp = new int[arr.length - 1];
System.arraycopy(arr, 1, tmp, 0, tmp.length);
return Math.max(arr[0], valorMaxim(tmp));
}
}
public static void main(String[] args) {
System.out.println(valorMaxim(new int[]{1, 5, 252, 24, 7, 82, 3}));
}
}
Basically, the recursive idea is:
If the array has length 1, return the only element;
Otherwise, split the array into x the first element, and xs the rest;
Find the maximum element within xs, compare it to x and yield the greater.
There are two ways to achieve such a "split":
Create a new copy of part of the array for xs
You can either use System.arraycopy (see answer by #Abra) or Arrays.copyOfRange, which is simpler:
int x = arr[0];
int[] xs = Arrays.copyOfRange(arr, 1, arr.length);
And now we lookup the maximum element within xs (which is valorMaxim(xs)), and compare it to x as the final result:
return Math.max(x, valorMaxim(xs));
Put everything together, and don't forget to add a length checker:
public static int valorMaxim(int arr[])
{
if (arr.length == 1) return arr[0];
int x = arr[0];
int[] xs = Arrays.copyOfRange(arr, 1, arr.length);
return Math.max(x, valorMaxim(xs));
}
And that's it! Since we have the length checker in the first place,
we can safely make sure xs would never be empty, and hence valorMaxim(xs) would
never result in ArrayIndexOutOfBoundsException.
Set a boundary for the array
You may have found that copying a new array at each time could be time- and memory-consuming.
Instead of creating a physical copy for xs, we can conceptualise the idea
and use a bounded array instead. We would need to define a helper method to do so:
private static int findMaxBound(int arr[], int startFrom)
{
// does "xs" have length 1?
if (startFrom == arr.length - 1) return arr[startFrom];
int x = arr[startFrom];
int maxInXs = findMaxBound(arr, startFrom + 1);
return Math.max(x, maxInXs);
}
And then we can define valorMaxim as
public static int valorMaxim(int arr[])
{
return findMaxBound(arr, 0);
}
In the end, we did not create any new copies of arr
but uses different ranges of itself and treat them as xs throughout the process.
I'm dealing with this recursion problem and I do need some assistance. I'm given a number n
and a length n, sorted array r which contains only positive integers.
I need to remove every second element from the array, then third,...,nth element and so on until my array size is smaller then the nth number. then i need to determine if the given number n is a "special number", meaning it is in the final list after all required elements had been removed.
Not allowed to use any loops nor to create any other arrays but the given one.
for example: r = {1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20}
after removing every second element: r = {1, 3, 5, 7, 9, 11, 13, 15, 17, 19}
after removing every third element: r = {1, 3, 7, 9, 13, 15, 19}.
after removing every 5th element: r = {1,3,7,13}
1,3,7,13 are special numbers.
Below is what I've done so far. for the above mentioned array r the program prints false.
What am I missing?
public static boolean isSpecial (int n ){
int [] r = new int []{1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20};
int end = r.length -1 ;
return isSpecialHelper(r, -1, end ,2 , n );
}
public static boolean isSpecialHelper ( int []r ,int start,int end, int i, int n){
if ( i > r.length ){
return isSpecialHelper1( r, i -1, n);
}
else if (i <= r.length && (start + i) % i != 0 && (start + i) < end){
// r[(start+i)] = r[(start+i)+1];
r[start+i] = r[(start+i)+1];
return isSpecialHelper(r, start + i, i, end, n);
}
else if((start + i) == end){
// r[(start+i)] = r[(start+i)+1];
return isSpecialHelper(r, -1, i++ , end, n);
}
return false;
}
public static boolean isSpecialHelper1( int [] r,int j,int n){
if (r[j] == n){
return true;
}
else if (r[j]!= n ){ return isSpecialHelper1(r, j--, n);}
return false;
}
public static void main (String [] args){
System.out.print( isSpecial(7)));
}
}
isSpecial() doesn't have a System.out.println(); statement. return on its own doesn't print. You should do System.out.println(isSpecial(7)); in your main method or add System.out.println(); to your method. In this case you don't have to add return there and you can change method type to void.
For example if I have an array of ints as a parameter to my method, my method needs to return an array of ints where each element is the sum of all the elements following it.
Example:
parameter is [5, 6, 7, 2, 3, 1] I need to return [24, 19, 13, 6, 4, 1]
I have a written a helper method that correctly adds an index to all of the ones after it here:
public static int sum(int[] array, int index) {
if (index == array.length) {
return array[array.length-1];
} else {
return array[index] + sum(array, index + 1);
}
}
This all works as it should, but I'm having trouble with the original method here:
public int[] reverseCumulative(int[] numbers) {
int[] temp = new int[numbers.length];
if (numbers.length == 0) {
return temp;
}
else {
temp[numbers.length-1] = sum(numbers, numbers.length);
numbers = Arrays.copyOf(numbers, numbers.length - 1);
reverseCumulative(numbers);
return temp;
}
}
The output here is [0, 0, 0, 0 , 0, 1]. I understand that this is most likely due to the fact I'm creating a new int[] temp every time I call the reverseCumulative method within itself, but I am completely lost and any push in the right direction would be appreciated.
Edit: Forgot to add, I am not allowed to use any loops.
Since you are creating a new array each time you call the reverseCumulative method, you should use the sum method as a helper method inside the reverseCumulative method so that you are still using recursion. For example,
public int[] reverseCumulative(int[] numbers) {
int[] temp = new int[numbers.length];
if (numbers.length == 0) {
return temp;
}
else {
for(int i = 0; i < numbers.length; i++){
temp[i] = sum(numbers,i);
}
return temp;
}
}
This way, each element in temp equals a sum of integers in the numbers array depending on which iteration it is currently on. In the first iteration, temp[0] = the sum of all the ints in numbers. In the second iteration, temp[1] = the sum of all the ints in numbers except the first int and so on. However, the way the sum method is written right now, it adds the last element twice so here's a simple fix,
public static int sum(int[] array, int index) {
if (index == array.length-1) {
return array[array.length-1];
} else {
return array[index] + sum(array, index + 1);
}
}
Maybe something like this?
public static int sum(final int[] target, final int[] source, int index) {
if (index >= source.length - 1)
return source[index];
return target[index] = source[index] + sum(target, source, index + 1);
}
public static int[] reverseCulmulative(final int[] array) {
final int[] target = array.clone();
sum(target, array, 0);
return target;
}
Below, I have designed a function tournamentTreeKSelection which simulates a tree like structure using arrays and returns the largest element in the array. For example, given an input array [10,9,8,7,6,5,4,3,2,1] the following steps are performed to return 10.
[10, 8, 6, 4, 2, -1]
[10, 6, 2, -1]
[10, 2]
[10] //Max element of array found
My goal is to now add a second parameter int k requesting that the function return the k-th largest element such that tournamentTreeKSelection(data, 2) returns 9.
I'm having a lot of difficulty in modifying my algorithm to perform this task because my assumption is that i'm going to have to keep track of all elements that the max element beats ? Any help is appreciated.
import java.util.ArrayList;
import java.util.Arrays;
public class TournamentTree {
public static int tournamentTreeKSelection(int[] data, int k) {
ArrayList<Integer> list = new ArrayList<>();
ArrayList<Integer> list2 = new ArrayList<>();
for(int i = 0; i < data.length - 1; i += 2) {
list.add(max(data[i] , data[i + 1]));
}
for(int i = 0; i < data.length - 1; i++) {
list2.add(min(data[i], data[i + 1]));
}
if(list.size() == 1) return list.get(0);
if(list.size() % 2 != 0) list.add(-1);
if(k == 1) return tournamentTreeKSelection(listToArray(list),k);
else return tournamentTreeKSelection(listToArray(list2), --k);
}
public static int max(int a, int b) {
return a > b ? a : b;
}
public static int min(int a, int b) {
return a > b ? b : a;
}
public static int[] listToArray(ArrayList<Integer> arr) {
int[] arr2 = new int[arr.size()];
for(int i = 0; i < arr.size(); i++)
arr2[i] = arr.get(i);
return arr2;
}
}
I have now modified the code but it only works for k = 1 - 8, why does it break down ? tournamentTreeKSelection(data, 9) and tournamentTreeKSelection(data, 10) return 3 when they should be returning 2 and 1 respectively.
First of all, why your code is wrong:
When the size of the list is 2 or 3, your statement list.size() == 1 will be true even if K > 1.
Why do you do min(data[i], data[i + 1]), I have a feeling you just want to remove the maximum element but what with the case
[10,1,9,2,8,3,7,4,6,5], gives after 1 iteration [1,1,2,2,3,3,4,4,5] removing possible outcomes 9, 8, 7 and 6.
Some tips
Don't do useless computations. You are calculating the two lists, while you know in front you are only going to use one of them.
Use builtin methods whenever possible, see Math.max, Math.min
Note that you know the size of the resulting array in front. There is no need to create an ArrayList which causes a lot of overhead for you. Just create an array of the resulting size. For k==1, ((data.length+1)/2) else data.length-1
Still wondering
You say your tournament tree structure is a requirement, but you are looping over it in your code as it is an array. Why? You could determine the max value from the moment K==1 in 1 loop, instead of taking half of the maxes and doing it over and over again.
Alternative approach
As already suggested the sorting approach, or the quick find methods can be used. I was thinking how you could still use your tournament tree approach. And the best I came up with is how merge sort works. I slightly edited because you only need max K elements to return.
public static int find(int[] a, int k) {
int[] max = find(a, 0, a.length - 1, k);
return max[k-1];
}
private static int[] find(int[] a, int lo, int hi, int k) {
if (hi < lo){
return new int[]{};
}
if(lo == hi){
return new int[]{a[lo]};
}
int mid = lo + (hi - lo) / 2;
int[] left = find(a, lo, mid, k);
int[] right = find(a, mid + 1, hi, k);
return merge(left, right, k);
}
private static int[] merge(int[] left, int[] right, int k) {
int[] res = new int[Math.min(k, left.length+right.length)];
int l = 0, r = 0;
for (int i = 0; i<res.length;i++) {
if (l == left.length)
res[i] = right[r++];
else if (r == right.length)
res[i] = left[l++];
else if (left[l] > right[r])
res[i] = left[l++];
else
res[i] = right[r++];
}
return res;
}
Please read the question before marking it as duplicate
I have written following code to remove duplicates from array without using Util classes but now I am stuck
public class RemoveDups{
public static void main(String[] args) {
int[] a = { 1, 2, 3, 4, 5, 6, 1, 2, 3, 4, 5, 6, 3, 1, 4, 52, 1, 45, };
int temp;
for (int i : a) {
for (int j = 0; j < a.length - 1; j++) {
if (a[j] > a[j + 1]) {
temp = a[j];
a[j] = a[j + 1];
a[j + 1] = temp;
}
}
}
a = removeDups(a);
for (int i : a) {
System.out.println(i);
}
}
private static int[] removeDups(int[] a) {
int[] result = new int[a.length];
int j = 0;
for (int i : a) {
if (!isExist(result, i)) {
result[j++] = i;
}
}
return result;
}
private static boolean isExist(int[] result, int i) {
for (int j : result) {
if (j == i) {
return true;
}
}
return false;
}
}
and now the output is
1
2
3
4
5
6
45
52
0
0
0
0
0
0
0
0
0
0
Here my problem is
My code is not working in case of 0s
I am not able to understand how sorting an array can reduce time of execution
Is there any way to remove elements from array without using Util classes I know one way to remove convert array into list and then remove but for that also we need Util classes is there any way to implement by myself.
Since the numbers you deal with are limited to a small range you can remove duplicates by a simple "counting sort": mark the numbers you have found in a set-like data structure and then go over the data structure. An array of boolean works just fine, for less memory usage you could create a basic bitset or hash table. If n is the number of elements in the array and m is the size of the range, this algorithm will have O(n+m) complexity.
private static int[] removeDups(int[] a, int maxA) {
boolean[] present = new boolean[maxA+1];
int countUnique = 0;
for (int i : a) {
if (!present[i]) {
countUnique++;
present[i] = true;
}
}
int[] result = new int[countUnique];
int j = 0;
for (int i=0; i<present.length; i++) {
if (present[i]) result[j++] = i;
}
return result;
}
I am not able to understand how sorting an array can reduce time of execution
In a sorted array you can detect duplicates in a single scan, taking O(n) time. Since sorting is faster than checking each pair - O(n log n) compared to O(n²) time complexity - it would be faster to sort the array instead of using the naive algorithm.
As you are making the result array of the same length as array a
so even if you put only unique items in it, rest of the blank items will have the duplicate values in them which is 0 for int array.
Sorting will not help you much, as you code is searching the whole array again and again for the duplicates. You need to change your logic for it.
You can put some negative value like -1 for all the array items first in result array and then you can easily create a new result array say finalResult array from it by removing all the negative values from it, It will also help you to remove all the zeroes.
In java , arrays are of fixed length. Once created, their size can't be changed.
So you created an array of size18.
Then after you applied your logic , some elements got deleted. But array size won't change. So even though there are only 8 elements after the duplicate removal, the rest 10 elements will be auto-filled with 0 to keep the size at 18.
Solution ?
Store the new list in another array whose size is 8 ( or whatever, calculate how big the new array should be)
Keep a new variable to point to the end of the last valid element, in this case the index of 52. Mind you the array will still have the 0 values, you just won't use them.
I am not able to understand how sorting an array can reduce time of execution
What ? You sort an array if you need it to be sorted. Nothing else. Some algorithm may require the array to be sorted or may work better if the array is sorted. Depends on where you are using the array. In your case, the sorting will not help.
As for your final question , you can definitely implement your own duplicate removal by searching if an element exists more than once and then deleting all the duplicates.
My code is not working in case of 0
There were no zeroes to begin with in your array. But because its an int[], after the duplicates are removed the remaining of the indexes are filled with 0. That's why you can see a lot of zeroes in your array. To get rid of those 0s, you need to create another array with a lesser size(size should be equal to the no. of unique numbers you've in your array, excluding 0).
If you can sort your array(I see that its already sorted), then you could either bring all the zeroes to the front or push them to the last. Based on that, you can iterate the array and get the index from where the actual values start in the array. And, then you could use Arrays.copyOfRange(array, from, to) to create a copy of the array only with the required elements.
try this
package naveed.workingfiles;
public class RemoveDups {
public static void main(String[] args) {
int[] a = { 1, 2, 3, 4, 5, 6, 1, 2, 3, 4, 5, 6, 3, 1, 4, 52, 1, 45, };
removeDups(a);
}
private static void removeDups(int[] a) {
int[] result = new int[a.length];
int j = 0;
int count = 0;
for (int i : a) {
if (!isExist(result, i)) {
result[j++] = i;
count++;
}
}
System.out.println(count + "_____________");
for (int i=0;i<count;i++) {
System.out.println(result[i]);
}
// return result;
}
private static boolean isExist(int[] result, int i) {
for (int j : result) {
if (j == i) {
return true;
}
}
return false;
}
}
public class RemoveDups {
public static void main(String[] args) {
int[] a = { 1, 2, 0, 3, 1,0, 3, 6, 2};
removeDups(a);
}
private static void removeDups(int[] a) {
int[] result = new int[a.length];
int j = 0;
int count = 0;
boolean zeroExist = false;
for (int i : a) {
if(i==0 && !zeroExist){
result[j++] = i;
zeroExist = true;
count++;
}
if (!isExist(result, i)) {
result[j++] = i;
count++;
}
}
System.out.println(count + "_____________");
for (int i=0;i<count;i++) {
System.out.println(result[i]);
}
// return result;
}
private static boolean isExist(int[] result, int i) {
for (int j : result) {
if (j == i) {
return true;
}
}
return false;
}
}
// It works even Array contains 'Zero'
class Lab2 {
public static void main(String[] args) {
int[] a = { 1, 2, 3, 4, 5, 6, 1, 2, 3, 4, 5, 6, 3, 1, 4, 52, 1, 45 };
removeDups(a);
}
private static void removeDups(int[] a) {
int[] result = new int[a.length];
int j = 0;
int count = 0;
for (int i : a) {
if (!isExist(result, i)) {
result[j++] = i;
count++;
}
}
System.out.println(count + "_____________");
for (int i = 0; i < count; i++) {
System.out.println(result[i]);
}
}
private static boolean isExist(int[] result, int i) {
for (int j : result) {
if (j == i) {
return true;
}
}
return false;
}
}