Search code examples
c++arrayssortingarraylistarr

how to put all odd number in left an even number in right on array


Given two arrays of integers A and B of sizes N and M respectively. Write a function named MIX with four arguments, which will produce and return a third array named C. such that the following sequence is followed.

-All odd numbers of A from left to right are copied into C from left to right. -All eve numbers of A from left to right are copied into C from right to left. -All odd numbers of B from left to right are copied into C from left to right. -All even numbers of B from left to right are copied into C from right to left.

Sample #1

Input

6 7
3 2 1 7 6 3
9 3 5 6 2 8 10

Output

3 1 7 3 9 3 5 10 8 2 6 6 2

code in c++

#include<iostream> 
#include<vector>
#include<algorithm>
using namespace std;
vector<int> insert (vector<int> &a, vector<int> &b)
{
  vector<int>c;

for (int i = 0 ;i < a.size() ; i ++) 
{
  if (a[i]%2!=0 )
    c.push_back(a[i]);
  else 

    c.insert(c.begin(),a[i]);
}
      for(int j = 0; j < b.size() ; j++)
  {
 if (b[j]%2!=0 )

       c.push_back(b[j]);    
  else 
  
        c.insert(c.begin(),b[j]);
      }
return c;
}
int main (void){
  int as;
  int bs;
  cin>>as>>bs;
  vector<int> a(as);  
  vector<int> b(bs);
  for(int i =0 ; i <a.size();i++)
  {
    cin>>a[i];
  }
  for(int k =0 ; k<b.size();k++)
  {
    cin>>b[k];
  }  
  vector<int> c=insert(a,b);
  for(int & v: c)
        cout<<v<<"    ";
  return 0;
}

Solution

  • #include <vector>
    #include <algorithm>
    
    static bool is_odd(int n) { return n % 2 == 1; }
    
    // Let a == {3, 2, 1, 7, 6, 3} as example
    static std::vector<int>::iterator order_odds_first_and_reverse_evens(std::vector<int> &a) {
        // a == {3, 2, 1, 7, 6, 3}
        const auto first_even{stable_partition(a.begin(), a.end(), is_odd)};
        // a == {3, 1, 7, 3, 2, 6}
        reverse(first_even, a.end());
        // a == {3, 1, 7, 3, 6, 2}
        return first_even;
        // first_even points to 6
    }
    
    std::vector<int> insert(std::vector<int> &a, std::vector<int> &b) {
        // b == {9, 3, 5, 6, 2, 8, 10}
        order_odds_first_and_reverse_evens(b);
        // b == {9, 3, 5, 10, 8, 2, 6}
    
        // a == {3, 2, 1, 7, 6, 3}
        a.insert(
            order_odds_first_and_reverse_evens(a), // a == {3, 1, 7, 3, 6, 2}
            b.begin(), 
            b.end()
        );
        // a == {3, 1, 7, 3, 9, 3, 5, 10, 8, 2, 6, 6, 2}
        return a;
    }