What's the right transition equation of this problem? - algorithm

For every mouse, it takes two months for them to become mature after birth, then they are able to give birth to baby mouses. A mature mouse can give birth to 12 baby mouses every month. We have one mouse initially, and what's the total numebr of mouse after ten months?
My transition equation is F(n) = F(n-1) + 12 * F(n-2), but my classmate told me this is not right. So what's the right equation of this question?

Your transition equation needs to be a matrix (3x3) so that given 3 states as a vector (newborn, 1m old, 2m+ old) gives you new vector of new states after 1m. Logic to build such matrix is similar as your reasoning.
new_state = matrix * current_state
EDIT:
matrix that we build represents 3 linear equations.
# abbreviations
ns = new state
nb = newborn
1m = 1 month old
2m = 2 mounts old or more
cs = current state
mXX = matrix index
# 3 scalar questions from matrix eqution ->
# ns = matrix * cs
ns_nb = m00 * cs_nb + m01 * cs_1m + m02 * cs_2m
ns_1m = m10 * cs_nb + m11 * cs_1m + m12 * cs_2m
ns_2m = m20 * cs_nb + m21 * cs_1m + m22 * cs_2m
Now you need to figure out what m00 - m22 are based on your requrements

Enlightened by answer by Luka above, I figure out these coefficients
ns_nb = 12 * cs_2m + 12 * cs_1m
ns_1m = cs_nb
ns_2m = cs_2m + cs_1m

From the posts of Luka Rahne and KningTG,
I think the python code below will work fine for the problem using dynamic programming:
# Initial Conditions
new_born = 1
one_month_old = 0
mature_mouse = 0
n = 10 # Month upto which we want to find
i = 1
while(i<n):
# Finding updated new value
new_born_update = 12*(one_month_old+mature_mouse)
one_month_old_update = new_born
mature_mouse_update = one_month_old + mature_mouse
# Updating values
new_born,one_month_old,mature_mouse = new_born_update,one_month_old_update,mature_mouse_update
i = i + 1
# Calculating the total number of mouses for month n
Total_mouses = new_born+one_month_old+mature_mouse
# Printing total number of mouses
print(Total_mouses)

Related

How the property of modulous (A*B)%m = (A%m * B%m) %m is used to find the mod of very large numbers

I saw the property of mod where
(A*B)%m = (A%m * B%m) %m
And this property is used in the below algorithm to find the mod of very large numbers.
Get one variable to store the answer initialized to zero.
Scan the string from left to right,
every time multiply the answer by 10 and add the next number and take the modulo and store this as the new answer.
But I'm unable to understand this algorithm . How the property is connected to the algorithm here?
It will be helpful if used an example to understand the underneath math behind the algorithm , for example 12345%100
Using this algorithm, 23 % k is computed as
(2%k * 10 + 3)%k
((2%k * 10)%k + 3)%k // because (a+b)%k = (a%k + b)%k (1)
(((2%k)%k * 10%k)%k + 3)%k // because (a*b)%k = (a%k * b%k)%k (2)
((2%k * 10%k)%k + 3)%k // because (a%k)%k = a%k (trivial)
((2 * 10)%k + 3)%k // because (a%k * b%k)%k = (a*b)%k (2)
(2 * 10 + 3)%k // because (a%k + b)%k = (a+b)%k (1)
23%k
In other words, (a%k * p + b)%k = (a * p + b)%k thanks to that property (2). b is the last digit of a number in base p (p = 10 in your example), and a is the rest of the number (all the digits but the last).
In my example, a is just 2, but if you apply this recursively, you have your algorithm. The point is that a * p + b might be too big to handle, but a%k * p + b probably isn't.

Calculate cash flows given a target IRR

