我又在做一些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堆栈跟踪在45ms findShort内完成(结果表明随机测试用例比写出基本测试用例更容易)应返回3测试失败
1不等于3堆栈跟踪在1ms内完成findShort(让我们谈谈最好的语言javascript )应该返回3测试失败1不等于3堆栈跟踪在1ms findShort内完成(我希望有一天写代码环游世界)应该返回1 findShort(让所有人去非常冷的地方度假)应该返回2测试失败
%1不等于%2堆栈跟踪在1ms findShort(Steem Dogecoin 21inc Dash MadeSafeCoin)内完成的堆栈跟踪应返回%4测试失败
1不等于4堆栈跟踪在1毫秒内完成findShort(比特币Lisk)应返回4测试失败1不等于4堆栈跟踪在1毫秒findShort内完成(ProofOfStake纹波)应返回6测试失败
%1不等于%6堆栈跟踪findShort(ProofOfWork Dogecoin BTC Classic Dash Ripple ProofOfWork)应返回%3测试失败
1不等于3堆栈跟踪在1ms内完成findShort(LiteCoin比特币LiteCoin比特币Waves比特币破折号波纹以太经典Factom LiteCoin Factom Waves Factom)应返回4测试失败
%1不等于%4堆栈跟踪在2ms findShort(比特币Waves MadeSafeCoin DarkCoin ProofOfStake经典BTC)内完成的堆栈跟踪应返回%3测试失败
1不等于3堆栈跟踪在1毫秒内完成findShort(ProofOfStake Waves以太网波纹LiteCoin Steem Classic LiteCoin Ripple ProofOfStake Steem Monero Dogecoin Factom)应返回5测试失败
发布于 2019-06-21 20:08:41
你的解决方案其实还可以,你只需要把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
}
}https://stackoverflow.com/questions/56702986
复制相似问题