Click here to Skip to main content
15,890,185 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
How can I change the location of members of an array based on members of another array?

I am given an array A with length X, and another array B containing Z pairs of elements from A.

The program should output a Z by X array, where the n th row is the result of swapping the n th pair of elements in B.

What I have tried:

For example:
First array: X=4, A[4] = [4 1 5 6]
Second array: Z=3, B[3][2]=[[4 1] [1 6] [5 5]]
Program output:
G[Z][X]=
[ [1 4 5 6] // 4 and 1 swapped
[6 4 5 1] // 1 and 6 swapped
[6 4 5 1] ] // 5 and 5 swapped
Posted
Updated 16-Apr-20 0:17am

"Yes - You can!" if you array isnt constant declared.

(a) first you must extract and save one element,
(b) than you can assign the second value to the first one
(c) and last you assign the first (and saved) value to the second element.
C++
int arr[4] = {1,4,5,6};
int t = arr[0];//(a)
arr[0] = arr[1];//(b)
arr[1] = t;//(c)
 
Share this answer
 
Comments
CPallini 16-Apr-20 7:33am    
5.
So declare and fill array A and B.
Then declare array result as 2D, X by Z elements.

Then you need two nested loops: One to process each "row" in B, and one to porcess each element of A.
In the inner loop, copy each element of A to the output row.
Then apply the swap operation as specified in the B row to the output row you just created.

After the loops, print it.

If that doesn't make a lot of sense, then get some paper and a pencil, and give it a try manually. When you have the idea sorted in your mind, you can start coding.

But this is your homework, and I'll not give you the code! (Hint: it's pretty simple stuff when you work out what you have to do.)
 
Share this answer
 
Comments
CPallini 16-Apr-20 7:33am    
5.

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900