Shifting/aligning/rotating a circular buffer to zero in-place

前端 未结 5 1655
谎友^
谎友^ 2021-02-02 00:13

I\'m using a circular buffer to push data onto either end of a list. After I\'m done I want to align the buffer so the first element in the list is at position zero and can be u

5条回答
  •  死守一世寂寞
    2021-02-02 01:08

    fn swapItems arr index_a index_b = (
    
        local item_a = arr[index_a]
        local item_b = arr[index_b]
        arr[index_a] = item_b
        arr[index_b] = item_a
    ),
    fn rotateItems arr cnt way:#right = (
    
        for i=1 to cnt do ( --how many times we shift
    
            case way of (
    
                #right:(
                    local next = 2
                    for j=1 to arr.count-1 do ( --shift each except last
    
                        swapItems arr 1 next --swap first with next
                        next+=1
                    )
                )
                #left:(
                    local prev = arr.count - 1
                    for j=arr.count to 2 by -1 do ( --shift each except first
    
                        swapItems arr arr.count prev --swap last with prev
                        prev-=1
                    )
                )
            )
        )
    )
    ar = #(1, 2, 3, 4)
    mcArray.rotateItems ar 1 > #(4, 1, 2, 3)
    mcArray.rotateItems ar 2 > #(3, 4, 1, 2)
    mcArray.rotateItems ar 1 way:#left > #(2, 3, 4, 1)
    

提交回复
热议问题