Search code examples
javaarraysinsertion

Adding sets of integers to an array decreasing size of each set added by half


I have two arrays and I want to insert bits of the first array into the second

array1: {1,2,3,4,5,6}

array2: {-1,-1,-1,-1,-1,-1,-1}

My target is add half+1 of the numbers from the first array into the second array for the first iteration And then half of the remaining numbers for each further iteration: e.g.

1st iteration: {-1,-1,-1,1,2,3,4}

Second iteration: {-1,5,6,1,2,3,4}

the input data to be processed consists of exactly N positive integers, where N = 2^M − 2 and M = 3, 4, 5. That is, N = {6, 14, 30}.

I have the code that creates the first iteration: e.g.

for (int i1 = 0, i2 = Array2.length/2; i1 < ((Array2.length/2)+1) && i2 >=0 ;i1++, i2++) {
            Array2[i2] = Array1[i1];
        } 

However to generate the second iteration I am having a lot of trouble. If anyone can give me some advice on how to accomplish this I will really appreciate it!


Solution

  • you can do it simpler, just try this:

        int[] array1 = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14};
        int[] array2 = {-1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1};
    
        int a1 = array1.length;
        int a2 = array2.length - 1;
        int j = 0;
    
        while (a1 > 1) {
            a1 = a1 / 2;
            int l = j;
            for (int i = j; i <= l + a1;) {
                array2[a2 - i] = array1[2*l + a1 - i];
                j = ++i;
            }
        }
        System.out.println(Arrays.toString(array2));
    

    OUTPUT: [-1, 13, 14, 9, 10, 11, 12, 1, 2, 3, 4, 5, 6, 7, 8].

    Note: you may need to check the length of your second array to be greater than first one, I assumed it is.