I apologize if the answer for this is somewhere already, I've been searching for a couple of hours now and I can't find what I'm looking for.
I'm building a simple financial calculator to calculate the cash flows given the target IRR. For example:
I have an asset worth $18,000,000 (which depreciates at $1,000,000/year)
I have a target IRR of 10% after 5 years
This means that the initial investment is $18,000,000, and in year 5, I will sell this asset for $13,000,000
To reach my target IRR of 10%, the annual cash flows have to be $2,618,875. Right now, I calculate this by hand in an Excel sheet through guess-and-check.
There's other variables and functionality, but they're not important for what I'm trying to do here. I've found plenty of libraries and functions that can calculate the IRR for a given number of cash flows, but nothing comes up when I try to get the cash flow for a given IRR.
At this point, I think the only solution is to basically run a loop to plug in the values, check to see if the IRR is higher or lower than the target IRR, and keep calculating the IRR until I get the cash flow that I want.
Is this the best way to approach this particular problem? Or is there a better way to tackle it that I'm missing? Help greatly appreciated!
Also, as an FYI, I'm building this in Ruby on Rails.
EDIT:
IRR Function:
NPV = -(I) + CF[1]/(1 + R)^1 + CF[2]/(1 + R)^2 + ... + CF[n]/(1 + R)^n
NPV = the Net Present Value (this value needs to be as close to 0 as possible)
I = Initial investment (in this example, $18,000,000)
CF = Cash Flow (this is the value I'm trying to calculate - it would end up being $2,618,875 if I calculated it by hand. In my financial calculator, all of the cash flows would be the same since I'm solving for them.)
R = Target rate of return (10%)
n = the year (so this example would end at 5)
I'm trying to calculate the Cash Flows to within a .005% margin of error, since the numbers we're working with are in the hundreds of millions.
Let
v0 = initial value
vn = value after n periods
n = number of periods
r = annual rate of return
y = required annual net income
The one period discount factor is:
j = 1/(1+r)
The present value of the investment is:
pv = - v0 + j*y + j^2*y + j^3*y +..+ j^n*y + j^n*vn
= - v0 + y*(j + j^2 + j^3 +..+ j^n) + j^n*vn
= - v0 + y*sn + j^n*vn
where
sn = j + j^2 + j^3 + j^4 +..+ j^n
We can calulate sn as follows:
sn = j + j^2 + j^3 + j^4 +..+ j^n
j*sn = j^2 + j^3 + j^4 +..+ j^n + j^(n+1)
sn -j*sn = j*(1 - j^n)
sn = j*(1 - j^n)/(1-j)
= (1 - j^n)/[(1+r)(r/(1+r)]
= (1 - j^n)/r
Set pv = 0 and solve for y:
y*sn = v0 - vn * j^n
y = (v0 - vn * j^n)/sn
= r * (v0 - vn * j^n)/(1 - j^n)
Our Ruby method:
def ann_ret(v0, vn, n, r)
j = 1/(1+r)
(r * (v0 - vn * j**n)/(1 - j**n)).round(2)
end
With annual compounding:
ann_ret(18000000, 13000000, 5, 0.1) # => 2618987.4
With semi-annual compounding:
2 * ann_ret(18000000, 13000000, 10, 0.05) # => 2595045.75
With daily compounding:
365 * ann_ret(18000000, 13000000, 5*365, 0.10/365) # => 2570881.20
These values differ slightly from the required annual return you calculate. You should be able to explain the difference by comparing present value formulae.
There's a module called Newton in Ruby... it uses the Newton Raphson method.
I've been using this module to implement the IRR function into this library:
https://github.com/Noverde/exonio
If you need the IRR, you can use like this:
Exonio.irr([-100, 39, 59, 55, 20]) # ==> 0.28095

implementing a simple big bang big crunch (BB-BC) in matlab

i want to implement a simple BB-BC in MATLAB but there is some problem.
here is the code to generate initial population:
pop = zeros(N,m);
for j = 1:m
% formula used to generate random number between a and b
% a + (b-a) .* rand(N,1)
pop(:,j) = const(j,1) + (const(j,2) - const(j,1)) .* rand(N,1);
end
const is a matrix (mx2) which holds constraints for control variables. m is number of control variables. random initial population is generated.
here is the code to compute center of mass in each iteration
sum = zeros(1,m);
sum_f = 0;
for i = 1:N
f = fitness(new_pop(i,:));
%keyboard
sum = sum + (1 / f) * new_pop(i,:);
%keyboard
sum_f = sum_f + 1/f;
%keyboard
end
CM = sum / sum_f;
new_pop holds newly generated population at each iteration, and is initialized with pop.
CM is a 1xm matrix.
fitness is a function to give fitness value for each particle in generation. lower the fitness, better the particle.
here is the code to generate new population in each iteration:
for i=1:N
new_pop(i,:) = CM + rand(1) * alpha1 / (n_itr+1) .* ( const(:,2)' - const(:,1)');
end
alpha1 is 0.9.
the problem is that i run the code for 100 iterations, but fitness just decreases and becomes negative. it shouldnt happen at all, because all particles are in search space and CM should be there too, but it goes way beyond the limits.
for example, if this is the limits (m=4):
const = [1 10;
1 9;
0 5;
1 4];
then running yields this CM:
57.6955 -2.7598 15.3098 20.8473
which is beyond all limits.
i tried limiting CM in my code, but then it just goes and sticks at all top boundaries, which in this example give CM=
10 9 5 4
i am confused. there is something wrong in my implementation or i have understood something wrong in BB-BC?

False Mirrors. can you help me to solve?

Here is the problem
BFG-9000 destroys three adjacent balconies per one shoot. (N-th balcony is adjacent to
the first one). After the shoot the survival monsters inflict damage to Leonid
(main hero of the novel) — one unit per monster. Further follows new shoot and so on
until all monsters
will perish. It is required to define the minimum amount of damage,
which can take Leonid.
For example :
N = 8
A[] = 4 5 6 5 4 5 6 5
answer : 33
4 * * * 4 5 6 5 - 24
4 * * * * * * 5 - 9
* * * * * * * * - 0
Can you help me to solve this problem? What is the complexity?
Problem can be solved with DP.
After first shot problem will not be circular anymore. Damage of monsters that left after attack can be calculated with DP. Lets NB is number of balconies.
Define D[n,m] for n<=m or m+4<=nas damage of monsters left on balconies b, n<=b<=m or m<=b<=n.
If n <= m < n+3 than D[n,m] = sum A[i] for n<=i<=m.
If m >= n+3 than D[n,m] =
min{ 2*D[n,i-1] + D[i,i+2] + 2*D[i+3,m] } for i in {n,...,m}.
If m < n than D[n,m] =
min{ 2*D[n,i-1] + D[i,i+2] + 2*D[i+3,m] } for i in {n,...,NB} U {1,...,m}.
Result is min{ D[i+3,NB+i-1] for i in {1,...,NB-2} }.
In third case and result indices are modulo NB.
This approach has complexity O(n^3).
It looks like the constraints of the problem are such that you can just brute force it . Basically
def go(hit):
res = 999
#base case, check if all items in hit are true.
for i in range(len(hit)):
if not hit[i]:
newhit = [x for x in hit]
newhit[i] = newhit[i-1] = newhit[(i+1)%len(hit)] = True;
damage = 0;
for j in range(len(hit)):
if not newhit[j]:
damage+=hit[j]
res = min(res, go(newhit)+damage)
You can also implement hit as a bit map and then memoize it to speed up the function.

shoot projectile (straight trajectory) at moving target in 3 dimensions

I already googled for the problem but only found either 2D solutions or formulas that didn't work for me (found this formula that looks nice: http://www.ogre3d.org/forums/viewtopic.php?f=10&t=55796 but seems not to be correct).
I have given:
Vec3 cannonPos;
Vec3 targetPos;
Vec3 targetVelocityVec;
float bulletSpeed;
what i'm looking for is time t such that
targetPos+t*targetVelocityVec
is the intersectionpoint where to aim the cannon to and shoot.
I'm looking for a simple, inexpensive formula for t (by simple i just mean not making many unnecessary vectorspace transformations and the like)
thanks!
The real problem is finding out where in space that the bullet can intersect the targets path. The bullet speed is constant, so in a certain amount of time it will travel the same distance regardless of the direction in which we fire it. This means that it's position after time t will always lie on a sphere. Here's an ugly illustration in 2d:
This sphere can be expressed mathematically as:
(x-x_b0)^2 + (y-y_b0)^2 + (z-z_b0)^2 = (bulletSpeed * t)^2 (eq 1)
x_b0, y_b0 and z_b0 denote the position of the cannon. You can find the time t by solving this equation for t using the equation provided in your question:
targetPos+t*targetVelocityVec (eq 2)
(eq 2) is a vector equation and can be decomposed into three separate equations:
x = x_t0 + t * v_x
y = y_t0 + t * v_y
z = z_t0 + t * v_z
These three equations can be inserted into (eq 1):
(x_t0 + t * v_x - x_b0)^2 + (y_t0 + t * v_y - y_b0)^2 + (z_t0 + t * v_z - z_b0)^2 = (bulletSpeed * t)^2
This equation contains only known variables and can be solved for t. By assigning the constant part of the quadratic subexpressions to constants we can simplify the calculation:
c_1 = x_t0 - x_b0
c_2 = y_t0 - y_b0
c_3 = z_t0 - z_b0
(v_b = bulletSpeed)
(t * v_x + c_1)^2 + (t * v_y + c_2)^2 + (t * v_z + c_3)^2 = (v_b * t)^2
Rearrange it as a standard quadratic equation:
(v_x^2+v_y^2+v_z^2-v_b^2)t^2 + 2*(v_x*c_1+v_y*c_2+v_z*c_3)t + (c_1^2+c_2^2+c_3^2) = 0
This is easily solvable using the standard formula. It can result in zero, one or two solutions. Zero solutions (not counting complex solutions) means that there's no possible way for the bullet to reach the target. One solution will probably happen very rarely, when the target trajectory intersects with the very edge of the sphere. Two solutions will be the most common scenario. A negative solution means that you can't hit the target, since you would need to fire the bullet into the past. These are all conditions you'll have to check for.
When you've solved the equation you can find the position of t by putting it back into (eq 2). In pseudo code:
# setup all needed variables
c_1 = x_t0 - x_b0
c_2 = y_t0 - y_b0
c_3 = z_t0 - z_b0
v_b = bulletSpeed
# ... and so on
a = v_x^2+v_y^2+v_z^2-v_b^2
b = 2*(v_x*c_1+v_y*c_2+v_z*c_3)
c = c_1^2+c_2^2+c_3^2
if b^2 < 4*a*c:
# no real solutions
raise error
p = -b/(2*a)
q = sqrt(b^2 - 4*a*c)/(2*a)
t1 = p-q
t2 = p+q
if t1 < 0 and t2 < 0:
# no positive solutions, all possible trajectories are in the past
raise error
# we want to hit it at the earliest possible time
if t1 > t2: t = t2
else: t = t1
# calculate point of collision
x = x_t0 + t * v_x
y = y_t0 + t * v_y
z = z_t0 + t * v_z

Resources