有什么更好的方法可以更稳定地解决这一问题?

时间:2019-07-14 06:34:44

标签: scala functional-programming immutability tail-recursion immutable-collections

我正在尝试解决HackerRank上的问题。我正在尝试以更实用的方式(使用不变性)解决此问题。我已经尝试过一种解决方案,但是对此我没有完全的信心。

这里是问题的链接:

https://www.hackerrank.com/challenges/sock-merchant/problem?h_l=interview&playlist_slugs%5B%5D=interview-preparation-kit&playlist_slugs%5B%5D=warmup

我的可变解决方案如下:

/**
  * Mutable solution
  * MSet => mutable set is used
  * val pairs => it is delclared var and getting reassigned
  */

import scala.annotation.tailrec
import scala.collection.mutable.{Set => MSet}

def sockMerchant2(n: Int, ar: Array[Int]): Int = {
  val sockInventory : MSet[Int] = MSet.empty[Int]
  var pairs = 0
  ar.foreach { elem =>
    if(sockInventory.contains(elem)) {
      pairs = pairs + 1
      sockInventory -= elem
    } else sockInventory += elem
  }
  pairs
}

sockMerchant(5, Array(1,2,1,2,4,2,2))

相同解决方案的不变版本:

/**
  * Solution with tail recursion.
  * Immutable Set is used. No variable is getting reassigned
  * How it is getting handled internally ?
  * In each iteration new states are assigned to same variables.
  * @param n
  * @param ar
  * @return
  */

import scala.annotation.tailrec
def sockMerchant(n: Int, ar: Array[Int]): Int = {
  @tailrec
  def loop(arr: Array[Int], counter: Int, sockInventory: Set[Int]): Int ={
    if(arr.isEmpty) counter
    else if(sockInventory.contains(arr.head))
      loop(arr.tail, counter +1, sockInventory-arr.head)
    else loop(arr.tail, counter, sockInventory + arr.head)
  }
  loop(ar, 0, Set.empty)
}

sockMerchant(5, Array(1,2,1,2,4,2,2))

考虑函数式编程原理,什么是解决此问题的理想方法?

1 个答案:

答案 0 :(得分:2)

第一种可能是使用模式匹配:

  def sockMerchant(n: Int, ar: Array[Int]): Int = {
    @tailrec
    def loop(list: List[Int], counter: Int, sockInventory: Set[Int]): Int =
    list match {
      case Nil =>
        counter
      case x::xs if sockInventory.contains(x) =>
        loop(xs, counter +1, sockInventory-x)
      case x::xs =>
        loop(xs, counter, sockInventory + x)
    }
    loop(ar.toList, 0, Set.empty)
  }

如果将Array更改为List,则会得到一个易读的解决方案。

甚至更实用的解决方案解决方案是使用folding

  def sockMerchant(n: Int, ar: Array[Int]): Int = {
    ar.foldLeft((0, Set.empty[Int])){case ((counter, sockInventory), x: Int) =>
      if (sockInventory.contains(x))
        (counter +1, sockInventory-x)
        else
        (counter, sockInventory + x)
    }._1
  }

这有点难以阅读/理解-因此,当我开始时,我更喜欢使用recursion的版本。

并且 jwvh 在其注释中显示-如果您无法使用 Scala 在同一行中执行-您可能会错过一些东西;)。

相关问题