copy array without specified element java - java

i'm trying copy an array without a specified element. Let's say I have the following arrays:
int[] array = {1,2,3,4,5,6,7,8,9};
int[] array2 = new int[array.length-1];
what I want is to copy array to array2 without the element containing the int "6" so it will contain
"{1,2,3,4,5,7,8,9}"
I only want to use for loops and this is what I have so far but it doesnt work
int[] array= { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9 };
int[] array2= new int[array.length - 1];
int remove = 6;
for (int i = 0; i < array2.length; i++) {
if (array[i] != remove) {
array2[i] = array[i];
} else {
array2[i] = array[i + 1];
i++;
}
}
for (int i = 0; i < array2.length; i++) {
System.out.println(array2[i]);
}
Thanks

You can also do it using Java 8's streams and lambda expressions:
int[] array= { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9 };
int[] array2 = Arrays.stream( array ).filter( value -> value != 6 ).toArray();
System.out.println( Arrays.toString( array2 ) );
// Outputs: [0, 1, 2, 3, 4, 5, 7, 8, 9]

int j = 0;
int count = 0; //Set this variable to the number of times the 'remove' item appears in the list
int[] array2 = new int[array.length - count];
int remove = 6;
for(int i=0; i < array.length; i++)
{
if(array[i] != remove)
array2[j++] = array[i];
}

ArrayUtils.remove(array, 6) from apache.commons.lang might also be suitable

Related

Checking if two int arrays have duplicate elements, and extract one of the duplicate elements from them

