3

我再次进行了一些 Code-Wars 挑战,我对这个特定的挑战有疑问:

任务:" 给定一串单词,返回最短单词的长度。

字符串永远不会为空,您不需要考虑不同的数据类型。”

我在 SO 上查找了可用的答案,并设法根据国外的想法自己创建了该程序。

问题是它仍然没有产生所需的输出。

我运行了代码,我认为问题出在变量上,并且我无法分配正确的代码部分。(尽管我可能错了)

所以在下面,我附上代码和测试。

希望大家都能找到问题的答案。

干杯

object Shortest{
  def findShort(str:String):Int ={

    var smallestLength = 99
    var currentLength = 0

    for(word <- str.split("")) {
      currentLength = 0

      for(letter <- word){
        currentLength +=1
      }

      if(currentLength < smallestLength)
        smallestLength = currentLength         
    }
    smallestLength            
  } 
}

以下是测试:

试验结果:

ShortestTest findShort(比特币接管世界也许谁知道)应该返回 3

测试失败 1 不等于 3 堆栈跟踪在 45 毫秒内完成 findShort(结果随机测试用例比写出基本用例更容易)应该返回 3 测试失败

1 不等于 3 堆栈跟踪在 1 毫秒内完成 findShort(让我们谈谈 javascript 最好的语言)应该返回 3 测试失败 1 不等于 3 堆栈跟踪在 1 毫秒内完成 findShort(我想有一天环游世界写代码)应该返回 1 findShort(让所有人都去非常寒冷的地方度假)应该返回 2 测试失败

1 不等于 2 堆栈跟踪在 1 毫秒内完成 findShort(Steem Dogecoin 21inc Dash MadeSafeCoin) 应该返回 4 测试失败

1 不等于 4 堆栈跟踪在 1 毫秒内完成 findShort(Bitcoin Lisk) 应该返回 4 测试失败 1 不等于 4 堆栈跟踪在 1 毫秒内完成 findShort(ProofOfStake Ripple) 应该返回 6 测试失败

1 不等于 6 Stack Trace findShort(ProofOfWork Dogecoin BTC Classic Dash Ripple ProofOfWork) 应该返回 3 测试失败

1 不等于 3 堆栈跟踪在 1 毫秒内完成 findShort(LiteCoin Bitcoin LiteCoin Bitcoin Waves Waves Bitcoin Dash Ripple Ripple Ethereum Classic Factom LiteCoin Factom Waves Factom) 应该返回 4 测试失败

1 不等于 4 堆栈跟踪在 2 毫秒内完成 findShort(Bitcoin Waves MadeSafeCoin DarkCoin ProofOfStake Classic BTC) 应该返回 3 测试失败

1 不等于 3 堆栈跟踪在 1 毫秒内完成 findShort(ProofOfStake Waves Ethereum Ethereum Ripple LiteCoin Steem Classic LiteCoin Ripple ProofOfStake Steem Monero Dogecoin Factom) 应该返回 5 测试失败

4

1 回答 1

4

实际上,您的解决方案还可以,您需要更改的只是str.split("")str.split(" ")注意空格)。

这是一种依赖内置方法的方法:

def findShort(wordsString: String): Int = {
  val wordsArray = wordsString.split(" ")
  wordsArray.minBy(_.length).length
}

println(findShort("LiteCoin Bitcoin LiteCoin Bitcoin Waves Waves Bitcoin Dash Ripple Ripple Ethereum Classic Factom LiteCoin Factom Waves Factom"))
// Display 4
println(findShort("Bitcoin Waves MadeSafeCoin DarkCoin ProofOfStake Classic BTC"))
// Display 3

foldLeft如果您不想依赖内置方法,这里有一个使用的版本:

def length(word: String): Int =
  word.foldLeft(0){case (acc, _) => acc + 1}

def findShort(str:String):Int = {

   str.split(" ").foldLeft(99){ case (smallestLength, word) =>
      val currentLength = length(word)
      if(currentLength < smallestLength)
         currentLength
       else smallestLength
   }
}
于 2019-06-21T12:08:40.950 回答