Last active
September 24, 2016 22:16
-
-
Save stsatlantis/33c13318646d475a00a885f56dda8fb4 to your computer and use it in GitHub Desktop.
CodeFights - ancientTempleLocation
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| def ancientTempleLocation(r: Int, sa: Array[Int], p: Array[Int]): Array[Int] = { | |
| val xMin = math.min(sa(0),sa(2)) | |
| val yMin = math.min(sa(1),sa(3)) | |
| val xMax = math.max(sa(0),sa(2)) | |
| val yMax = math.max(sa(1),sa(3)) | |
| case class CoordValue(x:Int, y:Int, value: Int,c:Int){ | |
| def this(x:Int,y:Int,cv:(Int,Int)) = this(x,y,cv._1,cv._2) | |
| def toArray = Array(x,y) | |
| } | |
| def maxBy[T](xs: List[T], compare :(T,T) => Int) = | |
| (List(xs.head) /: xs.tail) { | |
| (acc, y) => | |
| compare(y,acc.head) match { | |
| case 1 => List(y) | |
| case 0 => y :: acc | |
| case -1 => acc | |
| } | |
| } | |
| def compareByC(t:CoordValue , that: CoordValue) = t.c compare that.c | |
| def compareByValue(t:CoordValue ,that: CoordValue) = t.value compare that.value | |
| def compareByXY(t:CoordValue, that:CoordValue) = (t.x+t.y) compare (that.x+that.y) | |
| def compareByX(t:CoordValue, that:CoordValue) = that.x compare t.x | |
| def calcDistance(x1:Int, y1: Int, x2: Int, y2: Int) = math.sqrt((x1-x2)*(x1-x2) + (y1-y2)*(y1-y2)) | |
| def contains(x:Int, y: Int) = if(xMin <= x && x <= xMax && yMin <= y && y <= yMax) 1 else 0 | |
| def calcMatrixValue(x: Int, y: Int) = p(0) * x + p(1) * y + p(2) * x * y + p(3) * x * x + p(4) * y * y | |
| def calcReactangeValue(x:Int, y: Int) = { | |
| var v = 0 | |
| var c = 0 | |
| for { | |
| i <- x-r to x+r | |
| j <- y-r to y+r | |
| } yield (if(calcDistance(i,j,x,y) <= r){ | |
| v = v + calcMatrixValue(i-r+xMin,j-r+yMin) | |
| c = c + contains(i-r+xMin,j-r+yMin) | |
| }) | |
| (v,c) | |
| } | |
| val rect = | |
| for{ | |
| x <- xMin to xMax | |
| y <- yMin to yMax | |
| } yield new CoordValue(x,y,calcReactangeValue(x+r-xMin,y+r-yMin)) | |
| maxBy(maxBy(maxBy(maxBy(rect.toList,compareByValue),compareByC),compareByXY),compareByX)(0).toArray | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment