Compute the area covered by cards randomly put on a table

前端 未结 5 1335
故里飘歌
故里飘歌 2021-02-07 10:20

This is an interview question, the interview has been done.

Given a deck of rectangular cards, put them randomly on a rectangular table whose size is much larger than t

5条回答
  •  悲&欢浪女
    2021-02-07 10:51

    Here's an idea that is not perfect but is practically useful. You design an algorithm that depends on an accuracy measure epsilon (eps). Imagine you split the space into squares of size eps x eps. Now you want to count the number of squares lying inside the cards. Let the number of cards be n and let the sides of the cards be h and w.

    Here is a naive way to do it:

    S = {} // Hashset
    for every card:
       for x in [min x value of card, max x value of card] step eps:
           for y in [min y value of card, max y value of card] step eps:
               if (x, y) is in the card:
                   S.add((x, y))
    return size(S) * eps * eps
    

    The algorithm runs in O(n * (S/eps)^2) and the error is strongly bounded by (2 * S * n * eps), therefore the relative error is at most (2 * eps * n / S).

    So for example, to guarantee an error of less than 1%, you have to choose eps less than S / (200 n) and the algorithm runs in about 200^2 * n^3 steps.

提交回复
热议问题