【问题标题】:Can i use a while loop to shorten this Scala code我可以使用while循环来缩短这个Scala代码吗
【发布时间】:2015-03-04 15:58:27
【问题描述】:

这段代码可能很长而且很丑,有没有办法使用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 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()
}
}

【问题讨论】:

    标签: scala loops while-loop


    【解决方案1】:

    给你。没有故意解释实际代码,你是在回答一个作业。但是一些一般性的提示——如果你发现自己重复的代码除了操作的数据之外是相同的,那么,是的,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)
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2013-05-04
      • 2020-11-21
      • 1970-01-01
      • 2015-01-14
      • 2020-11-05
      • 2014-02-18
      • 2023-04-03
      • 1970-01-01
      相关资源
      最近更新 更多