首页 > 解决方案 > Scala 不可变数组过滤条件

问题描述

我正在使用项目中的邻接矩阵,我需要安全地移除边缘。

我正在从事的项目以下列方式使用矩阵: Map[Agent, Array[Edge]]. 我想使用该Array.filter功能来删除有问题的边缘。我这样做是为了避免使用索引或zipWithIndex.

在向矩阵添加四个“代理”并添加两个无向边之后,这就是我的矩阵的样子:

A1: null, 1.1, null, null, 
A2: 1.1, null, null, null, 
A3: null, null, null, 1.2, 
A4: null, null, 1.2, null, 

如您所见,边缘是 (A1, A2) 和 (A3, A4)。

要删除边缘(A1,A2),我正在使用这个:

map = map.updated(a1, map(a2).filter(e => e != null && e.toAgent != a2))

但是,这将删除空条目(如预期的那样)。这是使用上述技术删除边缘后我的矩阵的样子:

A1: 1.1, 
A2: 
A3: null, null, null, 1.2, 
A4: null, null, 1.2, null, 

空条目的作用很重要,因为它允许我在正确位置快速插入新边。我正在寻找过滤掉单个边缘的解决方案。

简单地做的问题:

map = map.updated(a1, map(a2).filter(e => e.toAgent != a2))

是我正在对空条目进行操作,这会导致NullPointerException (显然)。我正在寻找解决方案。

重申一下,我想使用每个边缘的属性进行过滤,该属性可能为空,也可能不为空。有没有办法实现一种“如果为空则跳过”

感谢您的帮助和建议。

标签: scalafilteradjacency-matrix

解决方案


你最好使用Option而不是拥有null元素。ScalaOption是比null.

A1: None,      Some(1.1), None,      None, 
A2: Some(1.1), None,      None,      None, 
A3: None,      None,      None,      Some(1.2), 
A4: None,      None,      Some(1.2), None,

你可以filterOption它只会测试Some值和跳过None值。

map = map.updated(a1, map(a2).map(_.filter(_.toAgent == a2)))

推荐阅读