Number of ways to sit in a 2XN grid - recursion

I had this question in an interview but I was not able to solve it.
We have a grid of 2 rows and n columns. We have to find the number of ways to sit M men and W women given no men can sit adjacent or in front of each other.
I thought of solving it by Dynamic Programming but I'm not sure how to get the recurrence relation.
I know that if I am at (0,i), I can go to (1,i+1) but I don't know how to keep track of counts of men and women so far. Can anybody help me with the recurrence relation or states of dp?

Recurrence relation
Here is one recurrence relation I could thing of.
Let's call n_ways(N, W, M, k) the number of ways to seat:
W women
and M men
in the remaining N columns
knowing there was k men in the previous column. k can only take values 0 and 1.
n_ways(N, 0, 0, k) = 1
n_ways(N, W, M, k) = 0 if M > N or W+M > 2*N
n_ways(N, W, 0, k) = ((2*N) choose W)
n_ways(N, 0, M, 0) = 2 * (N choose M)
n_ways(N, 0, M, 1) = (N choose M)
n_ways(N, W, M, 0)
= n_ways(N-1, W, M, 0) // put nobody in first column
+ 2 * n_ways(N-1, W-1, M, 0) // put 1 woman in first column
+ n_ways(N-1, W-2, M, 0) // put 2 women in first column
+ 2 * n_ways(N-1, W-1, M-1, 1) // put 1 woman & 1 man in first column
+ 2 * n_ways(N-1, W, M-1, 1) // put 1 man in first column
n_ways(N, W, M, 1)
= n_ways(N-1, W, M, 0) // put nobody in first column
+ 2 * n_ways(N-1, W-1, M, 0) // put 1 woman in first column
+ n_ways(N-1, W-2, M, 0) // put 2 women in first column
+ n_ways(N-1, W-1, M-1, 1) // put 1 woman & 1 man in first column
+ n_ways(N-1, W, M-1, 1) // put 1 man in first column
Testing with python
Since I'm too lazy to implement dynamic programming myself, I instead opted for caching using python's functools.cache.
I implemented the recurrence relation above as a cached recursive function, and got the following results:
Number of ways to seat w women and m men in n columns:
n, w, m --> ways
0, 0, 0 --> 1
0, 0, 1 --> 0
0, 1, 0 --> 0
1, 2, 0 --> 1
1, 0, 2 --> 0
1, 1, 1 --> 2
2, 2, 2 --> 2
3, 3, 3 --> 2
4, 6, 2 --> 18
10, 15, 5 --> 2364
10, 10, 10 --> 2
Here is the python code:
from functools import cache
from math import comb
#cache
def n_ways(n, w, m, k):
if w == m == 0:
return 1
elif m > n or w + m > 2 * n:
return 0
elif m == 0:
return comb(2*n, w)
elif w == 0:
return (2-k) * comb(n, m)
else:
r_0, r_w, r_ww, r_wm, r_m = (
n_ways(n-1, w, m, 0),
n_ways(n-1, w-1, m, 0),
n_ways(n-1, w-2, m, 0) if w > 1 else 0,
n_ways(n-1, w-1, m-1, 1),
n_ways(n-1, w, m-1, 1)
)
return (r_0 + r_w + r_w + r_ww + r_wm + r_m) + (1-k) * (r_wm + r_m)
if __name__=='__main__':
print(f'Number of ways to seat w women and m men in n columns:')
print(f' n, w, m --> ways')
for w, m in [(0, 0), (0, 1), (1, 0), (2, 0), (0, 2),
(1, 1), (2, 2), (3, 3), (6, 2), (15, 5),
(10, 10)]:
n = (w + m) // 2
print(f'{n:2d}, {w:2d}, {m:2d} --> ', end='')
print(n_ways(n, w, m, 0))

Related

Counting how many times an equation is true for items from an array

I have an array containing integers from 1 to 1000. I'm trying to count how many times this equation is true A + B + C + D = E where A <= B <= C <= D and A, B, C, D, E are all items from the array. Could you guys suggest any solutions?
The array contains all integers from 1 to 1000, so 1, 2, 3, 4, .. , 999, 1000. The numbers A - D can be the same number from the array.
You need to calculate number of integer partitions for every value E in range 1..1000 into 4 parts.
Python function countparts to calculate number of such partitions.
def cp(n, k, m):
if k == 0:
if n == 0:
return 1
else:
return 0
res = 0
for i in range(min(n + 1, m + 1)):
res += cp(n - i, k - 1, i)
return res
def countparts(n, k):
return cp(n - k, k, n - k + 1)
print(countparts(8, 4))
>> 5 (1115, 1124, 1133, 1223, 2222)
But it works slowly for large arguments.
Also at this page I found formula to get needed values fast:
P(i) = round((i**3 + 3*i*i - 9*i*(i % 2))/144)

mathematica code that is not working according to wanted expression

enter image description here
I failed to do the following expression and make it give accurate results if any one can help me I will be glade. I attached my expression in a pic "want this" and my trial as "my trial". the correct answer must equal 0.119 when a=1, b=10, m=3, n=6. thanks a lot in advance.
a = 1
b = 10
m = 3
n = 6
a^1 b^n (Sum[
Sum[Sum[Sum[(-1)^(k + v - n + m + 1)
If[k == 0, 1,
SeriesCoefficient[Series[(-Log[1 - x])^k, {x, 0, 30}],
p + k]] If[n - k - 2 == 0, 1,
SeriesCoefficient[
Series[(-Log[1 - x])^(n - k - 2), {x, 0, 30}],
q + (n - k - 2)]]
Binomial[n - m - 1, k] Binomial[b - 1,
v] (-PolyGamma[0, -1 + 1/a - k + n + q] +
PolyGamma[0, 2/a + n + p + q + v])/(a (1 + k + p + v) +
1), {q, 0, 30 - (n - k - 2)}], {p, 0, 30 - k}], {v, 0,
b - 1}], {k, 0, n - m - 1}])/((m - 1)! (n - m - 1)!)
I found the solution for the problem. the problem was when the value of k was 0 the coefficient will not equal 1 but the whole expression must be found from the start for a value of k that will start from 1 and an expression when the value of k is 0. yet I failed to solve it using MATHEMATICA but by doing the above I succeed to get the correct result. thank you all for your precious time and opinions.

How to approach this type of problem in permutation and combination?

