1. Ask the user how many times you want to run the algorithm. 2. Then choose a w
ID: 3557310 • Letter: 1
Question
1. Ask the user how many times you want to run the algorithm. 2. Then choose a word at random from the array of Strings as the target (Use the integer random number generator). 3 Then set up a for loop to run the algorithm the correct number of times by using the sequential algorithm. 4. Before the for loop, place the following code to get time in nanoseconds: long start = System.nanoTime(); 5. After the for loop, place the following code to get the elapsed time: long diff = System.nanoTime()-start; double time = diff/1000000000.0; 6. Print your result 10 timesExplanation / Answer
import java.util.*;
class seqAlgo{
public static void main(String args[]){
int n = 12;
String strings[] = {"Write", "a", "program", "to", "empirically", "find", "the", "runtime", "for", "the", "sequential", "algorithm"};
Scanner scan = new Scanner(System.in);
Long no = scan.nextLong();
Random rn = new Random();
int i = rn.nextInt() % n;
long start = System.nanoTime();
int loop =0;
for(loop=0;loop<10;loop++){
for(int c=0;c<no;c++){
String temp = strings[i];
}
long diff = System.nanoTime()-start;
double time = diff/1000000000.0;
System.out.println((loop+1)+". "+ time);
}
}
}
Related Questions
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.