Skip to content

Instantly share code, notes, and snippets.

@rasjones
Last active May 20, 2016 23:21
Show Gist options
  • Save rasjones/9b2f5d1958eba8ad982466c1ca68c230 to your computer and use it in GitHub Desktop.
Save rasjones/9b2f5d1958eba8ad982466c1ca68c230 to your computer and use it in GitHub Desktop.
Solutions for HackerRank Interview
// derived this formula for summation of odd integers
def calculate(arr: Array[Int]) = {
arr.map{
(days) =>
val numOddPairs = Math.round((days - 1).toDouble / 4)
val numOddNumbers = Math.ceil(days.toDouble / 2).toInt
val midPoint = days match {
case _ => if (numOddNumbers % 2 == 1) Math.ceil(days.toDouble / 2).toInt else 0
}
2 * Math.round((days + 1) / 2) * numOddPairs + midPoint
}
}
calculate((1 to 10).toArray)
//res0: Array[Long] = Array(1, 1, 4, 4, 9, 9, 16, 16, 25, 25)
def customSort(arr: Array[Int]) = {
arr.groupBy(identity).mapValues(_.length).toList.sortBy(x => x._2 -> x._1).flatMap {
case (num, freq) => List.fill(freq)(num)
}
}
customSort(Array(3, 1, 2, 2, 4))
// res2: List[Int] = List(1, 3, 4, 2, 2)
def calculate_amount(arr: Array[Int]) : Long = {
def costFn(cost: Long, discount: Long) : Long = if (discount > cost) 0 else cost - discount
if (arr.length == 0) 0 else
arr.foldLeft((Long.MaxValue, 0.toLong)){
case ((currMin, total), elem) => (Math.min(currMin, elem),
total.toLong + costFn(elem.toLong, Math.min(elem, currMin)))
}._2 + arr.head.toLong
}
calculate_amount(Array(4, 9, 2, 3))
calculate_amount(Array(1, 2, 3, 4))
//res5: Long = 10
//res6: Long = 7
def kSub(k: Int, nums: Array[Int]): Long = {
nums.scanLeft(0)(_ + _).map(_ % k).groupBy(identity).mapValues(_.length).values.map(x => x * (x - 1) / 2).sum
}
kSub(3, Array(1, 2, 3, 4, 1))
kSub(2, Array(1, 2, 1, 2, 1, 2))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment