0
在scala中Array
上使用sliding
函數時,根據原始數組跟蹤滑動子數組的索引是什麼正確的方法?如何跟蹤Array.sliding中的索引
// Initialize some data
val bigArray = List(2, 3, 4, 2, 3, 6, 8, 4, 5).toArray
val n:Int = 5
// Slide through the big array
for (smallArray <- bigArray.sliding(n)) {
val thirdValue:Int = smallArray(3)
val k = (bigArray zip smallArray) lastIndexWhere { case (x, y) => x < y }
if (bigArray(k+1) >= thirdValue) {
println(bigArray.toList.toString +
" has "
+ bigArray(k+1)
+ " >= "
+ thirdValue
+ " in "
+ smallArray.toList.toString
+ " at index "
+ k+1)
}
現在我知道
val k = (bigArray zip smallArray) lastIndexWhere { case (x, y) => x < y }
不正確。跟蹤原始bigArray
的smallArray
的正確方法是什麼?
什麼,我得到的是
List(2, 3, 4, 2, 3, 6, 8, 4, 5) has 2 >= 2 in List(2, 3, 4, 2, 3) at index -11
List(2, 3, 4, 2, 3, 6, 8, 4, 5) has 6 >= 3 in List(3, 4, 2, 3, 6) at index 41
List(2, 3, 4, 2, 3, 6, 8, 4, 5) has 6 >= 6 in List(4, 2, 3, 6, 8) at index 41
List(2, 3, 4, 2, 3, 6, 8, 4, 5) has 6 >= 4 in List(3, 6, 8, 4, 5) at index 41
,我需要
List(2, 3, 4, 2, 3, 6, 8, 4, 5) has 6 >= 2 in List(2, 3, 4, 2, 3) at index 5
List(2, 3, 4, 2, 3, 6, 8, 4, 5) has 8 >= 3 in List(3, 4, 2, 3, 6) at index 6
更新
我無法得到map
與在來自head
的tuple2(Int, Int)
工作接受的答案,但提到zipWithIndex
讓我在那裏,所以我接受了有用的答案。這是我結束了:
for (zipArray <- bigArray.slice(0, bigArray.length - 1).zipWithIndex.sliding(n)) {
val j = zipArray.head._2
val k = zipArray.last._2
val smallArray = bigArray.slice(j, k)
val thirdValue:Int = smallArray(3)
if (bigArray(k+1) >= thirdValue) {
println(bigArray.toList.toString +
" has "
+ bigArray(k+1)
+ " >= "
+ thirdValue
+ " in "
+ smallArray.toList.toString
+ " at index "
+ (k+1))
}
}
這將產生:
List(2, 3, 4, 2, 3, 6, 8, 4, 5) has 6 >= 2 in List(2, 3, 4, 2) at index 5
List(2, 3, 4, 2, 3, 6, 8, 4, 5) has 8 >= 3 in List(3, 4, 2, 3) at index 6
感謝。我需要做些什麼來允許標準'map'作用於'(Int,Int)'smallArrayWithIndex.head'。 –
我無法獲得'map'來解決,但是您使用'zipWithIndex'的幫助最終讓我到那裏。謝謝。 –