摸鱼的时候看到了一个题,是个老铁在面试泰康时候做的拔高题。咱们也来解一下。

解题思路

  1. 之前不是做个刮刮卡嘛,外面就有刮开占比的显示,那咱们间接用这个计划来解题岂不是美滋滋。刮刮卡成果实现
  2. 通过计算重叠面积失去

    1. 先计算所有圆和矩形的重叠面积,而后把面积加起来
    2. 因为还有一些圆是重叠的,所以咱们须要计算圆和圆的重叠面积,减去
  3. 通过计算矩形每个点是否在圆内,而后求出占比。

好了,临时就想到了这几个计划,你还有吗?

根底数据

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。

计算点与点的间隔,返回是否在危险区间

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))

canvas 计算:0.1364

感觉这个计划好的一点是能够看到后果

jsrun的调试地址:http://jsrun.net/yH6Kp/edit

步长精度是 1

步长精度是 4

调整半径为15

感觉这样的图比拟类似

微信公众号:前端linong

欢送大家关注我的公众号。有疑难也能够加我的微信前端交换群。