Please explain each line of code: Please explain each line of this code: Answer:
ID: 3833535 • Letter: P
Question
Please explain each line of code:
Please explain each line of this code:
Answer:
function k=how_much_new_snow()
k= round(0 + (10).*rand(1,1));
end
function k1=odd(val)
if mod(val,2)==0
k1=0;
else
k1=1;
end
end
% Initial value
count=0;
snow=[0 10 4];
sz=length(snow)
budget=100;
for day=1:1:sz
budget=budget+10;
amt=how_much_new_snow()
for i=1:sz
snow(i)=snow(i)+amt;
end
if amt>0
total=0;
for n=1:sz
total=total+snow(n);
end
budget=budget+0.2*total;
if odd(day)==1
for m=1:3
if odd(m)==1
snow(m)=0;
end
end
else
for m=1:sz
if odd(m)==0
snow(m)=0;
end
end
end
else
for m=1:sz
if snow(m)>0
snow(m)=snow(m)-1;
if budget>0
budget=budget-1;
else
count=count+1;
end
end
end
end
end
Explanation / Answer
%function how_much_new_snow..It randomly generates and returns amount of snow fell on a day.
function k=how_much_new_snow()
%K vlue is random num generatn betwenn 0 to 10
k= round(0 + (10).*rand(1,1));
end
%function to check odd day .this is used o check with days needs to be plowed
function k1=odd(val)
if mod(val,2)==0
k1=0;
else
k1=1;
end
end
% Initial value
count=0;
%declaring snow for 3 roads
snow=[0 10 4];
%sz contains he length f snow() i.e 3
sz=length(snow)
%initial budget
budget=100;
%everyday we are given $10 so initialise buget to 10 and increment on daily basis.loop for the 3 roads
for day=1:1:sz
budget=budget+10;
%for each day calculate how much snow is added using he function
amt=how_much_new_snow()
%add that amount to existing snow value
for i=1:sz
snow(i)=snow(i)+amt;
end
if amt>0
total=0;
%calculate the total budget by adding all the snow on raods values
for n=1:sz
total=total+snow(n);
end
%add 20% on emergency as amt>0 it means snowfall exists and increent budget value
budget=budget+0.2*total;
%if even day make the even numbers snowfall to 0 not to plough and same for odd days
if odd(day)==1
%as we have innitialsed only 3 roads checing for those 3
for m=1:3
if odd(m)==1
snow(m)=0;
end
end
else
%check odd days
for m=1:sz
if odd(m)==0
snow(m)=0;
end
end
end
else
%for each road to remove 1 inch deduct $1 and snowfall also to -1
for m=1:sz
if snow(m)>0
snow(m)=snow(m)-1;
if budget>0
budget=budget-1;
else
count=count+1;
end
end
end
end
end