我对scala和编程很新(只是为了好玩)而且我正在尝试理解尾递归和集合,但是debugg真的很难。
我有2个名单:
val quoters = List[Map[String,List[String]]]
val quoted = List[Map[String,List[String]]]
前:
val quoters = List(Map("author1"->List("1","7","8")),Map("author2"->List("2","4","6","3")),Map("author3"->List("5","2","1","3")))
val quoted = List(Map("author1"->List("5","6")),Map("author2"->List("5","8","1")),Map("author3"->List("4")))
“引用”引用“引用”和“引用”也引用“引用”。
在示例中:
author1 quoted author2 with "1" and "8",
author2 quoted author3 with "4",
author3 quoted author1 with "5" & author2 with "5" + "1"
我想找到引用“引用”引用“引用”的“引用”圈子......
输出应该是这样的:
val quotesCircle = List(
Map("quoter"->"author1","receiver"->"author2","quote"->"4"),
Map("quoter"->"author2","receiver"->"author3","quote"->"2"),
Map("quoter"->"author3","receiver"->"author1","quote"->"1")
)
我的问题:
1 /我认为我在滥用收藏品(Json似乎太多了......)2 /我可以与列表列表交叉:
def getintersect(q1:List[List[String]],q2:List[List[String]])={
for(x<-q1;r<-q2; if (x intersect r) != Nil)yield x intersect r
}
但没有地图列表的结构。
3 /我尝试了这个用于递归,但是它没有用,因为......我真的不知道:def getintersect(q1:List[List[String]],q2:List[List[String]])= {
def getQuotedFromIntersect(quoteMatching:List[String],quoted:List[List[String]]):List[List[String]]={
for(x<-q1;r<-q2; if (x intersect r) != Nil)
getQuotedFromIntersect(x intersect r,quoted)
}
}
我希望我足够清楚:/
提前谢谢!
菲利克斯
答案 0 :(得分:0)
我认为您的数据结构中有一个额外的图层。我可能会使用“作者”这个名称而不是“引用”,以避免混淆,因为引用/引用之间的共鸣:
val quoters = List(
Map("author1"->List("1","7","8")),
Map("author2"->List("2","4","6","3")),
Map("author3"->List("5","2","1","3")))
val authors = Map(
"author1" -> List(5, 6),
"author2" -> List(5, 8, 1),
"author3" -> List(4))
有了这个,还有一个像这样的小功能:
def findQuoters(article: Int): List[String] = {
quoters.keys.toList filter { name =>
quoters(name) contains article
}
}
然后,您可以开始尝试不同的收集和报告方式,引用哪位作者以及在哪里,例如:
// For each name in the 'authors' map:
// For each article authored by this name:
// Find all quoters of this article
// Report that author 'name' has been quoted for article 'id' by 'whom'...
for (name <- authors.keys) {
for (article <- authors(name)) {
val qq = findQuoters(article)
println("author %s has been quoted %d times for article %d by %s".format(
name, qq.size, article, qq.mkString(" ")))
}
}
打印输出如下:
author author1 has been quoted 1 times for article 5 by author3
author author1 has been quoted 1 times for article 6 by author2
author author2 has been quoted 1 times for article 5 by author3
author author2 has been quoted 1 times for article 8 by author1
author author2 has been quoted 2 times for article 1 by author1 author3
author author3 has been quoted 1 times for article 4 by author2
现在,想一想你用这些关联数组映射的内容。您可以有效地构建图形的邻接矩阵。你会如何在有向图中找到所有圆圈?