首页 > 解决方案 > 将项目从子数组列表分发到其他子数组/有时会随机出错

问题描述

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

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)

}

标签: arraysalgorithmgodata-structuresmaps

解决方案


问题出在这一行:

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

在这里,您假设 的长度thisMap[0]至少为 k,如果例如k为 2 并且thisMap[0]只剩下一个元素,则这是错误的。

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

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

我关于代码组织的两分钱:

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

推荐阅读