Skip to content

Instantly share code, notes, and snippets.

@polyglotpiglet
Created February 16, 2016 20:13
Show Gist options
  • Save polyglotpiglet/b72fce3d6f2e0ba77f07 to your computer and use it in GitHub Desktop.
Save polyglotpiglet/b72fce3d6f2e0ba77f07 to your computer and use it in GitHub Desktop.
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)
)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment