合并包含 Scala 中常见元素的集合集合 [英] Merge Sets of Sets that contain common elements in Scala

查看:40
本文介绍了合并包含 Scala 中常见元素的集合集合的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想在 Scala 中实现一个函数,即,给定一组 Int 集合,将合并包含一个或多个常见元素的任何包含集合.

I want to implement a function in Scala, that, given a Set of Sets of Ints will merge any containing Set that contains one or more common elements.

例如,给定:

def mergeSets(sets: Set[Set[Int]]): Set[Set[Int]] = ???

val sets = Set(Set(1,2), Set(2,3), Set(3,7), Set(8,10))  
val mergedSets = mergeSets(sets)

mergedSets 将包含 Set(Set(1,2,3,7), Set(8,10))

mergedSets will contain Set(Set(1,2,3,7), Set(8,10))

如果可能,在 Scala 中执行此操作的一种不错、高效且实用的方法是什么?

What would be a nice, efficient and functional if possible, way to do this in Scala?

推荐答案

最有效的方法是使用可变结构,但您要求使用函数式方法,所以这里是:

The most efficient way to do this will be using mutable structures, but you asked for a functional way, so here goes:

sets.foldLeft(Set.empty[Set[Int]])((cum, cur) => {
  val (hasCommon, rest) = cum.partition(_ & cur nonEmpty)
  rest + (cur ++ hasCommon.flatten)
})

(未测试,用手机写的)

(Not tested, wrote this using phone)

这篇关于合并包含 Scala 中常见元素的集合集合的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