How to rearrange an array by indices array?

前端 未结 9 2047
故里飘歌
故里飘歌 2021-02-01 19:12

Given an array arr and an array of indices ind, I\'d like to rearrange arr in-place to satisfy the given indices. For exa

9条回答
  •  误落风尘
    2021-02-01 19:46

    Below, one may find a PARTIAL solution for a case when we have only ONE cycle, i.e.

    var arr = ["A", "B", "C", "D", "E", "F"];
    var ind = [4, 2, 5, 0, 1, 3];
    
    function rearrange( i, arr, ind, temp ){
        if( temp ){
            if( arr[ind[i]] ){
                var temp2 = arr[ind[i]];
                arr[ind[i]] = temp;
                rearrange( ind[i], arr, ind, temp2 );
            }
            else{                                           // cycle
                arr[ind[i]] = temp;
                // var unvisited_index = ...;
                // if( unvisited_index ) rearrange( unvisited_index, arr, ind, "" );
            }
        }
        else{
            if( i == ind[i] ){
                if( i < arr.length ) rearrange( i + 1, arr, ind, temp );    
            }
            else{
                temp = arr[ind[i]];
                arr[ind[i]]=arr[i];
                arr[i] = "";
                i = ind[i];
                rearrange(i, arr, ind, temp );
            }
        }
    }
    
    rearrange( 0, arr, ind, "" );
    

    To make this solution to work for a general case, we need to find total numbers of unique cycles and one index from each of them.

    For the OP example:

    var arr = ["A", "B", "C", "D", "E", "F"];
    var ind = [4, 0, 5, 2, 1, 3];
    

    There are 2 unique cycles:

    4 -> 1 -> 0 -> 4
    5 -> 3 -> 2 -> 5
    

    If one runs

    rearrange( 0, arr, ind, "" );
    rearrange( 5, arr, ind, "" );
    

    S(he) will get desirable output for the OP problem.

提交回复
热议问题