I'm trying to write a method, union(), that will return an int array, and it takes two int array parameters and check if they are sets, or in other words have duplicates between them. I wrote another method, isSet(), it takes one array argument and check if the array is a set. The problem is I want to check if the two arrays in the union method have duplicates between them, if they do, I want to extract one of the duplicates and put it in the unionArray[] int array. This is what I tried so far.
public int[] union(int[] array1, int[] array2){
int count = 0;
if (isSet(array1) && isSet(array2)){
for (int i = 0; i < array1.length; i++){
for (int j = 0; j < array2.length; j++){
if (array1[i] == array2[j]){
System.out.println(array2[j]);
count ++;
}
}
}
}
int[] array3 = new int[array2.length - count];
int[] unionArray = new int[array1.length + array3.length];
int elementOfUnion = 0;
for (int i = 0; i< array1.length; i++){
unionArray[i] = array1[i];
elementOfUnion = i + 1 ;
}
int index = 0;
for (int i = elementOfUnion; i < unionArray.length; i++){
unionArray[i] = array3[index];
index++;
}
return unionArray;
}
public boolean isSet(int[] array){
boolean duplicates = true;
for (int i = 0; i < array.length; i++){
for(int n = i+1; n < array.length; n++){
if (array[i] == array[n])
duplicates = false;
}
}
return duplicates;
}
What I was trying to do is to use all of array1 elements in the unionArray, check if array2 has any duplicates with array1, and then move all the non-duplicate elements from array2 to a new array3, and concatenate array3 to unionArray.
It will be much easier to do it with Collection API or Stream API. However, you have mentioned that you want to do it purely using arrays and without importing any class, it will require a few lengthy (although simple) processing units. The most important theories that drive the logic is how (given below) a union is calculated:
n(A U B) = n(A) + n(B) - n(A ∩ B)
and
n(Only A) = n(A) - n(A ∩ B)
n(Only B) = n(B) - n(A ∩ B)
A high-level summary of this solution is depicted with the following diagram:
Rest of the logic has been very clearly mentioned through comments in the code itself.
public class Main {
public static void main(String[] args) {
// Test
display(union(new int[] { 1, 2, 3, 4 }, new int[] { 3, 4, 5, 6 }));
display(union(new int[] { 1, 2, 3 }, new int[] { 4, 5, 6 }));
display(union(new int[] { 1, 2, 3, 4 }, new int[] { 1, 2, 3, 4 }));
display(union(new int[] { 1, 2, 3, 4 }, new int[] { 3, 4 }));
display(union(new int[] { 1, 2, 3, 4 }, new int[] { 4, 5 }));
display(union(new int[] { 1, 2, 3, 4, 5, 6 }, new int[] { 7, 8 }));
}
public static int[] union(int[] array1, int[] array2) {
// Create an array of the length equal to that of the smaller of the two array
// parameters
int[] intersection = new int[array1.length <= array2.length ? array1.length : array2.length];
int count = 0;
// Put the duplicate elements into intersection[]
for (int i = 0; i < array1.length; i++) {
for (int j = 0; j < array2.length; j++) {
if (array1[i] == array2[j]) {
intersection[count++] = array1[i];
}
}
}
// Create int []union of the length as per the n(A U B) = n(A) + n(B) - n(A ∩ B)
int[] union = new int[array1.length + array2.length - count];
// Copy array1[] minus intersection[] into union[]
int lastIndex = copySourceOnly(array1, intersection, union, count, 0);
// Copy array2[] minus intersection[] into union[]
lastIndex = copySourceOnly(array2, intersection, union, count, lastIndex);
// Copy intersection[] into union[]
for (int i = 0; i < count; i++) {
union[lastIndex + i] = intersection[i];
}
return union;
}
static int copySourceOnly(int[] source, int[] exclude, int[] target, int count, int startWith) {
int j, lastIndex = startWith;
for (int i = 0; i < source.length; i++) {
// Check if source[i] is present in intersection[]
for (j = 0; j < count; j++) {
if (source[i] == exclude[j]) {
break;
}
}
// If j has reached count, it means `break;` was not executed i.e. source[i] is
// not present in intersection[]
if (j == count) {
target[lastIndex++] = source[i];
}
}
return lastIndex;
}
static void display(int arr[]) {
System.out.print("[");
for (int i = 0; i < arr.length; i++) {
System.out.print(i < arr.length - 1 ? arr[i] + ", " : arr[i]);
}
System.out.println("]");
}
}
Output:
[1, 2, 5, 6, 3, 4]
[1, 2, 3, 4, 5, 6]
[1, 2, 3, 4]
[1, 2, 3, 4]
[1, 2, 3, 5, 4]
[1, 2, 3, 4, 5, 6, 7, 8]
Using Java's streams could make this quite simpler:
public int[] union(int[] array1, int[] array2) {
return Stream.of(array1, array2).flatMapToInt(Arrays::stream).distinct().toArray();
}
Even with all the restrictions of only using arrays, you can simplify your code a lot. No need to check for sets. Just :
allocate an array to store all elements of the union (i.e., int[] tmp_union ), which at worst will be all elements from both arrays array1 and array2.
iterate over the elements of array1 and compared them against the elements from tmp_union array, add them into the tmp_union array only if they were not yet added to that array.
Repeat 2) for the array2.
During this process keep track of the number of elements added to the tmp_union array so far (i.e., added_so_far). In the end, copy the elements from the tmp_union array into a new array (i.e., unionArray) with space allocated just for the union elements. The code would look something like:
public static int[] union(int[] array1, int[] array2){
int[] tmp_union = new int[array1.length + array2.length];
int added_so_far = add_unique(array1, tmp_union, 0);
added_so_far = add_unique(array2, tmp_union, added_so_far);
return copyArray(tmp_union, added_so_far);
}
private static int[] copyArray(int[] ori, int size) {
int[] dest = new int[size];
for(int i = 0; i < size; i++)
dest[i] = ori[i];
return dest;
}
private static int add_unique(int[] array, int[] union, int added_so_far) {
for (int element : array)
if (!is_present(union, added_so_far, element))
union[added_so_far++] = element;
return added_so_far;
}
private static boolean is_present(int[] union, int added_so_far, int element) {
for (int z = 0; z < added_so_far; z++)
if (element == union[z])
return true;
return false;
}

Combine two int arrays without duplicates using only for loops

