fork download
  1. object Main extends App {
  2. def createInitList(r:Range, depth:Int):Map[Int, Int] = {
  3. depth match {
  4. case x if x<0 => Map(1 -> 1)
  5. case 1 => r.map(v=> (v->1)).toMap
  6. case n => {
  7. val m = createInitList(r, depth-1)
  8. val ret = collection.mutable.Map[Int, Int]().withDefaultValue(0)
  9. for(k <- r; v <- m){
  10. ret(v._1 * k) = ret(v._1 * k) + v._2
  11. }
  12. ret.toMap
  13. }
  14. }
  15. }
  16.  
  17. def medianFromCompressedSeq(lst:List[Tuple2[Int, Int]]):Int = {
  18. val sorted = lst.sortBy(_._1)
  19. println(sorted.take(20))
  20. val cumulativeList = sorted.foldLeft(List(Tuple3(0,0,0)))((r, v) => {
  21. Tuple3(v._1, r.head._3, v._2 + r.head._3)::r
  22. })
  23. val tot = cumulativeList.head._3
  24.  
  25. // 本当は tot が偶数/奇数で処理が微妙にちがうが、
  26. // sample でも奇数決め打ちでやっているのでそれに従う
  27. val ind = (tot+1)/2
  28. val ret = cumulativeList.find(v => {v._2 < ind && v._3 >= ind})
  29. assert(ret != None)
  30. ret.get._1
  31. }
  32.  
  33. val vec = createInitList(1 to 31, 5).toList
  34. println(medianFromCompressedSeq(vec))
  35. }
Success #stdin #stdout 1.11s 382080KB
stdin
Standard input is empty
stdout
List((1,1), (2,5), (3,5), (4,15), (5,5), (6,25), (7,5), (8,35), (9,15), (10,25), (11,5), (12,75), (13,5), (14,25), (15,25), (16,70), (17,5), (18,75), (19,5), (20,75))
356400