dshun123456 2019-03-21 18:02
浏览 49
已采纳

如何在Go中使用数组范围添加嵌套循环的索引?

I am working on printing the index of the numbers that leads to the sum that is entered through input by user. I have basically used the tradition method of using two loops of i & j and iterate until array length. However, when it comes to Go Language, we do have an option of getting index & key value of array using a different format in Go.

Here's my working code:

func findKIndex(arr []int, k int) (int, int) {
    index1, index2 := 0, 0
    Length := len(arr)
    for i := 0; i < Length; i++ {
        for j := i + 1; j < Length; j++ {
            if arr[i]+arr[j] == k {
                index1 = i
                index2 = j
            }
        }
    }
    return index1, index2
}

How do I do the same thing using :

for idx, key := range arr{
    for idx2, key2 := range arr {
        //statements
    }
}

Basically, I am not able to figure out initiating the inner index with +1 of outer index or may do it in a single loop.

  • 写回答

1条回答 默认 最新

  • dongzhu6900 2019-03-21 18:27
    关注

    Just iterate over a slice starting at idx+1:

    https://play.golang.org/p/KDITT8zQ6q-

    for idx, key := range arr{
        for idx2, key2 := range arr[idx+1:] {
            //actual second index is idx + idx2 + 1
            //statements
        }
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥20 基于MSP430f5529的MPU6050驱动,求出欧拉角
  • ¥20 Java-Oj-桌布的计算
  • ¥15 powerbuilder中的datawindow数据整合到新的DataWindow
  • ¥20 有人知道这种图怎么画吗?
  • ¥15 pyqt6如何引用qrc文件加载里面的的资源
  • ¥15 安卓JNI项目使用lua上的问题
  • ¥20 RL+GNN解决人员排班问题时梯度消失
  • ¥60 要数控稳压电源测试数据
  • ¥15 能帮我写下这个编程吗
  • ¥15 ikuai客户端l2tp协议链接报终止15信号和无法将p.p.p6转换为我的l2tp线路