Altitudes
Alice and Bob took a journey to the mountains. They have been climbing
up and down for N days and came home extremely tired.
Alice only remembers that they started their journey at an altitude of
H1 meters and they finished their wandering at an alitude of H2
meters. Bob only remembers that every day they changed their altitude
by A, B, or C meters. If their altitude on the ith day was x,
then their altitude on day i + 1 can be x + A, x + B, or x + C.
Now, Bob wonders in how many ways they could complete their journey.
Two journeys are considered different if and only if there exist a day
when the altitude that Alice and Bob covered that day during the first
journey differs from the altitude Alice and Bob covered that day during
the second journey.
Bob asks Alice to tell her the number of ways to complete the journey.
Bob needs your help to solve this problem.
Input format
The first and only line contains 6 integers N, H1, H2, A, B, C that
represents the number of days Alice and Bob have been wandering,
altitude on which they started their journey, altitude on which they
finished their journey, and three possible altitude changes,
respectively.
Output format
Print the answer modulo 10**9 + 7.
Constraints
1 <= N <= 10**5
-10**9 <= H1, H2 <= 10**9
-10**9 <= A, B, C <= 10**9
Sample Input
2 0 0 1 0 -1
Sample Output
3
Explanation
There are only 3 possible journeys-- (0, 0), (1, -1), (-1, 1).
Note
This problem comes originally from a hackerearth competition, now closed. The explanation for the sample input and output has been corrected.
Here is my solution in Python 3.
The question can be simplified from its 6 input parameters to only 4 parameters. There is no need for the beginning and ending altitudes--the difference of the two is enough. Also, we can change the daily altitude changes A, B, and C and get the same answer if we make a corresponding change to the total altitude change. For example, if we add 1 to each of A, B, and C, we could add N to the altitude change: 1 additional meter each day over N days means N additional meters total. We can "normalize" our daily altitude changes by sorting them so A is the smallest, then subtract A from each of the altitude changes and subtract N * A from the total altitude change. This means we now need to add a bunch of 0's and two other values (let's call them D and E). D is not larger than E.
We now have an easier problem: take N values, each of which is 0, D, or E, so they sum to a particular total (let's say H). This is the same at using up to N numbers equaling D or E, with the rest zeros.
We can use mathematics, in particular Bezout's identity, to see if this is possible. Some more mathematics can find all the ways of doing this. Once we know how many 0's, D's, and E's, we can use multinomial coefficients to find how many ways these values can be rearranged. Total all these up and we have the answer.
This code finds the total number of ways to complete the journey, and takes it modulo 10**9 + 7 only at the very end. This is possible since Python uses large integers. The largest result I found in my testing is for the input values 100000 0 100000 0 1 2 which results in a number with 47,710 digits before taking the modulus. This takes a little over 8 seconds on my machine.
This code is a little longer than necessary, since I made some of the routines more general than necessary for this problem. I did this so I can use them in other problems. I used many comments for clarity.
# Combinatorial routines -----------------------------------------------
def comb(n, k):
"""Compute the number of ways to choose k elements out of a pile of
n, ignoring the order of the elements. This is also called
combinations, or the binomial coefficient of n over k.
"""
if k < 0 or k > n:
return 0
result = 1
for i in range(min(k, n - k)):
result = result * (n - i) // (i + 1)
return result
def multcoeff(*args):
"""Return the multinomial coefficient
(n1 + n2 + ...)! / n1! / n2! / ..."""
if not args: # no parameters
return 1
# Find and store the index of the largest parameter so we can skip
# it (for efficiency)
skipndx = args.index(max(args))
newargs = args[:skipndx] + args[skipndx + 1:]
result = 1
num = args[skipndx] + 1 # a factor in the numerator
for n in newargs:
for den in range(1, n + 1): # a factor in the denominator
result = result * num // den
num += 1
return result
def new_multcoeff(prev_multcoeff, x, y, z, ag, bg):
"""Given a multinomial coefficient prev_multcoeff =
multcoeff(x-bg, y+ag, z+(bg-ag)), calculate multcoeff(x, y, z)).
NOTES: 1. This uses bg multiplications and bg divisions,
faster than doing multcoeff from scratch.
"""
result = prev_multcoeff
for d in range(1, ag + 1):
result *= y + d
for d in range(1, bg - ag + 1):
result *= z + d
for d in range(bg):
result //= x - d
return result
# Number theory routines -----------------------------------------------
def bezout(a, b):
"""For integers a and b, find an integral solution to
a*x + b*y = gcd(a, b).
RETURNS: (x, y, gcd)
NOTES: 1. This routine uses the convergents of the continued
fraction expansion of b / a, so it will be slightly
faster if a <= b, i.e. the parameters are sorted.
2. This routine ensures the gcd is nonnegative.
3. If a and/or b is zero, the corresponding x or y
will also be zero.
4. This routine is named after Bezout's identity, which
guarantees the existences of the solution x, y.
"""
if not a:
return (0, (b > 0) - (b < 0), abs(b)) # 2nd is sign(b)
p1, p = 0, 1 # numerators of the two previous convergents
q1, q = 1, 0 # denominators of the two previous convergents
negate_y = True # flag if negate y=q (True) or x=p (False)
quotient, remainder = divmod(b, a)
while remainder:
b, a = a, remainder
p, p1 = p * quotient + p1, p
q, q1 = q * quotient + q1, q
negate_y = not negate_y
quotient, remainder = divmod(b, a)
if a < 0:
p, q, a = -p, -q, -a # ensure the gcd is nonnegative
return (p, -q, a) if negate_y else (-p, q, a)
def byzantine_bball(a, b, s):
"""For nonnegative integers a, b, s, return information about
integer solutions x, y to a*x + b*y = s. This is
equivalent to finding a multiset containing only a and b that
sums to s. The name comes from getting a given basketball score
given scores for shots and free throws in a hypothetical game of
"byzantine basketball."
RETURNS: None if there is no solution, or an 8-tuple containing
x the smallest possible nonnegative integer value of
x.
y the value of y corresponding to the smallest
possible integral value of x. If this is negative,
there is no solution for nonnegative x, y.
g the greatest common divisor (gcd) of a, b.
u the found solution to a*u + b*v = g
v " "
ag a // g, or zero if g=0
bg b // g, or zero if g=0
sg s // g, or zero if g=0
NOTES: 1. If a and b are not both zero and one solution x, y is
returned, then all integer solutions are given by
x + t * bg, y - t * ag for any integer t.
2. This routine is slightly optimized for a <= b. In that
case, the solution returned also has the smallest sum
x + y among positive integer solutions.
"""
# Handle edge cases of zero parameter(s).
if 0 == a == b: # the only score possible from 0, 0 is 0
return (0, 0, 0, 0, 0, 0, 0, 0) if s == 0 else None
if a == 0:
sb = s // b
return (0, sb, b, 0, 1, 0, 1, sb) if s % b == 0 else None
if b == 0:
sa = s // a
return (sa, 0, a, 1, 0, 1, 0, sa) if s % a == 0 else None
# Find if the score is possible, ignoring the signs of x and y.
u, v, g = bezout(a, b)
if s % g:
return None # only multiples of the gcd are possible scores
# Find one way to get the score, ignoring the signs of x and y.
ag, bg, sg = a // g, b // g, s // g # we now have ag*u + bg*v = 1
x, y = sg * u, sg * v # we now have a*x + b*y = s
# Find the solution where x is nonnegative and as small as possible.
t = x // bg # Python rounds toward minus infinity--what we want
x, y = x - t * bg, y + t * ag
# Return the information
return (x, y, g, u, v, ag, bg, sg)
# Routines for this puzzle ---------------------------------------------
def altitude_reduced(n, h, d, e):
"""Return the number of distinct n-tuples containing only the
values 0, d, and e that sum to h. Assume that all these
numbers are integers and that 0 <= d <= e.
"""
# Handle some impossible special cases
if n < 0 or h < 0:
return 0
# Handle some other simple cases with zero values
if n == 0:
return 0 if h else 1
if 0 == d == e: # all step values are zero
return 0 if h else 1
if 0 == d or d == e: # e is the only non-zero step value
# If possible, return # of tuples with proper # of e's, the rest 0's
return 0 if h % e else comb(n, h // e)
# Handle the main case 0 < d < e
# --Try to get the solution with the fewest possible non-zero days:
# x d's and y e's and the rest zeros: all solutions are given by
# x + t * bg, y - t * ag
solutions_info = byzantine_bball(d, e, h)
if not solutions_info:
return 0 # no way at all to get h from d, e
x, y, _, _, _, ag, bg, _ = solutions_info
# --Loop over all solutions with nonnegative x, y, small enough x + y
result = 0
while y >= 0 and x + y <= n: # at most n non-zero days
# Find multcoeff(x, y, n - x - y), in a faster way
if result == 0: # 1st time through loop: no prev coeff available
amultcoeff = multcoeff(x, y, n - x - y)
else: # use previous multinomial coefficient
amultcoeff = new_multcoeff(amultcoeff, x, y, n - x - y, ag, bg)
result += amultcoeff
x, y = x + bg, y - ag # x+y increases by bg-ag >= 0
return result
def altitudes(input_str=None):
# Get the input
if input_str is None:
input_str = input('Numbers N H1 H2 A B C? ')
# input_str = '100000 0 100000 0 1 2' # replace with prev line for input
n, h1, h2, a, b, c = map(int, input_str.strip().split())
# Reduce the number of parameters by normalizing the values
h_diff = h2 - h1 # net altitude change
a, b, c = sorted((a, b, c)) # a is now the smallest
h, d, e = h_diff - n * a, b - a, c - a # reduce a to zero
# Solve the reduced problem
print(altitude_reduced(n, h, d, e) % (10**9 + 7))
if __name__ == '__main__':
altitudes()
Here are some of my test routines for the main problem. These are suitable for pytest.
# Testing, some with pytest ---------------------------------------------------
import itertools # for testing
import collections # for testing
def brute(n, h, d, e):
"""Do alt_reduced with brute force."""
return sum(1 for v in itertools.product({0, d, e}, repeat=n)
if sum(v) == h)
def brute_count(n, d, e):
"""Count achieved heights with brute force."""
if n < 0:
return collections.Counter()
return collections.Counter(
sum(v) for v in itertools.product({0, d, e}, repeat=n)
)
def test_impossible():
assert altitude_reduced(0, 6, 1, 2) == 0
assert altitude_reduced(-1, 6, 1, 2) == 0
assert altitude_reduced(3, -1, 1, 2) == 0
def test_simple():
assert altitude_reduced(1, 0, 0, 0) == 1
assert altitude_reduced(1, 1, 0, 0) == 0
assert altitude_reduced(1, -1, 0, 0) == 0
assert altitude_reduced(1, 1, 0, 1) == 1
assert altitude_reduced(1, 1, 1, 1) == 1
assert altitude_reduced(1, 2, 0, 1) == 0
assert altitude_reduced(1, 2, 1, 1) == 0
assert altitude_reduced(2, 4, 0, 3) == 0
assert altitude_reduced(2, 4, 3, 3) == 0
assert altitude_reduced(2, 4, 0, 2) == 1
assert altitude_reduced(2, 4, 2, 2) == 1
assert altitude_reduced(3, 4, 0, 2) == 3
assert altitude_reduced(3, 4, 2, 2) == 3
assert altitude_reduced(4, 4, 0, 2) == 6
assert altitude_reduced(4, 4, 2, 2) == 6
assert altitude_reduced(2, 6, 0, 2) == 0
assert altitude_reduced(2, 6, 2, 2) == 0
def test_main():
N = 12
maxcnt = 0
for n in range(-1, N):
for d in range(N): # must have 0 <= d
for e in range(d, N): # must have d <= e
counts = brute_count(n, d, e)
for h, cnt in counts.items():
if cnt == 25653:
print(n, h, d, e, cnt)
maxcnt = max(maxcnt, cnt)
assert cnt == altitude_reduced(n, h, d, e)
print(maxcnt) # got 25653 for N = 12, (n, h, d, e) = (11, 11, 1, 2) etc.

Non Decreasing Number Combinations (Interval)

So my problem is the following:
Given a number X of size and an A (1st number), B(Last number) interval, I have to find the number of all different kind of non decreasing combinations (increasing or null combinations) that I can build.
Example:
Input: "2 9 11"
X = 2 | A = 9 | B = 11
Output: 8
Possible Combinations ->
[9],[9,9],[9,10],[9,11],[10,10],[10,11],[11,11],[10],[11].
Now, If it was the same input, but with a different X, line X = 4, this would change a lot...
[9],[9,9],[9,9,9],[9,9,9,9],[9,9,9,10],[9,9,9,11],[9,9,10,10]...
Your problem can be reformulated to simplify to just two parameters
X and N = B - A + 1 to give you sequences starting with 0 instead of A.
If you wanted exactly X numbers in each item, it is simple combination with repetition and the equation for that would be
x_of_n = (N + X - 1)! / ((N - 1)! * X!)
so for your first example it would be
X = 2
N = 11 - 9 + 1 = 3
x_of_n = 4! / (2! * 2!) = 4*3*2 / 2*2 = 6
to this you need to add the same with X = 1 to get x_of_n = 3, so you get the required total 9.
I am not aware of simple equation for the required output, but when you expand all the equations to one sum, there is a nice recursive sequence, where you compute next (N,X) from (N,X-1) and sum all the elements:
S[0] = N
S[1] = S[0] * (N + 1) / 2
S[2] = S[1] * (N + 2) / 3
...
S[X-1] = S[X-2] * (N + X - 1) / X
so for the second example you give we have
X = 4, N = 3
S[0] = 3
S[1] = 3 * 4 / 2 = 6
S[2] = 6 * 5 / 3 = 10
S[3] = 10 * 6 / 4 = 15
output = sum(S) = 3 + 6 + 10 + 15 = 34
so you can try the code here:
function count(x, a, b) {
var i,
n = b - a + 1,
s = 1,
total = 0;
for (i = 0; i < x; i += 1) {
s *= (n + i) / (i + 1); // beware rounding!
total += s;
}
return total;
}
console.log(count(2, 9, 11)); // 9
console.log(count(4, 9, 11)); // 34
Update: If you use a language with int types (JS has only double),
you need to use s = s * (n + i) / (i + 1) instead of *= operator to avoid temporary fractional number and subsequent rounding problems.
Update 2: For a more functional version, you can use a recursive definition
function count(x, n) {
return n < 1 || x < 1 ? 0 : 1 + count(n - 1, x) + count(n, x - 1);
}
where n = b - a + 1

Calculate xyz position from given index

I wan't to calculate an xyz position from a given index.
I'm close but not there yet.
Can someone help me, I think only my z is wrong.
int w = 25;
int h = 25;
int d = 25;
int max = w*h*d;
for(int i = 0; i < max; i++) {
int x = i % w;
int y = ((i - x) / w)/d;
int z = ((i - y) / w) / d ;
println(x, y, z);
}
Let N(i) = {0, 1, ..., i - 1}.
A way to map 1-D to 2-D
You can map from N(AB) to N(A) × N(B) in the following way.
k &mapsto; (k / B, k % B)
k is the 1-D index, and (k / B, k % B) is the corresponding 2-D index.
Example
For example, suppose you want to map from {0, 1, 2, 3, 4, 5} to {0, 1, 2} × {0, 1}.
Then A = 3 and B = 2 and you get the following mapping.
k &mapsto; (x, y)
0 &mapsto; (0, 0)
1 &mapsto; (0, 1)
2 &mapsto; (1, 0)
3 &mapsto; (1, 1)
4 &mapsto; (2, 0)
5 &mapsto; (2, 1)
A way to map 1-D to 3-D using composition
Now if you want to map from N(ABC) to N(A) × N(B) × N(C), you can do so by using the above mapping twice: once to map from N(ABC) to N(A) × N(BC) then again to map from N(BC) to N(B) × N(C).
// Input: k in N(ABC)
// Output: (x, y, z) in N(A) x N(B) x N(C)
// N(ABC) -> N(A) x N(BC)
x = k / (B * C) // x in N(A)
w = k % (B * C) // w in N(BC)
// N(BC) -> N(B) x N(C)
y = w / C // y in N(B)
z = w % C // z in N(C)
Example
For A = B = C = 2, this will give you the following mapping.
k &mapsto; (x, y, z)
0 &mapsto; (0, 0, 0)
1 &mapsto; (0, 0, 1)
2 &mapsto; (0, 1, 0)
3 &mapsto; (0, 1, 1)
4 &mapsto; (1, 0, 0)
5 &mapsto; (1, 0, 1)
6 &mapsto; (1, 1, 0)
7 &mapsto; (1, 1, 1)

Resources