STAGE 3 | The infinite monkey theorem states that a monkey hitting keys at rando
ID: 3915795 • Letter: S
Question
STAGE 3 | The infinite monkey theorem states that a monkey hitting keys at random on a typewriter keyboard for an infinite amount of time will almost surely type a given text, such as the complete works of William Shakespeare. In fact the monkey would almost surely type every possible finite text an infinite number of times. However, the probability of a universe full of monkeys typing a complete work such as Shakespeare's Hamlet is so tiny that the chance of it occurring during a period of time hundreds of thousands of orders of magnitude longer than the age of the universe is extremely low (but technically not zero).
Write a Java Program called “Lab14._02java” that check to see how long it takes to generate a given word (to save time, maximum word length 6)
Program Skeleton
import java.util.*;
public class Lab14_02 {
public static void main(String[] args) {
// TODO code application logic here
// input a word (max 6 characters)
Scanner in = new Scanner(System.in);
String word;
do {
System.out.println("Enter a word, max 6 chars");
word = in.nextLine();
} while (word.length() > 6);
long startTime = System.currentTimeMillis();
String s="";
// generate the initial String based on length of word
……
while ( !s.equals(word))
{
// Generate the next word by dropping first character and adding random char at end
}
long endTime = System.currentTimeMillis();
long time = (endTime - startTime)/1000;
System.out.println(time);
}
// generate a random lowercase character
public static char generate(){
}
}
Explanation / Answer
Please the code below with detailed inline comments.
CODE
==============
import java.util.*;
public class Lab14_02 {
public static void main(String[] args) {
// TODO code application logic here
// input a word (max 6 characters)
Scanner in = new Scanner(System.in);
String word;
do {
System.out.println("Enter a word, max 6 chars");
word = in.nextLine();
} while (word.length() > 6);
long startTime = System.currentTimeMillis();
String s="";
// generate the initial String based on length of word
for(int i=0; i<6; i++) {
s += generate();
}
while ( !s.equals(word))
{
// Generate the next word by dropping first character and adding random char at end
s += generate();
s = s.substring(1);
}
long endTime = System.currentTimeMillis();
long time = (endTime - startTime)/1000;
System.out.println(time);
}
// generate a random lowercase character
public static char generate(){
String letters = "abcdefghijklmnopqrstuvwxyz";
Random random = new Random();
return letters.charAt(random.nextInt(26));
}
}
Related Questions
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.