This is a pretty beginner assignment, and I would love to get some help with my code.
I need to combine two integer arrays into one using for loops, and make sure I don't have duplicates. Anything I googled is pretty over complicated and uses all sorts of built in methods.
Here is my code:
static void SumArray(){
int[] array1 = { 1, 2, 3 };
int[] array2 = { 3, 4, 5 };
int[] merged = new int[array1.length + array2.length];
int pos = 0;
for (int i = 0; i < array1.length; i++) {
merged[pos] = array1[i];
pos++;
}
for (int j = merged[pos]; j < array2.length; j++) {
if (merged[pos] != array2[j]) {
merged[pos] = array2[j];
pos++;
}
}
System.out.println(Arrays.toString(merged));
Ultimately, it should return {1, 2, 3, 4, 5}. Instead, currently it returns 1, 2, 3, 3, 4, 5.
I would like to know why my if doesn't work. It should skip the 3 since it is already in there.
What am I missing?
Thanks :)
Edit:
Thanks guys, this is what I ended up doing, which still isn't good since I'm not checking for duplicates in the first loop that goes over the first array:
static void SumArray(){
int[] array1 = { 1, 2, 3 };
int[] array2 = { 3, 4, 5 };
int arrSize = array1.length + array2.length;
int[] merged = new int[arrSize];
int pos = 0;
int counter = 0;
for (int i = 0; i < array1.length; i++) {
merged[pos] = array1[i];
pos++;
}
for (int j = merged[pos]; j < array2.length; j++) {
if (merged[pos-1] != array2[j]) {
merged[pos] = array2[j];
pos++;
counter++;
}
}
int[] newMerged = new int[arrSize - counter + 1];
System.arraycopy(merged, 0, newMerged, 0, newMerged.length);
System.out.println(Arrays.toString(newMerged));
}
I'm sure I'll find a way.
I would like to know why my if doesn't work.
Because merged[pos] is always 0, because you've never assigned any other value to it in your code. Array entries are initialized to zero when you create the array.
You can't just check one entry to know whether to add a value from array2. You have to check all of the entries you've written, with a nested loop within your second for loop. Only add a new entry if it isn't already there.
Note that you'll also need to either check ahead of time how many duplicates there are so you know that merged should only be 5 entries long, or you need to re-create merged later when you know how long it should be. Otherwise, your end result will be {1, 2, 3, 4, 5, 0}, not {1, 2, 3, 4, 5}.
because of the "pos++" in the first for loop as you are using as start index of j in the second loop.
Your 3 is in the index 2 and you are comparing it to index 3, which never be equal
here is your answer:
int[] array1 = { 1, 2, 3 };
int[] array2 = { 3, 4, 5 };
int[] merged = new int[array1.length + array2.length];
int pos = 0,i=0, j;
Set<Integer> intSet = new HashSet();
for (i = 0; i < array1.length; i++) {
if(!intSet.contains(array1[i])) {
merged[pos] = array1[i];
intSet.add(Integer.valueOf(i));
pos++;
}
}
for (j= 0, pos = pos-1; j < array2.length; ) {
if(!intSet.contains(Integer.valueOf(array2[j]))) {
merged[pos] = array2[j];
intSet.add(Integer.valueOf(i));
pos++;
j++;
}
}
System.out.println(Arrays.toString(merged));
Here is solution for Java 8 and bigger version:
int[] first = { 1, 2, 3 };
int[] second = { 3, 4, 5 };
int[] merged = Stream.of(first, second)
.flatMapToInt(Arrays::stream)
.distinct()
.toArray();

Java - Merge Two Arrays without Duplicates (No libraries allowed)

Need assistance with programming issue.
Must be in Java. Cannot use any libraries (Arraylist, etc.).
int[] a = {1, 2, 3, 4, 8, 5, 7, 9, 6, 0}
int[] b = {0, 2, 11, 12, 5, 6, 8}
Have to create an object referencing these two arrays in a method that merges them together, removes duplicates, and sorts them.
Here's my sort so far. Having difficulty combining two arrays and removing duplicates though.
int lastPos;
int index;
int temp;
for(lastPos = a.length - 1; lastPos >= 0; lastPos--) {
for(index = 0; index <= lastPos - 1; index++) {
if(a[index] > a[index+1]) {
temp = a[index];
a[index] = a[index+1];
a[index+1] = temp;
}
}
}
a method that merges them together, removes duplicates, and sorts them.
I suggest you break this down into helper methods (and slightly tweak the order of operations). Step 1, merge the two arrays. Something like,
static int[] mergeArrays(int[] a, int[] b) {
int[] c = new int[a.length + b.length];
for (int i = 0; i < a.length; i++) {
c[i] = a[i];
}
for (int i = 0; i < b.length; i++) {
c[a.length + i] = b[i];
}
return c;
}
Step 2, sort the new array (your existing sort algorithm is fine). Like,
static void sortArray(int[] a) {
for (int lastPos = a.length - 1; lastPos >= 0; lastPos--) {
for (int index = 0; index <= lastPos - 1; index++) {
if (a[index] > a[index + 1]) {
int temp = a[index];
a[index] = a[index + 1];
a[index + 1] = temp;
}
}
}
}
Finally, remove duplicates. Step 3a, count unique values. Assume they're unique, and decrement by counting adjacent (and equal) values. Like,
static int countUniqueValues(int[] c) {
int unique = c.length;
for (int i = 0; i < c.length; i++) {
while (i + 1 < c.length && c[i] == c[i + 1]) {
i++;
unique--;
}
}
return unique;
}
Then step 3b, take the unique count and build your result with the previous methods. Like,
public static int[] mergeDedupSort(int[] a, int[] b) {
int[] c = mergeArrays(a, b);
sortArray(c);
int unique = countUniqueValues(c);
int[] d = new int[unique];
int p = 0;
for (int i = 0; i < c.length; i++) {
d[p++] = c[i];
while (i + 1 < c.length && c[i] == c[i + 1]) {
i++;
}
}
return d;
}
Then you can test it with your arrays like
public static void main(String[] args) {
int[] a = { 1, 2, 3, 4, 8, 5, 7, 9, 6, 0 };
int[] b = { 0, 2, 11, 12, 5, 6, 8 };
int[] c = mergeDedupSort(a, b);
System.out.println(Arrays.toString(c));
}
And I get
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 11, 12]
Merge Two Arrays without Duplicates and Sort it (No libraries used).
Using an object.
public class MergeRemoveDupSort {
public int[] mergeRemoveDupSortIt(int[] a, int[] b) {
int [] c = mergeIt(a,b);
int [] d = removeIt(c);
int [] e = sortIt(d);
return e;
}
private int[] mergeIt(int[] a, int[] b) {
int[] c = new int[a.length + b.length];
int k=0;
for (int n : a) c[k++]=n;
for (int n : b) c[k++]=n;
return c;
}
private int[] removeIt(int[] c) {
int len=c.length;
for (int i=0;i<len-1;i++)
for (int j=i+1;j<len;j++)
if (c[i] == c[j]) {
for (int k=j;k<len-1;k++)
c[k]=c[k+1];
--len;
}
int [] r = new int[len];
for (int i=0;i<r.length;i++)
r[i]=c[i];
return r;
}
private int[] sortIt(int[] a) {
for(int index=0; index<a.length-1; index++)
for(int i=index+1; i<a.length; i++)
if(a[index] > a[i]){
int temp = a[index];
a[index] = a[i];
a[i] = temp;
}
return a;
}
public void printIt(int[] a) {
System.out.print("[");
for (int i=0;i<a.length;i++){
System.out.print(a[i]);
if (i!=a.length-1) System.out.print(",");
else System.out.print("]");
}
}
public static void main(String[] args) {
int[] a = {1, 2, 3, 4, 8, 5, 7, 9, 6, 0};
int[] b = {0, 2, 11, 12, 5, 6, 8};
MergeRemoveDupSort array = new MergeRemoveDupSort();
int [] r = array.mergeRemoveDupSortIt(a, b);
array.printIt(r);
}
}
You should use IntStream like this.
int[] a = {1, 2, 3, 4, 8, 5, 7, 9, 6, 0};
int[] b = {0, 2, 11, 12, 5, 6, 8};
int[] merged = IntStream
.concat(IntStream.of(a), IntStream.of(b))
.distinct()
.sorted()
.toArray();
System.out.println(Arrays.toString(merged));
Assuming that array a and array b are sorted, the following code will merge them into a third array merged_array without duplicates :
public static int[] get_merged_array(int[] a, int[] b, int a_size, int b_size)
{
int[] merged_array = new int[a_size + b_size];
int i = 0 , j = 0, x = -1;
for(; i < a_size && j < b_size;)
{
if(a[i] <= b[j])
{
merged_array[++x] = a[i];
++i;
}
else
{
if(merged_array[x] != b[j])
{
merged_array[++x] = b[j]; // avoid duplicates
}
++j;
}
}
--i; --j;
while(++i < a_size)
{
merged_array[++x] = a[i];
}
while(++j < b_size)
{
merged_array[++x] = b[j];
}
return merged_array;
}
Hope this may help, all the best :)
try{
int[] a = {1, 2, 3, 4, 8, 5, 7, 9, 6, 0};
int[] b = {0, 2, 11, 12, 5, 6, 8};
int[] c = new int[a.length+b.length];
int[] final = new int[a.length+b.length];
int i = 0;
for(int j : final){
final[i++] = -1;
}
i = 0;
for(int j : a){
c[i++] = j;
}
for(int j : b){
c[i++] = j;
}
boolean check = false;
for(int j = 0,k = 0; j < c.length; j++){
for(int l : fin){
if( l == c[j] )
check = true;
}
if(!check){
final[k++] = c[j];
} else check = false;
}
} catch(Exception ex){
ex.printStackTrace();
}
I prefer you to use Hashset for this cause it never allow duplicates
and there is another method in java 8 for arraylist to remove duplicates
after copying all elements to c follow this code
List<Integer> d = array.asList(c);
List<Integer> final = d.Stream().distinct().collect(Collectors.toList());
final.forEach(System.out::println());
This code is lot much better than previous one and you can again transform final to array like this
int array[] = new int[final.size()];
for(int j =0;j<final.size();j++){
array[j] = final.get(j);
}
Hope my work will be helpful .
Let me restate your question.
You want a program that takes two arbitrary arrays, merges them removing any duplicates, and sorts the result.
First of all, if you have access to any data structure, there are much better ways of doing this. Ideally, you would use something like a TreeSet.
However, assuming all you have access to is arrays, your options are much more limited. I'm going to go ahead and assume that each of the two arrays initially has no duplicates.
Let's assume the first array is of length m and the second array is of length n.
int[] array1; // length m
int[] array2; // length n
First, let's sort both arrays.
Arrays.sort(array1);
Arrays.sort(array2);
This assumes you have access to the Arrays class which is part of the standard Java Collections Framework. If not, any reasonable merge implementation (like MergeSort) will do the trick.
The sorts will take O(n log n + m log m) with most good sort implementations.
Next, let's merge the two sorted arrays. First, we need to allocate a new array big enough to hold all the elements.
int[] array3 = new int[size];
Now, we will need to insert the elements of array1 and array2 in order, taking care not to insert any duplicates.
int index=0, next=0, i=0, j=0;
int last = Integer.MAX_INT;
while(i < m || j < n) {
if(i == m)
next = array2[j++];
else if(j == n)
next = array1[i++];
else if(array1[i] <= array2[j])
next = array1[i++];
else
next = array2[j++];
if(last == next)
continue;
array3[index++] = next;
}
Now, you have your array. Just one problem - it could have invalid elements at the end. One last copy should take care of it...
int[] result = Arrays.copyOf(array3, index + 1);
The inserts and the final copy will take O(n + m), so the overall efficiency of the algorithm should be O(n log n + m log n).

