How to resolve the algorithm 100 prisoners step by step in the Processing programming language

Published on 12 May 2024 09:40 PM

How to resolve the algorithm 100 prisoners step by step in the Processing programming language

Table of Contents

Problem Statement

Show and compare the computed probabilities of success for the two strategies, here, on this page.

Let's start with the solution:

Step by Step solution about How to resolve the algorithm 100 prisoners step by step in the Processing programming language

Source code in the processing programming language

IntList drawers = new IntList();
int trials = 100000;
int succes_count;

void setup() {
  for (int i = 0; i < 100; i++) {
    drawers.append(i);
  }
  println(trials + " trials\n");

  //Random strategy
  println("Random strategy");
  succes_count = trials;
  for (int i = 0; i < trials; i++) {
    drawers.shuffle();
    for (int prisoner = 0; prisoner < 100; prisoner++) {
      boolean found = false;
      for (int attempt = 0; attempt < 50; attempt++) {
        if (drawers.get(int(random(drawers.size()))) == prisoner) {
          found = true;
          break;
        }
      }
      if (!found) {
        succes_count--;
        break;
      }
    }
  }
  println(" Succeses: " + succes_count);
  println(" Succes rate: " + 100.0 * succes_count / trials + "%\n");

  //Optimal strategy
  println("Optimal strategy");
  succes_count = trials;
  for (int i = 0; i < trials; i++) {
    drawers.shuffle();
    for (int prisoner = 0; prisoner < 100; prisoner++) {
      boolean found = false;
      int next = prisoner;
      for (int attempt = 0; attempt < 50; attempt++) {
        next = drawers.get(next);
        if (next == prisoner) {
          found = true;
          break;
        }
      }
      if (!found) {
        succes_count--;
        break;
      }
    }
  }
  println(" Succeses: " + succes_count);
  print(" Succes rate: " + 100.0 * succes_count / trials + "%");
}

  

You may also check:How to resolve the algorithm Currying step by step in the Go programming language
You may also check:How to resolve the algorithm Dynamic variable names step by step in the AutoHotkey programming language
You may also check:How to resolve the algorithm Literals/Floating point step by step in the Ruby programming language
You may also check:How to resolve the algorithm Hailstone sequence step by step in the Scilab programming language
You may also check:How to resolve the algorithm Hello world/Web server step by step in the Rust programming language