swift - 图中朋友的递归函数逻辑朋友
问题描述
嗨,我有这个json
包含这些部分数据的文件,我将user 1
在这个例子中,需要为我的所有朋友创建一个图形顶点并将其连接到我的用户,然后创建一个顶点并连接我的朋友朋友等等。
[
{
"id": 1,
"name": "Me",
"friends": [25, 24, 16, 8, 13, 12, 7, 15]
},
{
"id": 2,
"name": "Anne Emerson",
"friends": [3, 21, 4, 20, 24, 5, 7, 12, 18]
},
{
"id": 3,
"name": "Ashley Hopper",
"friends": [2, 22, 10, 20, 25, 11]
},
{
"id": 4,
"name": "Alba Gates",
"friends": [2, 17, 21, 11, 7, 13]
},
{
"id": 5,
"name": "Louise Pennington",
"friends": [2, 23, 22, 15, 20, 24]
},
{
"id": 6,
"name": "Shields Gilliam",
"friends": [26]
},
{
"id": 7,
"name": "Freida Evans",
"friends": [1, 4, 2, 9, 18, 17]
},
{
"id": 8,
"name": "Noel Serrano",
"friends": [1, 24, 18, 9, 16, 11, 23]
}
]
我试图编写一个递归函数来抛出我的字段列表,这些字段列表是具有这些 ID 的用户,[3, 21, 4, 20, 24, 5, 7, 12, 18]
如示例中所示。并为我所在的用户创建一个图形顶点并将其与其父用户连接起来。并继续先扔我所有的朋友然后扔我的朋友朋友等等,直到我发现所有与我的用户相关的朋友都直接或间接地天气。
使用的图表方法:
创建父顶点(ME):
let me = graph.createVertex(data: "Me")
将顶点连接在一起:
graph.add(.undirected, from: me, to: user25, weight: 1)
用户型号:
struct User: Codable, Identifiable, Hashable {
enum CodingKeys: CodingKey {
case id
case name
case friends
}
var id: Int
var name: String
var friends: [Int]
}
到目前为止我尝试使用嵌套循环:
for (index, i) in friends.enumerated() {
print("i: \(i)")
let getUserByID = datas.users.filter{ $0.id == index}
for (index, i) in getUserByID.enumerated() {
print(i.friends)
}
}
friends
在哪里let friends = [25, 24, 16, 8, 13, 12, 7, 15]
逻辑还没有打到我,我无法做到这一点,Swift 5
有人可以帮忙吗?
我的朋友相互列表的示例输出:
John Doe - edge distance: 2, Mutual friends: 5
Bob Kemp - edge Distance: 2, Mutual friends: 3
Bryce Holmes - edge Distance: 3
James Smith - edge Distance: 3
该列表应首先按边缘距离排序,其次按共同朋友的数量排序。
解决方案
推荐阅读
- c# - EntityFramework - 使用控制台应用程序时登录数据库的问题
- javascript - 为什么添加商品的方法不正确?
- xcode - iOS 10 UNNotification 不显示警报
- python - Python用不同列表中的值替换列表中的空字符串
- java - 调整固定到 textview 的 drawabletop 图像的大小
- python - setuptools.find_packages 中的“where”参数是什么?
- php - 在服务中获取父存储库而不是我调用 Symfony2.8 的子存储库
- c - Z_MEM_ERROR Zlib deflateInit2() 嵌入式设备
- javascript - 使提示器弹出窗口不隐藏
- ios - 是否可以创建多个 DispatchQueue?