doulang1945 2015-10-10 22:04
浏览 105

这是合理且惯用的GoLang循环移位实现吗?

Can anyone comment on whether this is a reasonable and idiomatic way of implementing circular shift of integer arrays in Go? (I deliberately chose not to use bitwise operations.)

How could it be improved?

package main

import "fmt"

func main() {
    a := []int{1,2,3,4,5,6,7,8,9,10}
    fmt.Println(a)
    rotateR(a, 5)
    fmt.Println(a)
    rotateL(a, 5)
    fmt.Println(a)
}

func rotateL(a []int, i int) {
    for count := 1; count <= i; count++ {
        tmp := a[0]
        for n := 1;n < len(a);n++ {
            a[n-1] = a[n]
        }
        a[len(a)-1] = tmp
    }
}

func rotateR(a []int, i int) {
    for count := 1; count <= i; count++ {
        tmp := a[len(a)-1]
        for n := len(a)-2;n >=0 ;n-- {
            a[n+1] = a[n]
        }
        a[0] = tmp
    }
}
  • 写回答

3条回答 默认 最新

  • duanguoping2016 2015-10-11 10:15
    关注

    Your code is fine for in-place modification.

    Don't clearly understand what you mean by bitwise operations. Maybe this

    package main
    
        import "fmt"
    
        func main() {
            a := []int{1, 2, 3, 4, 5, 6, 7, 8, 9, 10}
            fmt.Println(a)
            rotateR(&a, 4)
            fmt.Println(a)
            rotateL(&a, 4)
            fmt.Println(a)
        }
    
        func rotateL(a *[]int, i int) {
            x, b := (*a)[:i], (*a)[i:]
            *a = append(b, x...)
        }
    
        func rotateR(a *[]int, i int) {
            x, b := (*a)[:(len(*a)-i)], (*a)[(len(*a)-i):]
            *a = append(b, x...)
        }
    

    Code works https://play.golang.org/p/0VtiRFQVl7

    It's called reslicing in Go vocabulary. Tradeoff is coping and looping in your snippet vs dynamic allocation in this. It's your choice, but in case of shifting 10000 elements array by one position reslicing looks much cheaper.

    评论

报告相同问题?

悬赏问题

  • ¥15 虚幻5 UE美术毛发渲染
  • ¥15 CVRP 图论 物流运输优化
  • ¥15 Tableau online 嵌入ppt失败
  • ¥100 支付宝网页转账系统不识别账号
  • ¥15 基于单片机的靶位控制系统
  • ¥15 真我手机蓝牙传输进度消息被关闭了,怎么打开?(关键词-消息通知)
  • ¥15 装 pytorch 的时候出了好多问题,遇到这种情况怎么处理?
  • ¥20 IOS游览器某宝手机网页版自动立即购买JavaScript脚本
  • ¥15 手机接入宽带网线,如何释放宽带全部速度
  • ¥30 关于#r语言#的问题:如何对R语言中mfgarch包中构建的garch-midas模型进行样本内长期波动率预测和样本外长期波动率预测