2

我知道这是一个冗长的问题:) 我正在尝试在 Scala 2.11 中的数据集上实现哈密顿循环,作为其中的一部分,我正在尝试从值映射生成邻接矩阵。

解释:

键 0 到 4 是不同的城市,所以在下面的“allRoads”变量中

0 -> Set(1, 2) Means city0 is connected to city1 and city2
1 -> Set(0, 2, 3, 4) Means City1 is connected to city0,city2,city3,city4
.
.

我需要生成adj Matrix,例如:如果城市是连接的,我需要生成1,否则我必须生成0,意思是

for: "0 -> Set(1, 2)", I need to generate: Map(0 -> Array(0,1,1,0,0)) 

输入-

var allRoads = Map(0 -> Set(1, 2), 1 -> Set(0, 2, 3, 4), 2 -> Set(0, 1, 3, 4), 3 -> Set(2, 4, 1), 4 -> Set(2, 3, 1)) 

我的代码:

val n: Int = 5
val listOfCities = (0 to n-1).toList
var allRoads = Map(0 -> Set(1, 2), 1 -> Set(0, 2, 3, 4), 2 -> Set(0, 1, 3, 4), 3 -> Set(2, 4, 1), 4 -> Set(2, 3, 1))
var adjmat:Array[Int] = Map()

  for( i <- 0 until allRoads.size;j <- listOfCities) {
    allRoads.get(i) match {
      case Some(elem) => if (elem.contains(j)) adjmat = adjmat:+1 else adjmat = adjmat :+0
      case _ => None
    }
  }

输出:

output: Array[Int] = Array(0, 1, 1, 0, 0, 1, 0, 1, 1, 1, 1, 1, 0, 1, 1, 0, 1, 1, 0, 1, 0, 1, 1, 1, 0)

预期输出 - 像这样的东西,请建议是否有更好的东西来生成哈密顿循环的输入

Map(0 -> Array(0, 1, 1, 0, 0),1 -> Array(1, 0, 1, 1, 1),2 -> Array(1, 1, 0, 1, 1),3 -> Array(0, 1, 1, 0, 1),4 -> Array(0, 1, 1, 1, 0))

不确定如何将上述输出存储为 Map 或 Plain 2D Array。

4

1 回答 1

1

尝试

val cities = listOfCities.toSet
allRoads.map { case (city, roads) =>
  city -> listOfCities.map(city => if ((cities diff roads).contains(city)) 0 else 1)
}

哪个输出

Map(0 -> List(0, 1, 1, 0, 0), 1 -> List(1, 0, 1, 1, 1), 2 -> List(1, 1, 0, 1, 1), 3 -> List(0, 1, 1, 0, 1), 4 -> List(0, 1, 1, 1, 0))
于 2019-07-07T09:25:59.453 回答