This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
val input = Array(1,2,3,4,3,4,1,2,3,4,6,2) | |
println(evaluate(input)) | |
def evaluate(arr: Array[Int]): Int = { | |
val p = peaks(arr) | |
var i = arr.length | |
while (i > 0) { | |
if (arr.length % i == 0 | |
&& canSplit(arr.length, p , arr.length/i)) { | |
return i | |
} | |
i -= 1 | |
} | |
0 | |
} | |
def canSplit(arrLength: Int, | |
peaks: IndexedSeq[Int], | |
numberOfChunks: Int): Boolean = { | |
// checks if we can split into numberOfChunks chunks | |
def aux(currentChunkIndex: Int, peakIndex: Int): Boolean = { | |
val endOfChunk = currentChunkIndex + numberOfChunks | |
if (currentChunkIndex == arrLength) true | |
else if (peakIndex == peaks.length) false | |
else { | |
if (peaks(peakIndex) >= currentChunkIndex | |
&& peaks(peakIndex) < endOfChunk) { | |
aux(endOfChunk, peakIndex + 1) | |
} | |
else { | |
aux(currentChunkIndex, peakIndex + 1) | |
} | |
} | |
} | |
aux(0, 0) | |
} | |
def peaks(arr: Array[Int]): IndexedSeq[Int] = { | |
(1 until arr.length - 1).filter ( i => | |
arr(i) > arr(i+1) && arr(i) > arr(i-1) | |
) | |
} |
No comments:
Post a Comment