我可以使用while循环来缩短这个Scala代码吗
这段代码可能很长很难看,有没有办法用while循环或其他方法缩短它?我是scala编程新手我可以使用while循环来缩短这个Scala代码吗,scala,loops,while-loop,Scala,Loops,While Loop,这段代码可能很长很难看,有没有办法用while循环或其他方法缩短它?我是scala编程新手 object VendingMachine { /** You need to write a program to calculate the coins that a vending * machine should dispense as change in an 8 element array (one array * element for each denomination of
object VendingMachine {
/** You need to write a program to calculate the coins that a vending
* machine should dispense as change in an 8 element array (one array
* element for each denomination of coin)
*
* For example:
* giveTheChange(242) gives Array(1,0,0,2,0,0,1,0)
*
* As 242p = (1*£2)+(0*£1)+(0*50p)+(2*20p)+(0*10p)+(0*5p)+(1*2p)+(0*1p)
*/
def giveTheChange(money : Int) : Array[Int] = {
// TODO: Complete this method.
// Write your solution here
var change:Array[Int] = new Array[Int](8)
var changegiven = money
count = 0
if(changegiven >= 200){
count = changegiven / 200
change(0) = count
changegiven = changegive%200
}
return change()
}
}
给你。没有故意解释实际代码,您正在寻找作业的答案。但是有一些一般性的提示——如果您发现自己重复的代码与操作的数据不同,那么,是的,while循环可能是一种可能性,但是在Scala这样的语言中,有丰富的函数编程功能选择和广泛的集合库,还有其他选择 您需要迭代各种硬币大小。您可以使用数组和该数组上的循环来完成此操作。我有一条经验法则,如果我只使用索引来检索数组的当前元素(也就是说,索引的值在任何其他方面都不重要),那么可能有一种更优雅的方法来实现它 在Scala中,我们有许多迭代集合的方法
foldLeft
很有启发性,因为它允许我们在行进中迭代一个数组来收集一些东西,这里我们想要收集要使用的硬币
另一种观点:一旦我处理了最大的硬币,我剩下的钱就更少了,还有一套更小的硬币。所以我有一个小问题。最终,我没有硬币和钱,也没有更多的事可做。这种分而治之的方法提出了一种递归解决方案
def giveTheChange(money:Int): Array[Int] = {
val coins = List(200,100,50,20,10,5,2,1)
coins.foldLeft((List[Int](), money))
{ case ((change, amount), coin) =>
((amount / coin) :: change, amount % coin) }
._1
.reverse
.toArray
}
giveTheChange(242)
//> res0: Array[Int] = Array(1, 0, 0, 2, 0, 0, 1, 0)
以及另一种方法
def giveTheChange2(money:Int): Array[Int] = {
def gtChelper(coins:List[Int], money:Int):List[Int] = coins match {
case Nil => Nil
case c::t => (money / c) :: gtChelper(t, money % c)
}
val coins = List(200,100,50,20,10,5,2,1)
gtChelper(coins, money).toArray
}
giveTheChange2(242)
//> res1: Array[Int] = Array(1, 0, 0, 2, 0, 0, 1, 0)