摸鱼的时候看到了一个题,是个老铁在面试泰康时候作的拔高题。咱们也来解一下。前端
经过计算重叠面积获得面试
好了,暂时就想到了这几个方案,你还有吗?算法
baseList = [ {type: 'rect', x: 0, y: 0, w: 100, h: 100} ] warnList = [ {type: 'round', x: 60, y: 95, r: 10}, {type: 'round', x: 50, y: 80, r: 10}, {type: 'round', x: 20, y: 30, r: 10}, {type: 'round', x: 70, y: 50, r: 10}, {type: 'round', x: 80, y: 25, r: 10} ]
有了基础数据咱们就能够开始搞了,咱们把圆定义为 10。canvas
function isSafe(x, y) { // 具备危险的地点 var dangers = warnList // 两点的距离 return dangers.every((p1)=>{ return Math.sqrt(Math.pow(p1.x - x, 2) + Math.pow(p1.y - y, 2)) > p1.r }) }
baseList = [ {type: 'rect', x: 0, y: 0, w: 100, h: 100} ] warnList = [ {type: 'round', x: 60, y: 95, r: 10}, {type: 'round', x: 50, y: 80, r: 10}, {type: 'round', x: 20, y: 30, r: 10}, {type: 'round', x: 70, y: 50, r: 10}, {type: 'round', x: 80, y: 25, r: 10} ] function isSafe(x, y) { // 具备危险的地点 var dangers = warnList // 两点的距离 return dangers.every((p1)=>{ return Math.sqrt(Math.pow(p1.x - x, 2) + Math.pow(p1.y - y, 2)) > p1.r }) } count = 0;//循环次数表明点数,其实能够直接乘出来。 countSafe = 0; for(let xStart = baseList[0].x, xEnd = baseList[0].x + baseList[0].w; xStart <= xEnd; xStart++ ){ for(let yStart = baseList[0].y, yEnd = baseList[0].y + baseList[0].h; yStart <= yEnd; yStart++ ){ count++ if(isSafe(xStart, yStart)) countSafe++ } } console.log(count, countSafe, 1-(countSafe/count))
感受这个方案好的一点是能够看到结果segmentfault
jsrun的调试地址:http://jsrun.net/yH6Kp/edit微信
感受这样的图比较类似spa
今天在网上找计算圆与矩形、圆与圆重叠面积的题,结果发现了这个算法,咱们也来实现一下。.net
欢迎你们关注个人公众号。有疑问也能够加个人微信前端交流群。3d