MEG-DM L08


# Estimate mean computing time for guessing a random number between 0 and 1E6.
# Copyright (C) 2013 Lars Fink
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
#
# Author: Lars Fink
# Version: “2013-10-23″

library(microbenchmark)

numberguess.dac <- function() {
  lower_bound <- 1
  upper_bound <- 1000000
  wanted_number <- sample(lower_bound:upper_bound, size=1)}

i<-0
a<-500000
b<-250000
while a!=wanted_number {
  
  i=i+1
  
  if a<wanted_number{a<-a-b}
  
  else {a<-a+b}
  
  b<-b/2}
print “iterationnumber:”,i

numberguess.stupid <- function() {
  lower_bound <- 1
  upper_bound <- 1000000
  wanted_number <- sample(lower_bound:upper_bound, size=1)}

d<-0
i<-0

while d!=wanted_number {
  d=d+1,i=i+1}

print “iterationnumber:”,i

microbenchmark(numberguess.dac(), times=100)
microbenchmark(numberguess.stupid(), times=100)

One thought on “MEG-DM L08

Leave a Reply