CSC300: Induction: Is this function useful? [5/15] Previous pageContentsNext page

01
02
03
04
05
06
07
08
09
10
11
public static int f (boolean[] a) {
  int result = 0;
  while (someTrue (a)) {
    int i = StdRandom.uniform (a.length);
    if (a[i]) {
      a[i] = false;
      result++;
    }
  }
  return result;
}

Is it guaranteed to terminate?

01
02
03
04
05
06
07
08
09
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
package algs11;
import stdlib.*;
public class Hello {
  public static boolean someTrue (boolean[] a) {
    boolean result = false;
    int i = 0;
    while (i < a.length) {
      if (a[i]) {
        result = true;
        break;
      } 
      i++;
    }
    return result;
  }
  public static int f (boolean[] a) {
    int result = 0;
    while (someTrue (a)) {
      int i = StdRandom.uniform (a.length);
      Trace.draw ();
      if (a[i]) {
        a[i] = false;
        result++;
      }
    }
    return result;
  }
  public static void main (String[] args) {
    Trace.run ();
    f (new boolean[] {true, false, true, true, false});
    StdOut.println ("Hello");
  }
}

Previous pageContentsNext page