import scala.collection.mutable
import scala.collection.immutable
/**
* Created by pliashkr on 4/20/2017.
*/
object Arrays {
// Ix a => (b -> c -> b) -> b -> (a,a) -> [(a,c)] -> Array a b
def accumArray[A <% Ordered[A], B, C](f: (B, C) => B, initial: B, bounds: (A, A), pairs: Seq[(A, C)]): Seq[(A, B)] = {
@scala.annotation.tailrec
def accum(xs: Seq[(A, C)], xz: Seq[(A, B)]): Seq[(A, B)] = {
(xs, xz) match {
case (Seq(), _) => xz
case ((a, u) +: xsr, Vector()) => accum(xsr, Vector[(A, B)]((a, f(initial, u))))
case (((a1, u)) +: xsr, xzr :+ ((a2, v))) =>
if (a1 == a2) accum(xsr, xzr :+(a2, f(v, u)))
else accum(xsr, xz :+(a1, f(initial, u)))
}
}
val (min, max) = bounds
val ys = pairs.filter { case (x, _) => x >= min && x <= max }.sortBy(_._1)
accum(ys, Vector())
}
def main(args: Array[String]) {
val sourceArray = Array(8, 23, 9, 0, 12, 11, 1, 10, 13, 7, 41, 4, 14, 21, 5, 17, 3, 19, 2, 6)
val xs = sourceArray.zip(List.fill(sourceArray.length)(1))
println(accumArray[Int, Int, Int]((v, u) => v + u, 0, (0, sourceArray.length), xs))
}
}
// def accumArray[R, T](acc: (R, T) => R, initial: R, bounds: (Int, Int), pairs: Array[(Int, T)]): Unit = {
// var map = mutable.LinkedHashMap[Int, R]()
//
// for (pair <- pairs; if pair._1 >= bounds._1 && bounds._2 >= pair._1) {
// map(pair._1) = map.get(pair._1).map(u => acc.apply(u, pair._2)).getOrElse(acc.apply(initial, pair._2))
// }
//
// for (e <- map) {
// println(e)
// }
//
// }
//
//
//}
Be the first to comment
You can use [html][/html], [css][/css], [php][/php] and more to embed the code. Urls are automatically hyperlinked. Line breaks and paragraphs are automatically generated.