grouping first few elements together

My following code does the randomization of an array, however, I am wondering if I want to group first two or three elements together always, how should I proceed?
ArrayList<Integer> numbers = new ArrayList<Integer>();
for(int i=1;i<=11;i++)
{
numbers.add(i);
}
Collections.shuffle(numbers);
for (Integer nums : numbers)
System.out.println(nums);
Example Output: 5, 7, 4, 11, 2, 3, 1, 9, 6, 8, 10
(Note that the sequence '1,2,3' is randomized within the main array.)
Something like this maybe:
final int[] array = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12 };
final int iterations = 10;
final int groupOf = 3;
for (int i = 0; i < array.length; i += groupOf) {
int groupOfRemainder = array.length - i < groupOf ? array.length - i : groupOf;
for (int j = 0; j < iterations; j++) {
int rnd1 = Math.random() * groupOfRemainder;
int rnd2 = Math.random() * groupOfRemainder;
Object temp = array[i + rnd1];
array[i + rnd1] = array[i + rnd2];
array[i + rnd2] = temp;
}
}
public static void shuffleKeepingFirstRTogether(List<Integer> list, int r) {
int size = list.size();
Collections.shuffle(list.subList(0, r));
Collections.shuffle(list.subList(r, size));
Collections.rotate(list, new Random().nextInt(size - r));
}

Remove all zeros from array

