簡體   English   中英

Scala:比較龐大列表中的所有元素

[英]Scala: Compare all elements in a huge list

請提供有關算法和實現的建議,以比較Scala中很長的列表中的元素。 我有一個包含數千個字符串的列表(來自SQL),我需要將每個列表元素與該列表中的所有其他元素進行比較。

結果,我需要獲取一個元組List[(String, String, Boolean)]List[(String, String, Boolean)]其中前兩個元素是要匹配的字符串,第三個元素是結果。

到目前為止,對於N個元素的列表,我的算法如下:

  1. 占據榜首
  2. 比較head和列表中剩余的N-1個元素
  3. 從舊列表的尾部創建一個新列表,並使用N -1個元素的新列表進行以上所有工作:

碼:

   /**
   * Compare head of the list with each remaining element in this list
   */
  def cmpel(
    fst: String, lst: List[String],
    result: List[(String, String, Boolean)]): List[(String, String, Boolean)] = {

    lst match {
      case next :: tail => cmpel(fst, tail, (fst, next, fst == next) :: result)
      case nill => result.reverse
    }
  }

  /**
   * Compare list elements in all combinations of two
   */
  def cmpAll(lst: List[String],
    result: List[(String, String, Boolean)]): List[(String, String, Boolean)] = {
    lst match {
      case head :: tail => cmpAll(tail, result ++ cmpel(head, tail, List()))
      case nill => result
    }
  }

  def main(args: Array[String]): Unit = {
    val lst = List[String]("a", "b", "b", "a")
    println(cmpAll(lst, List()))
  }

結果:

 List((a,b,false), (a,b,false), (a,a,true), (b,b,true), (b,a,false), (b,a,false))

謝謝!

您可以使用tailsflatMap方法編寫更簡潔,慣用的解決方案:

list.tails.flatMap {
  case x :: rest => rest.map { y =>
    (x, y, x == y)
  }
  case _ => List()
}.toList

tails方法返回一個迭代器,該迭代器將.tail重復應用迭代到列表中。 迭代器中的第一個元素是列表本身,然后是列表的尾部,依此類推,最后返回空列表。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM