Skip to content

Commit 1d59fb6

Browse files
Added ShuffleTheArray
1 parent 270e813 commit 1d59fb6

File tree

1 file changed

+52
-0
lines changed

1 file changed

+52
-0
lines changed

Arrays/ShuffleTheArray.cpp

Lines changed: 52 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,52 @@
1+
/*Question-
2+
Given the array nums consisting of 2n elements in the form [x1,x2,...,xn,y1,y2,...,yn].
3+
Return the array in the form [x1,y1,x2,y2,...,xn,yn].
4+
5+
Example 1:
6+
7+
Input: nums = [2,5,1,3,4,7], n = 3
8+
Output: [2,3,5,4,1,7]
9+
Explanation: Since x1=2, x2=5, x3=1, y1=3, y2=4, y3=7 then the answer is [2,3,5,4,1,7].
10+
Example 2:
11+
12+
Input: nums = [1,2,3,4,4,3,2,1], n = 4
13+
Output: [1,4,2,3,3,2,4,1]
14+
15+
Constraints:
16+
17+
1 <= n <= 500
18+
nums.length == 2n
19+
1 <= nums[i] <= 10^3
20+
21+
*/
22+
#include<bits/stdc++.h>
23+
using namespace std;
24+
// Create a function to shuffle the array
25+
vector<int> shuffle(vector<int> &nums, int n)
26+
{
27+
vector<int> result; //created result to return store the shuffled array elements
28+
for (int i = 0; i < n; i++)//Loop to iterate all the elements
29+
{
30+
result.push_back(nums[i]);//it will push the ith element
31+
result.push_back(nums[n + i]);//it will push the (n+i)th element
32+
}
33+
return result; //Return the shuffled array
34+
}
35+
36+
int main(){
37+
vector<int> nums;//Create a vector to input elements that you want to shuffle
38+
int n,element;
39+
cin>>n;
40+
for (int i = 0; i < n*2; i++)
41+
{
42+
cin>>element;
43+
nums.push_back(element);//Push the element that you want to shuffle
44+
}
45+
vector<int> shuffled=shuffle(nums,n);//created a vector that can store shuffled array
46+
for (int i = 0; i < shuffled.size(); i++)
47+
{
48+
cout<<shuffled[i]<<","; //print the shuffled array element
49+
}
50+
51+
return 0;
52+
}

0 commit comments

Comments
 (0)