Home > Software design >  How can i insert elements of one array into second one?
How can i insert elements of one array into second one?

Time:11-11

int nums1[] = {1,2,3,0,0,0}; //instead of zeros i want to add elements of nums2
int nums2[] = {2,5,6};
for(int i=3;i<nums1.length;i  ){
    for(int j=0;j<nums2.length;j  ){
        nums1[i]=nums2[j];
    }
}

System.out.println(Arrays.toString(nums1));

The output I want is (sorted)

[1,2,2,3,5,6]

but my output is

[1, 2, 3, 6, 6, 6].

CodePudding user response:

you don't want a nested loop. A single loop with multiple indexes is what you are after.

import org.junit.jupiter.api.Test;

import java.util.Arrays;

import static org.assertj.core.api.Assertions.assertThat;

public class ReplaceArrayItems {
    @Test
    void testReplaceItems() {
        int nums1[] = {1, 2, 3, 0, 0, 0}; //instead of zeros i want to add elements of nums2
        int nums2[] = {2, 5, 6};
        for (int i = 3, j = 0; i < nums1.length && j < nums2.length; i  , j  ) {
            nums1[i] = nums2[j];
        }

        assertThat(nums1).isEqualTo(new int[]{1, 2, 3, 2, 5, 6});
        System.out.println(Arrays.toString(nums1));
    }
}

CodePudding user response:

I think what you're looking for is something like this:

int nums1[] = {1, 2, 3, 0, 0, 0};
int nums2[] = {2, 5, 6};
for (int i = 0, j = 0; i < nums1.length && j < nums2.length; i  )
    if(nums1[i] == 0)
        nums1[i] = nums2[j  ];

Arrays.sort(nums1);
System.out.println(Arrays.toString(nums1));
  • Related