Once again, a brave hero is preparing for battle, but this time, s/he will be fi
ID: 3568863 • Letter: O
Question
Once again, a brave hero is preparing for battle, but this time, s/he will be fighting a particularly tricky enemy: a slime. What makes the slime so tricky? Every time the hero attacks the slime, it might split into TWO slimes, and the hero then has to kill BOTH slimes - each of which might split AGAIN when s/he tries to kill them! Your task for this question is to write a program that will determine how many slimes the hero will have to kill on average using the power of recursion.
Getting Started
Once again, this question will make use of random numbers, so you need to make the following preparations:
Task 1
Write a recursive function called killSlime(int killNumber). The function returns the total number of slimes that the hero actually killed while trying to kill the initial slime (note: a slime that "splits" has *not* been killed!). The function has a single integer parameter called 'killNumber.' This number indicates how hard the slime is to kill, and is used in the procedure below.
To determine whether the hero kills a slime, use the following procedure.
Explanation / Answer
#include <cstdlib>
#include <time.h>
#include<iostream>
using namespace std;
int killSlime(int killNumber)
{
int slimeKill = (rand() % 10) + 1 ; //random number generate from 1-10
if(slimeKill >= killNumber) //base condition if the random number generated is >= killNUmber then it gets killed, so it returns 1
return 1;
else
return killSlime(killNumber-1) + killSlime(killNumber-1) ; // else it divides int otwo with one less killNumber than before, so recursion is done twice
}
int main(int argc, char** argv) {
srand(time(0)); //seed data
int total = 0, max = 0;
for(int i=0; i<1000; i++) //loop to call the recursive function 1000 times
{
int kill = killSlime(10);
if(max < kill)
max = kill; //calculates max
total += kill; //calculates total for average
}
float average = (float)(total/1000); //finda average
cout<<"A slime appears! To battle, for great justice!! ";
cout<<"On average, with kill number 10, the hero must kill "<<average<<" slimes! ";
cout<<"The maximum number of slimes the hero had to kill was: "<<max;
return 0;
}
------------------------------------------------
OUTPUT
A slime appears! To battle, for great justice!!
On average, with kill number 10, the hero must kill 14 slimes!
The maximum number of slimes the hero had to kill was: 46
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.