I have an array:
[0, 5, 6, 0, 0, 2, 5]
I would like to remove all zeros from it, so that this returns (keeping the same order):
[5, 6, 2, 5]
Is there any easier way to remove all zeros than the following?
int[] array = {0, 5, 6, 0, 0, 2, 5};
int len = 0;
for (int i=0; i<array.length; i++){
if (array[i] != 0)
len++;
}
int [] newArray = new int[len];
for (int i=0, j=0; i<array.length; i++){
if (array[i] != 0) {
newArray[j] = array[i];
j++;
}
}
I haven't been able to find any method in the Arrays class, and Google/SO searches didn't give me any good answers.
This is one of those rare cases where it is easier to show it in code than to explain in plain English:
int targetIndex = 0;
for( int sourceIndex = 0; sourceIndex < array.length; sourceIndex++ )
{
if( array[sourceIndex] != 0 )
array[targetIndex++] = array[sourceIndex];
}
int[] newArray = new int[targetIndex];
System.arraycopy( array, 0, newArray, 0, targetIndex );
return newArray;
How about this:
Integer[] numbers = {1, 3, 6, 0, 4, 0, 3};
List<Integer> list = new ArrayList<Integer>(Arrays.asList(numbers));
list.removeAll(Arrays.asList(Integer.valueOf(0)));
numbers = list.toArray(new Integer[list.size()]);
System.out.println(Arrays.toString(numbers));
OUTPUT:
[1, 3, 6, 4, 3]
With Java 8 you can make a stream out of the array, apply .filter() and then convert it back into an array :
int[] array = {0, 5, 6, 0, 0, 2, 5};
int[] filteredArray = Arrays.stream(array).filter(num -> num != 0).toArray();
// filteredArray = {5, 6, 2, 5};
You can achieve this with one loop only. Whether this is better or more clear is a matter of personal taste I am afraid.
int[] array = {0, 5, 6, 0, 0, 2, 5};
int[] temp = new int[array.length];
int numberOfZeros = 0;
for (int i=0; i<array.length; i++){
if (array[i] != 0){
temp[i-numberOfZeros] = array[i];
} else {
numberOfZeros++;
}
}
int[] result = new int[temp.length-numberOfZeros];
System.arraycopy(temp, 0, result, 0, result.length);
Another option would be to use a List implementation like ArrayList from which you can just remove elements, but then you will have to work with Integer instances and not with ints
List<Integer> originalList = ....;
Iterator<Integer> iterator = originalList.iterator();
while ( iterator.hasNext() ) {
Integer next = iterator.next();
if ( next == 0 ){
iterator.remove();
}
}
//convert to array if needed
Integer[] result = originalList.toArray( new Integer[originalList.size()]);
This example uses Apache Commons library , I hope this will be useful to you
import org.apache.commons.lang.ArrayUtils;
public class Test {
public static void main(String args[]) {
int[] array = {0, 5, 6, 0, 0, 2, 5};
// this loop is to remove all zeros
while(ArrayUtils.contains(array, 0))
array = ArrayUtils.removeElement(array, 0);
// this loop will print the array elemnents
for(int i : array)
System.out.println(i);
}
}
Does the programming language you use employ .map or .reduce functions, or is there an extension that allows you to do this?
In Swift, you can do this via .filter; observe
var orders = [0, 5, 6, 0, 0, 2, 5]
orders = orders.filter({ $0 != 0 })
print (orders)
This returns [5, 6, 2, 5], retaining your order
You can remove zeros in O(1) extra space. Instead of copying the elements into another array you can just return the size and print the same array:
public class RemoveZeros {
static int removeZeros(int[] a){
int j =0;
for(int i =0;i<a.length;i++) {
if(a[i] !=0) {
a[j] = a[i];
j++;
}
}
return j;
}
public static void main(String[] args) {
int[] a = new int[]{0, 5, 6, 0, 0, 2, 5};
int val = removeZeros(a);
for(int i =0;i<val;i++)
System.out.println(a[i]);
}
}
You can use a Vector:
Vector vec = new Vector();
for (int i=0; i<array.length; i++){
if (array[i] != 0)
vec.add(array[i]);
}
vec.toArray()
(this isn't the precise syntax, but you get the idea..)
If you are allowed to user List instead of array, you can do actually nothing but create a new Iteratable interface and apply a method to it like google-collections Collections2.filter() does, you can check it out.
Try the basic way:
public int[] convert(int[] data) {
int count =0;
for (int i =0; i< data.length; i++) {
if(data[i]==0)
count++;
}
int[] nonZero = new int[data.length-count];
int j =0;
for(int i = 0; i<data.length; i++) {
if(data[i]!=0) {
nonZero[j] = data[i];
j++;
}
}
return nonZero;
}
public class RemoveZeros {
public static void main(String[] args) {
int arr[] = {1,0,0,1,0,0,1,0,0,0,0,1,2,0,5};
int n = arr.length;
for(int i=0; i<n; i++) {
if(arr[i]!=0) {
System.out.print(arr[i]+ " ");
}
}
}
}

Categories