我正试图用这段代码做一个简单的前十五:
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
中的前15个元素复制到数组top
,但目前我只得到:
98,78,71,20,0,0,0,0,0,0,0,0,0,0,0
我做错了什么?
答案 0 :(得分: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)
}
}
}