Shuffle an array according to the given order of elements

Posted in

Shuffle an array according to the given order of elements
vinaykhatri

Vinay Khatri
Last updated on June 15, 2024

    Problem

    Given two integer arrays of the same size, arr [] and index[] , reorder elements in arr [] according to the given index array.

    Sample Input

    [10, 11, 12]
    [1, 0, 2]

    Sample Output

    11, 10, 12
    0, 1, 2

    Approach

    We can traverse through 0 to n-1 (where n is the size of the arrays) and keep placing the current elements at the correct indices. This will ultimately give us the required array. For this, we can swap index[i] with index[index[i]] and arr[index[i]] with arr[i] .

    C++ Programming

    #include<bits/stdc++.h>
    using namespace std;
    void solve(int a[], int n, int index[]){
        for(int i=0;i<n;i++){
            int temp = index[i];
            swap(index[index[i]], index[i]);
            swap(a[temp], a[i]);
        }
    }
    int main(){
        int a[] = {50, 40, 70, 60, 90};
        int index[] = {3,  0,  4,  1,  2};
        int n =sizeof(a)/sizeof(a[0]);
        solve(a, n, index);
        for(int i=0;i<n;i++) cout<<a[i]<<" ";
        cout<<"\n";
        for(int i=0;i<n;i++) cout<<index[i]<<" ";
    }

    Output

    40 60 90 50 70 
    0 1 2 3 4

    C Programming

    #include<stdio.h>
    void swap(int *x, int *y)
    {
        int temp = *x;
        *x = *y;
        *y = temp;
    }
    
    void solve(int a[], int n, int index[]){
        for(int i=0;i<n;i++){
            int temp = index[i];
            swap(&index[index[i]], &index[i]);
            swap(&a[temp], &a[i]);
        }
    }
    int main(){
        int a[] = {50, 40, 70, 60, 90};
        int index[] = {3,  0,  4,  1,  2};
        int n =sizeof(a)/sizeof(a[0]);
        solve(a, n, index);
        for(int i=0;i<n;i++) printf("%d ", a[i]);
        printf("\n");
        for(int i=0;i<n;i++) printf("%d ", index[i]);
    }

    Output

    40 60 90 50 70 
    0 1 2 3 4

    Python Programming

    def solve(a, index, n):
        for i in range(0, n):
            temp = index[i]
            t = index[index[i]]
            index[index[i]] = index[i]
            index[i] = t
            t = a[temp]
            a[temp] = a[i]
            a[i] = t
    
    
    a = [50, 40, 70, 60, 90]
    index = [3,  0,  4,  1,  2]
    n = len(a)
    solve(a, index, n)
    print(a)
    print(index)

    Output

    [40, 60, 90, 50, 70] 
    [0, 1, 2, 3, 4]
    

    People are also reading:

    Leave a Comment on this Post

    0 Comments