1

我正在尝试使用以下代码制作一个简单的前十五名:

    var top = Array(0,0,0,0,0,0,0,0,0,0,0,0,0,0,0)
    val numbers = Array(4,5,8,1,33,23,45,6,11,10,87,46,43,66,55,98,78,71,19,20)


    def getTop() : Unit = {
        for ( i <- 0 to (numbers.length - 1)) {
            set(0, numbers(i), top)
        }

        top.map(x => println(x))
    }

    def set(index: Int, number: Int, top: Array[Int]) : Unit = {
        if (index <= top.length-1) {
            if(top(index) < number) {
                top(index) = number
            }
            else {
                set(index+1, number, top)
            }
        }
    }

该函数应将数组中的前十五个元素复制numbers到 array top,但目前我只得到:

98,78,71,20,0,0,0,0,0,0,0,0,0,0,0

我究竟做错了什么?

4

1 回答 1

2

您的代码不起作用,因为您覆盖了以前设置的数字:

top = Array(0,0,0,0,0,0,0,0,0,0,0,0,0,0,0)  //initially  
top = Array(4,0,0,0,0,0,0,0,0,0,0,0,0,0,0)  // let's call set for '4'  
top = Array(5,0,0,0,0,0,0,0,0,0,0,0,0,0,0)  // now for 5 ...   
top = Array(8,0,0,0,0,0,0,0,0,0,0,0,0,0,0)  
top = Array(8,1,0,0,0,0,0,0,0,0,0,0,0,0,0)  
....

您可以使用要替换到正确位置的相邻放置编号来修复它:

val top = Array.fill(15)(0)
val numbers = Array(4,5,8,1,33,23,45,6,11,10,87,46,43,66,55,98,78,71,19,20)


def printTop() : Unit = {
    for (n <- numbers) {
        set(0, n, top)
    }

    top.foreach(x => println(x))
}

def set(index: Int, number: Int, top: Array[Int]) : Unit = {
    if (index < top.length) {
        val current = top(index)
        if(current < number) {
            top(index) = number
            set(index+1, current, top) // send replaced number down the street
        }
        else {
            set(index+1, number, top)
        }
    }
}
于 2012-11-23T20:44:52.940 回答