Search code examples
rsortingvectornumeric

How to sort a vector in non-descending order without touching -1 values in R?


The question:

"Some people are standing in a row in a park. There are trees between them which cannot be moved. Your task is to rearrange the people by their heights in a non-descending order without moving the trees. People can be very tall!"

Example

For

 a = [-1, 150, 190, 170, -1, -1, 160, 180],

the output should be

 solution(a) = [-1, 150, 160, 170, -1, -1,   180, 190].

We basically need to scan through this list and see where there a downstep (unless it is to a -1) and then find a way to re-order non -1 elements so that the list is non-ascending. I basically don't know where to even begin on this question. Would anyone give this a go in base R and talk me through your thinking?


Solution

  • a = c(-1, 150, 190, 170, -1, -1, 160, 180)
    a[a>0] = sort(a[a>0])
    a
    
    [1]  -1 150 160 170  -1  -1 180 190
    

    Explanation:

    • a>0 is boolean mask to get the non-trees values:

    FALSE TRUE TRUE TRUE FALSE FALSE TRUE TRUE

    If you apply it to a you get :

    #a[a>0]
    150 160 170 180 190
    

    An thus you can order the values with sort(a[a>0]) and set back to the orignal vector using the same aproach with the boolean mask.

    a[a>0] = sort(a[a>0])