Last active
October 17, 2015 04:36
-
-
Save rbobillot/dc2a6bd199a000ffd00d to your computer and use it in GitHub Desktop.
This file contains 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
object TeslaTechQuestion { | |
case class Coord(x:Float, y:Float) // use case class, rather than Tuple | |
val A = Coord(487,143) // shema: B | |
val B = Coord(720,384) // A | |
val C = Coord(839,-235) // C | |
def gradient(a:Coord, b:Coord) = (b.y - a.y) / (b.x - a.x) // calculate 'a' | |
def intersec(a:Coord, b:Coord) = a.y - gradient(a,b) * a.x // calculate 'b' | |
def getCoord(a:Coord, b:Coord, x:Float) = (gradient(a,b) * x + intersec(a,b)) // calculate 'ax + b' | |
def main(av:Array[String]) = { | |
val (x, mX, y, mY) = (A.x, C.x, C.y, B.y) // define minX, maxX, minY, maxY (bounding box limits) | |
val sq = (x.toInt to mX.toInt) // define every integer coord, | |
.map(x => (y.toInt to mY.toInt).map(y => Coord(x,y))) // in bounding box. | |
.map(_.toList).toList // put them in a List[List[Coord]] | |
.foldLeft( List[Coord]() )(_ ++ _) // merge them in a List[Coord] | |
val delimA = (A.x.toInt to B.x.toInt).map( x => Coord(x, getCoord(A,B,x)) ) // for line 'AB' : get every coordinate, for each integer on X axis | |
val delimB = (B.x.toInt to C.x.toInt).map( x => Coord(x, getCoord(B,C,x)) ) // for line 'BC' | |
val delimC = (A.x.toInt to C.x.toInt).map( x => Coord(x, getCoord(A,C,x)) ) // for line 'AC' | |
var srcCoords = sq // get every integer coord, between triangle's boundaries | |
.filter( p => delimA.exists(d => p.x > d.x && p.y < d.y) ) // exclude 'AB' coordinates | |
.filter( p => delimB.exists(d => p.x < d.x && p.y < d.y) ) // exclude 'BC' | |
.filter( p => delimC.exists(d => p.x > d.x && p.y > d.y) ) // exclude 'AC' | |
.filter( c => c.x == c.x.toInt && c.y == c.y.toInt ) // make sure coords are INTEGERS | |
val newCoords = srcCoords.map( c => Coord(c.x + 100, c.y) ) // translate each X coord by 100 -> (1000 * 0.1) -> (speed * time) | |
val commonPts = (srcCoords intersect newCoords) // get every common coorinates between old and translated triangles | |
val bef = srcCoords.size // number of cars in the first triangle | |
val aft = commonPts.size // number of cars within the 2 triangles | |
println( "Before: " + bef + " cars" ) | |
println( "After : " + aft + " cars") | |
println( (bef - aft) + " Model S have escaped" ) // (bef - aft) : number of cars outta boundaries (escaped cars) | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Before: 85220 cars
After : 34843 cars
50377 Model S have escaped