doumei9832 2018-06-03 17:35
浏览 15

给定两个映射,如何找到两者之间的公用密钥?

I have two structs, Employee and Project.

type Employee struct {
    ID        int
    Projects map[*Departments]struct{}
}

type Project struct {
        ID        int
}

I have a Company struct that has the following:

type Company struct {
  Projects     map[*Project]map[*Employee]struct{}
  Employees       map[*Employee]struct{}
}

Given e *Employee and c *Company (func (c *Company) getEmployeesOnSameProject(e *Employee) []*Employee { } )and knowing that an employee can belong to multiple projects, I am having a difficult time figuring out how to get the employees across projects.

e.Projects might be something like -

eProjects {
  P1
  P2
} 

c.Projects might be something like -

cProjects {
  P1 {
    E1
    E2
  }
  P2 {
    E1
    E2
    E3
    E4
  }
}

If I am E1, how can I easily get the other employees on the same projects (P1 and P2) as me without having a nested for loop?

  • 写回答

1条回答 默认 最新

  • douzheng9221 2018-06-03 18:10
    关注

    If I understand correctly, in an idea world you'd like to be able to lookup "employees for a given project" as well as "projects for a given employee"?

    Without knowing the context that you will be using this code in; e.g. more writes than reads, more reads than writes, what the space vs. time complexity requirements are.

    If you are aiming for O(1) lookup for projects for an employee and O(1) lookup for employees for a project, then I would suggest creating your own datastructure to be able to facilitate this. This is the smallest interface that would work:

    type ProjectEmployees interface {
        RegisterProjectEmployee(p *Project, e *Employee)
        GetEmployees(p *Project) []*Employees
        GetProjects(e *Employee) []*Project
    }
    

    I haven't listed a full implementation below as it would be trivial to work out, but you'd implement this interface with a struct that store 2 maps.

    The tradeoff is that you have a larger write / update cost, and data duplication, the benefit is O(1) lookups in both directions Project <--> Employee.

    type projecEmployeesMap struct {
        pe map[*Project][]*Employee
        ep map[*Employee][]*Project
    }
    
    func (p *projectEmployeesMap) RegisterProjectEmployee(p *Project, e *Employee) {
        p.pe[p] = append(p.pe[p], e) // store the mapping project -> employees
        p.ep[e] = append(p.ep[e], p) // store the mapping employees --> project
    }
    

    The get methods should be easy to implement with simple map lookups

    评论

报告相同问题?

悬赏问题

  • ¥15 seatunnel 怎么配置Elasticsearch
  • ¥15 PSCAD安装问题 ERROR: Visual Studio 2013, 2015, 2017 or 2019 is not found in the system.
  • ¥15 (标签-MATLAB|关键词-多址)
  • ¥15 关于#MATLAB#的问题,如何解决?(相关搜索:信噪比,系统容量)
  • ¥500 52810做蓝牙接受端
  • ¥15 基于PLC的三轴机械手程序
  • ¥15 多址通信方式的抗噪声性能和系统容量对比
  • ¥15 winform的chart曲线生成时有凸起
  • ¥15 msix packaging tool打包问题
  • ¥15 finalshell节点的搭建代码和那个端口代码教程