解一道泰康的拔高面试题:面积占比

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

image.png

解题思路

  1. 以前不是作个刮刮卡嘛,里面就有刮开占比的显示,那咱们直接用这个方案来解题岂不是美滋滋。刮刮卡效果实现
    image.png
  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。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))

image.png

canvas 计算:0.1364

感受这个方案好的一点是能够看到结果segmentfault

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

步长精度是 1

image.png

步长精度是 4

image.png

调整半径为15

感受这样的图比较类似
image.pngspa

蒙特卡洛算法(统计模拟法,我认为是玄学算法)

今天在网上找计算圆与矩形圆与圆重叠面积的题,结果发现了这个算法,咱们也来实现一下。.net

9999999次:0.14850091485009154

image.png

99999999次:0.14849383148493833

image.png

9999次:0.1472147214721472

image.png

微信公众号:前端linong

欢迎你们关注个人公众号。有疑问也能够加个人微信前端交流群。3d

clipboard.png

相关文章
相关标签/搜索