arrays - 有时将子数组列表中的项目分发到其他子数组/作品然后随机出错

标签 arrays algorithm go data-structures maps

我有一个创建数组列表的程序。第一个数组填充有值,而其他数组可以为空或不为空。如果它是空的,我们从第一个数组中取出一个值并移动到一个空数组。目标是永远不要在列表中有一个空数组

Array      Values
    A1 -> V1, V2, V3, V4, V5 // add extra val to whatever is nxt in line
    A2  <------|----------| //add A1[0][1] and A1[0][4] since its extra
    A3  <----------|       //add A1[0][2]
    A4  <--------------|   //add A1[0][3]

这是我的。我感到困惑的是,它是随机让索引超出范围,而有时它会起作用,而且我相信有一种更优化和更有效的方法来做到这一点。我很想看到它。

package main

import "fmt"

func main(){

    //Create list of arrays
    something := []string{"first", "second", "third"}
    something2 := []string{""}
    something3 := []string{""}


    thisMap := make(map[int] []string, 0)


    //assign them
    thisMap[0] = something
    thisMap[1] = something2
    thisMap[2] = something3



    //loop through the maps
    for k, v := range thisMap{
        //if the key is great than 0
        if k > 0 {
            //loop through the array
            for _, items := range v {

                //if the item is empty
                if items == "" {
                    //we remove the empty string since we dont need it 
                    v = v[1:]
                    //append the k value from the first array to the k array
                    v = append(v, thisMap[0][k])

                    //We update the array and remove the item we just assigned from the initial array
                    thisMap[0] = append(thisMap[0][:k], thisMap[0][k+1:]...)

                }

            }
            //Assign the arrays back to the map
            thisMap[k] = v
        }

    }
    fmt.Println(thisMap)

}

最佳答案

问题出在这一行:

v = append(v, thisMap[0][k])

在这里,您认为 thisMap[0] 的长度至少为 k,如果例如 k 为 2 且 thisMap[0 ] 只剩下一个元素。

由于映射键/值对的迭代以随机顺序发生,如果幸运的话,顺序将是 2、1、0,一切都会正常进行。如果运气不好,可能会遇到超出范围的问题。

不是从 thisMap[0] 中选择位置 k 的元素,而是应该获取第一个元素、最后一个元素或随机元素,但总是考虑到 thisMap[0] 的当前长度。

关于代码组织的两点意见:

  • thisMap[0] 和 map 的其他条目显然在您的算法中扮演着不同的角色。所以你应该命名你的变量并组织你的代码来反射(reflect)这一点。例如,您可以编写一个函数,它接受一个 []string,并返回一个 map[int][]string,甚至可能是一个 [][]string
  • 我认为用一个空字符串初始化输出列表,然后删除它会引入不必要的噪音,您可以初始化空输出列表。另外,我不确定这部分的实现是否正确!

关于arrays - 有时将子数组列表中的项目分发到其他子数组/作品然后随机出错,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50396555/

相关文章:

c# - 从帖子标题生成一个唯一的字符串,如 stackoverflow

go - golang中的模块缓存在哪里?

amazon-web-services - 获取自日期以来创建的EC2实例列表

go - 在辅助路由中提供静态文件 ("/route/secondary/route") Golang

c++ - 如何在 C++ 中将零一矩阵求任意幂?

python - Numpy 根据索引求和多维数组中的元素

javascript - 返回数组中最大值的索引

java - 如何用数组引用这里

algorithm - 对公式已知的表面进行光线追踪的最有效方法是什么?

python - 乱七八糟的字谜最长的字 python