View Single Post
Hvorfor gir dette programmet 29,9% sjanse: (1 million tester, samme hver gang)

import java.util.*;

public class Fanger{


public static final int NR_CHANCES = 50;
public static final int NR_BOXES = 100;
public static final int NR_PRISONERS = 100;
public static int[] boxes = new int[NR_BOXES];


public static void main(String[] args){

//Initialiserer boxes,
randomizeboxes();


int successes = 0;
int nr_tests = 1000000;
for (int i = 0; i < nr_tests; i++){
if (allsurvives())
successes++;
randomizeboxes();
}

System.out.println("Overlevelsessjanse: " + (1.0*successes/nr_tests) );

}




//Returnerer true om alle fanger klarer det.
public static boolean allsurvives(){
for (int x = 0; x < NR_PRISONERS; x++){
if (!successfullcoice(x, x))//merkelig kall, ser det, men lettere se hva som gjøres
return false;
}
return true;
}


//returnerer true om én fange klarer det.
public static boolean successfullcoice(int startbox, int prisonnumber){
int choicesmade = 0;

while (choicesmade < NR_CHANCES){
int choice = select(startbox);
if (choice == prisonnumber)
return true;

choicesmade++;
startbox = choice;
}
return false;
}



public static int select(int boxnumber){
return boxes[boxnumber];
}


//Trekker tilfeldig lapp til hver box.
public static void randomizeboxes(){
for (int x = 0; x < NR_BOXES; x++){
boxes[x] = x;
}
//shuffle the array:
Random r = new Random();
for (int i = 0; i < boxes.length; i++) {
int newposition = r.nextInt(boxes.length);
int temp = boxes[newposition];
boxes[newposition] = boxes[i];
boxes[i] = temp;
}
}

}
Vis hele sitatet...