1

Let $E_1, E_2, \ldots, E_n$ be boolean-valued expressions, each with an associated evaluation cost and probability of returning true. For simplicity, assume these probabilities are independent, so that $\mathbb{P}(E_i \cap E_j) = \mathbb{P}(E_i) \, \mathbb{P}(E_j)$ for $i \ne j$.

Suppose we want to compute the expression $E_1 \mathbin{\&\&} E_2 \cdots \mathbin{\&\&} E_n$. Here $\mathbin{\&\&}$ means short-circuit evaluation, so if $E_1$ is false then $E_2$ is not evaluated, etc. The expected cost of a short-circuit evaluation is

$$ \mathop{\mathbb{E}} \mathrm{cost}(E_i \mathbin{\&\&} E_j) = \mathrm{cost}(E_i) + \mathbb{P}(E_i) \, \mathrm{cost}(E_j) \\\\ \mathop{\mathbb{E}} \mathrm{cost}(E_i \mathbin{\&\&} E_j \mathbin{\&\&} E_k \cdots) = \mathrm{cost}(E_i) + \mathbb{P}(E_i) (\mathrm{cost}(E_j) + \mathbb{P}(E_j) (\mathrm{cost}(E_k) + \cdots)) \\\\ $$

If the expressions have no side effects then they can be freely reordered. Is there an efficient way to find the ordering with the lowest expected cost? There is a dynamic programming algorithm based on finding the min-cost ordering of every subset:

$$ \min \mathrm{cost} \{E_1, E_2, \ldots, E_n\} = \min_i [\mathrm{cost}(E_i) + \mathbb{P}(E_i)\min \mathrm{cost} \{\ldots, E_{i-1}, E_{i+1}, \ldots\}] $$

but since it computes costs for every subset it takes $O(2^n)$ time.

D.W.
  • 159,275
  • 20
  • 227
  • 470
  • Intuitively, which expression would it make sense to test first? Try to prove your intuition. – Yuval Filmus Nov 28 '22 at 22:34
  • Can you credit the original source where you encountered this? What chapter are you studying? Are you guaranteed that the events are all independent for all subsets (not just all pairs)? – D.W. Nov 28 '22 at 22:53
  • Well... it depends. Might be good to start with the one with the lowest probability. But if that one has a high cost, then a cheaper one with slightly higher odds might be better – Tavian Barnes Nov 28 '22 at 22:53
  • I think you might have missed an important part of Yuval Filmus's comment: "Try to prove your intuition." Please don't just leave a comment with a guess at a solution -- spend the time to test whether your guess is a correct solution. You might find the following helpful: https://cs.stackexchange.com/q/59964/755 – D.W. Nov 28 '22 at 22:54
  • @D.W. I came up with this problem myself. The context is optimizing expressions in a program I wrote. I implemented it for binary operations a while ago and was thinking how to extend it to 3+ expressions. For more context see https://tavianator.com/2017/bfs_3.html – Tavian Barnes Nov 28 '22 at 22:56

0 Answers0