java - Calculating average in a TestLuck (Probability) Program -
i'm student, trying write program tests probability. it's called testluck it's supposed generate user determined amount of intarraylogs(adt's) populated random values. program supposed calculate how many values generated before there match first value.
actual problem: "create application testluck; have user enter upper limit of random integer range (the book says 10,000, should test 365) number of times run test. compute , output average."
this came with, i'm not getting correct results reason, tested methods use , seem work right, think it's how i'm keeping track of counter.
for(int k=0; k<numtests; k++) { for(int i=0; i<upperlimit; i++) { arrlog.insert(n); n = rand.nextint(upperlimit); if(arrlog.contains(arrlog.getelement(0))) { totalcount += i; break; } if(i == upperlimit-1) totalcount +=i; } system.out.println("total count: " + totalcount); arrlog.clear(); } testaverage = totalcount/numtests; system.out.println("average tests before match: " + testaverage); contains method:
// returns true if element in intlog, // otherwise returns false. public boolean contains(int element) { int location = 0; int counter = 0; while (location <= lastindex) { if (element == log[location]) { // if match counter++; location++; if(counter == 2) return true; } else location++; } return false; }
you don't need contains() method, take more time compute simple comparison.
the question how many numbers have generated before matching first number, need take account if includes first number. eg. {1,2,3,4,1} count = 5, or {1,2,3,4,1} count = 4. either way, wont affect logic on answer:
if re-arrange method work faster.
for(int k=0; k<numtests; k++){ for(int i=0; i<upperlimit; i++){ arrlog.insert(n); if(arrlog.getelement(0) == n && != 0){// != 0 prevent counting match on first iteration totalcount += i;//totalcount += i+1 if counting first number break; } n = rand.nextint(upperlimit); } system.out.println("total count: " + totalcount); arrlog.clear(); } testaverage = totalcount/numtests; system.out.println("average tests before match: " + testaverage); if required use contains() method let me know on comments , i'll edit answer.
i suggest not using storage data structure, in case adt's intarraylog (again, dont know if required use adt part of course); program run faster:
int firstnum; for(int k=0; k<numtests; k++){ firstnum = rand.nextint(upperlimit); for(int i=1; i<upperlimit; i++){//notice starts in 1 n = rand.nextint(upperlimit); if(firstnum == n){ totalcount += i;//totalcount += i+1 if counting first number break; } } system.out.println("total count: " + totalcount); arrlog.clear(); } testaverage = totalcount/numtests; system.out.println("average tests before match: " + testaverage);
Comments
Post a Comment