ENع
→Expected cost
الدرس 05 · Measuring cost

Expected cost of randomised algorithms

لم يُترجم بعد؛ يُعرض باللغة الإنجليزية

14 دقيقة11 خطوة5 أسئلةBeginner
عن هذا الدرس

Some algorithms flip coins on purpose, so the same input can cost a different amount each run. Here you shuffle a list of 4 numbers, count how often the best-so-far changes, and find the expected cost two ways: by averaging all 24 equally likely shuffles, and by adding one small indicator variable per position (linearity of expectation). The Software lesson "How fast is fast? Big O" introduces counting steps, and the Maths lessons "Logarithms and exponents" and "Recurrences: describing a value by smaller cases" cover the ln n that appears at the end.

ستتعلّم

حدّد ما تشعر بأنك أتقنته. هذا التقييم الذاتي لا يؤثر في درجة الدرس.

شكل 5 · تفاعلي
01 / 11

Random choices, random cost

A randomised algorithm makes random choices as it runs. This one shuffles the list, then scans it and counts how often best changes. That count is our cost. Same input, different shuffles, different costs.

cost model: one unit each time best is set
  1  import random
  2  def count_updates(a):
  3      random.shuffle(a)
  4      best, count = a[0], 1
  5      for x in a[1:]:
  6          if x > best:
  7              best = x
  8              count += 1
  9      return count

input a = [3, 1, 4, 2], n = 4
random.shuffle(a) reorders a in place
جارٍ تحميل الرسم…
أو ← →
اقرأ الدرس خطوة بخطوة
  1. Random choices, random cost

    A randomised algorithm makes random choices as it runs. This one shuffles the list, then scans it and counts how often best changes. That count is our cost. Same input, different shuffles, different costs.

    cost model: one unit each time best is set
      1  import random
      2  def count_updates(a):
      3      random.shuffle(a)
      4      best, count = a[0], 1
      5      for x in a[1:]:
      6          if x > best:
      7              best = x
      8              count += 1
      9      return count
    
    input a = [3, 1, 4, 2], n = 4
    random.shuffle(a) reorders a in place
  2. One run: 2 updates

    The shuffle gives [2, 4, 1, 3]. best starts at 2, count 1. Then 4 beats 2: an update. 1 and 3 do not beat 4. This run costs 2 updates.

    order [2, 4, 1, 3]
      i=1  x=2  first: best = 2, count = 1
      i=2  x=4  4 > 2: best = 4, count = 2
      i=3  x=1  1 < 4: skip
      i=4  x=3  3 < 4: skip
    return 2
  3. Unlucky: 4 updates

    Run it again on the same input. This time the shuffle lands sorted: [1, 2, 3, 4]. Every number beats the one before, so best changes at every position: 4 updates, the most possible.

    order [1, 2, 3, 4]
      i=1  x=1  first: best = 1, count = 1
      i=2  x=2  2 > 1: best = 2, count = 2
      i=3  x=3  3 > 2: best = 3, count = 3
      i=4  x=4  4 > 3: best = 4, count = 4
    return 4
  4. Lucky: 1 update

    Once more: [4, 1, 3, 2]. The largest number comes first, nothing beats it, and the cost is 1. So the cost is a random variable: a number that depends on chance.

    order [4, 1, 3, 2]
      i=1  x=4  first: best = 4, count = 1
      i=2  x=1  1 < 4: skip
      i=3  x=3  3 < 4: skip
      i=4  x=2  2 < 4: skip
    return 1
  5. Try every shuffle

    A fair shuffle makes all 24 orders of 4 numbers equally likely. Run each once and drop a cube on the bar for its cost: 6, 11, 6, 1 runs cost 1, 2, 3 and 4 updates.

    4! = 24 orders, each with chance 1/24
    updates   runs
       1        6
       2       11
       3        6
       4        1
    total     24 runs
  6. Expected cost: the average

    Expected cost is the average over all equally likely choices. The 24 runs make 50 updates in total, so E[cost] = 50/24 = 25/12 ≈ 2.08. The marker sits where the bars would balance.

    E[X] = sum of (cost × chance)
         = 1·6/24 + 2·11/24 + 3·6/24 + 4·1/24
         = (6 + 22 + 18 + 4)/24 = 50/24
         = 25/12 ≈ 2.08 updates
    worst case 4, best case 1
  7. One lamp per position

    Listing orders gets slow. Instead give position i a lamp X_i that shows 1 if best changes there. Run [1, 3, 2, 4]: lamps 1, 2 and 4 light, and the cost is their sum, 1 + 1 + 0 + 1 = 3.

    indicator variable: X_i = 1 if position i updates best, else 0
    cost X = X_1 + X_2 + X_3 + X_4
    order [1, 3, 2, 4]
      i=1  x=1  first: best = 1, count = 1
      i=2  x=3  3 > 1: best = 3, count = 2
      i=3  x=2  2 < 3: skip
      i=4  x=4  4 > 3: best = 4, count = 3
    return 3
  8. Each lamp: chance 1/i

    Position i updates only if it holds the largest of the first i numbers. In a fair shuffle that largest one is equally likely to be in any of those i places, so Pr[X_i = 1] = 1/i: lamps glow 1, ½, ⅓ and ¼.

    Pr[X_i = 1] = 1/i, and E[X_i] = 1·Pr[X_i = 1] + 0 = 1/i
    check against the 24 orders:
      X_1 is on in 24 of 24 = 1/1
      X_2 is on in 12 of 24 = 1/2
      X_3 is on in  8 of 24 = 1/3
      X_4 is on in  6 of 24 = 1/4
  9. Add the lamps

    Linearity of expectation: the average of a sum is the sum of the averages. So E[cost] = 1 + ½ + ⅓ + ¼ = 25/12, the same balance point as the 24 runs, with no list at all.

    E[X_1 + X_2 + X_3 + X_4] = E[X_1] + E[X_2] + E[X_3] + E[X_4]
      = 1 + 1/2 + 1/3 + 1/4 = (12 + 6 + 4 + 3)/12 = 25/12
      = (24 + 12 + 8 + 6)/24, the 24-run total 50
    linearity holds even when the X_i depend on each other
  10. Any n: about ln n

    The same sum works for any list size n: E[cost] = 1 + ½ + ... + 1/n, which grows like ln n. For n = 1000 that is about 7.49 updates, while the unlucky worst case is 1000. Expected O(log n).

    E[cost] = H_n = 1 + 1/2 + 1/3 + ... + 1/n
    ln(n + 1) < H_n ≤ ln n + 1, so H_n ~ ln n
    n = 4      H_4 = 2.08
    n = 100    H_100 ≈ 5.19
    n = 1000   H_1000 ≈ 7.49   (worst case 1000)
  11. No input is unlucky

    The luck is in the shuffle, not the data. Even a sorted list, the worst input for a plain scan, gets shuffled first, so every input has the same expected cost, 25/12. Expected cost averages over the coin flips only.

    input [1, 2, 3, 4]: without the shuffle, 4 updates every time
    with the shuffle: any of the 24 orders, e.g. [4, 2, 3, 1]
    expected cost for EVERY input: 25/12 ≈ 2.08
    average case (random inputs) ≠ expected cost (random choices)

اختبار يتاح بعد الخطوة الأخيرة.