2017-06-17 81 views
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 } 

不正確。跟蹤原始bigArraysmallArray的正確方法是什麼?

什麼,我得到的是

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與在來自headtuple2(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 

回答

2

您可以使用zipWithIndex以前sliding

for (smallArrayWithIndex <- bigArray.zipWithIndex.sliding(n)) { 
    val startingIndex = smallArrayWithIndex.head.map { case (_, index) => index } 
    val smallArray = smallArrayWithIndex.map { case (e, _) => e } 
    println("smallArray starts at index " + index + " and contains " + smallArray) 
} 
+0

感謝。我需要做些什麼來允許標準'map'作用於'(Int,Int)'smallArrayWithIndex.head'。 –

+0

我無法獲得'map'來解決,但是您使用'zipWithIndex'的幫助最終讓我到那裏。謝謝。 –