import scala.collection.mutable
object DivideArray {
def canDivideArrayIntoSets(nums: Array[Int], k: Int): Boolean = {
if (nums.length % k != 0) return false
val numCount = mutable.Map[Int, Int]().withDefaultValue(0)
for (num <- nums) {
numCount(num) += 1
}
for (num <- nums.distinct.sorted) {
val count = numCount(num)
if (count > 0) {
for (i <- num until num + k) {
if (numCount(i) < count) {
return false
}
numCount(i) -= count
}
}
}
true
}
def main(args: Array[String]): Unit = {
val nums1 = Array(1, 2, 3, 3, 4, 4, 5, 6)
val k1 = 4
val nums2 = Array(1, 2, 3, 4, 5, 6)
val k2 = 2
val nums3 = Array(3, 2, 1, 2, 3, 4, 4, 5)
val k3 = 4
println(s"Can divide nums1 into sets of $k1 consecutive numbers: ${canDivideArrayIntoSets(nums1, k1)}")
println(s"Can divide nums2 into sets of $k2 consecutive numbers: ${canDivideArrayIntoSets(nums2, k2)}")
println(s"Can divide nums3 into sets of $k3 consecutive numbers: ${canDivideArrayIntoSets(nums3, k3)}")
}
}