Search code examples
c++arraysfor-loopfunction-definition

Rewriting array in given order


I need to rewrite an array in given order below:

Write a void shuffle function (int* we, int count, int* wy) that rewrites the the elements of the we array (where the count parameter specifies the size of the we array) to the array wy according.

I tried with for loop to divide the array for i < 5 and i > 5 but all the time got some problems. The only one which work for now is rewriting element[0]. Any help?

#include <iostream>

using namespace std; 

void zadanie1(void)
{

    int count = 11;
    int* we = new int[count];
    int* wy = new int[count];


    cout << "Begin: " << endl;

    for (int i = 0; i < count; i++) {
        we[i] = rand() % 10;
        cout << we[i] << " ";
    }
    cout << endl;

    cout << "End: " << endl;

    for (int i = 0; i < count; i++) {
        if (i == 0) {
            wy[i] = we[i];
            cout << wy[i] << " ";
            i++;
        };
        
        
    };
}

Solution

  • From the image, you see that you map the element i->2*i for i=0...5, and i->2*i-11 for i=6..10. Thus the required loop is

    for (int i = 0; i <= 5; i++)
      wy[2 * i] = we[i];
    
    for (int i = 6; i < 11; i++)
      wy[2 * i - 11] = we[i];
    

    For a general size count the loop looks like

    for (int i = 0; i <= (count / 2); i++)
      wy[2 * i] = we[i];
    
    for (int i = (count / 2) + 1; i < count; i++)
      wy[2 * i - count] = we[i];