For what cases will this logic of this code fail? - c

In a coding site I came across a question which seem to be very easy. But when I implement a solution it gives me wrong answers for the hidden test cases. I tried to find for what cases it failed but I just couldn't get any.
The question goes as follows
Construct an N×M matrix with entries having positive integers such that
If M>1, ith row is strictly increasing from left to right with a fixed common difference di
for all 1≤i≤N.
If N>1, jth column is strictly increasing from top to bottom with a fixed common difference cj
for all 1≤j≤M.
All the common differences should be distinct.
In the case of multiple answers, find an arrangement that minimizes the maximum element of the
matrix.
The code with the logic
#include<stdio.h>
#include<stdlib.h>
int main(){
int t=0,n=0,m=0,d=0;
scanf("%d",&t);
while(t--){
scanf("%d%d",&n,&m);
if(n>=m){
d=2;
for(int i=0;i<n;i++){
for(int j=0;j<m;j++){
printf("%d ",(i+1) + j*d);
}
d+=2;
printf("\n");
}
}
else{
d=1;
for(int i=0;i<n;i++){
for(int j=0;j<m;j++){
printf("%d ",(2*i+1) + j*d);
}
d+=2;
printf("\n");
}
}
}
return 0;
}
Sample input
3
3 3
1 2
1 1
Sample Output
1 2 3
3 6 9
5 10 15
1 2
1
Simple logic I tried was, check if the rows are more or the columns, whichever is more increment that by even number C.D (from 2,4,6....) and the other in odd number C.D(from 1,3,5...)
For example: for 2X3
The matrix will be
1 3
2 6
3 9
This logic seems to be correct and while discussing with my friends even they say its right. But I get wrong answers while submitting to the hidden cases.
What logic error might have I done? Could you give me a example for which this code will fail?

The matrix shown in the question for the 2×3 case is:
1 3
2 6
3 9
However, a better solution is:
1 4
2 6
3 8
We see this satisfies the constraints:
Each row and each column is strictly increasing.
Each row has a fixed difference: 3, 4, and 5.
Each column has a fixed difference: 1 and 2.
All those differences are distinct.
A general solution follows.
Let the matrix be Ai, j. It is clear A0, 0 should be 1. Let A0, 1, A1, 0, and A1, 1 be 1+a, 1+b, and 1+c, respectively. Then simple algebra and induction shows that Ai, j is 1 + (1−i)ja + i(1−j)b + ijc.
The common difference in column j is b+j(c−a−b), and the common difference is row i is a+i(c−a−b). These form two arithmetic series with the same step size, c−a−b, so they do not intersect only if they either interleave (for example, c−a−b could be 2 and one of a or b can be odd while the other is even) or one series is entirely less than the other (for example, c−a−b could be 1). We will consider these cases below.
Let I and J be the maximum subscripts in the array, m−1 and n−1, respectively. (These are introduced for brevity, as m−1 and n−1 appear repeatedly below.) The maximum element in the array, AI,J, is 1 + (1−I)Ja + I(1−J)b + IJc = 1 + IJ(c−a−b) + Ja + Ib. Observe the derivative with respect to c is positive, so, once a and b are chosen, the minimum value for AI,J is obtained by making c as small as the constraints allow, hence either c = a+b+1 (for the case when one series is entirely less than the other) or c = a+b+2 (for the case when the series interleave). For the former, AI,J = 1 + IJ + Ja + Ib. For the latter, AI,J = 1 + 2IJ + Ja + Ib. This reveals we also wish to minimize a and b subject to the constraints.
The smallest a and b can be is 1 and 2 (in either order). So in the interleaving case, we have either AI,J = 1 + 2IJ + J + 2I or AI,J = 1 + 2IJ + 2J + I. To obtain the lesser of these, we choose a = 1, b = 2 if J < I and a = 2, b = 1 otherwise. Combinging these, the maximum is 1 + 2IJ + I + J + min(I, J). Restoring m and n from I and J and doing a little algebra gives us a maximum of 2mn − max(m, n).
For the non-interleaving case, we could have a = 1, the largest row difference (generally a+i(c−a−b)) of 1+I•1 = 1+I, so b = 2+I to start the column differences (generally b+j(c−a−b)) with b + 0(c−a−b) = 2+I. Conversely, we could have b = 1 and a = 2+J. Then we have AI,J = 1+ IJ + J + I(2+I) or 1 + IJ + J(2+J) + I, or, equivalently, mn+m2−m or mn+n2−n. The former is less when m < n and vice-versa.
Note than when m ≤ n, the interleaved case gives us a maximum of 2mn − n = mn + m2 + (m−1)(n−m) − m. Since (m−1)(n−m) is non-negative, that is at least as large as mn+m2−m, which is the maximum for the non-interleaved case. The analogous result holds for n ≤ m. Therefore, the interleaved case never has any advantage. The minimum is always obtained with the non-interleaved case with either a = 1, b = 2+I = m+1 or a = 2+J = n+1, b = 1, according to which of m and n is smaller.

Related

Index exceeds the number of array elements (9) in MATLAB

So I am getting an error where I believe n1 is larger than the array after n becomes n = 3, which is giving the error in ma. Premise of the code is to take 1 2, 3 4 5, 6 7 8 9, etc. and average each group. Pretty sure I have to change the length but not sure how to go about it. What should I do? Here is the code:
clear all
mdata = [1 2 3 4 5 6 7 8 9];
n1 = 1;
k = 1;
for n = 1:length(mdata)
ma(n) = (1/(k + 1)) * sum(mdata(n1:n1 + k));
n1 = ((n1 + k) + 1);
k = k + 1;
std_ma = std(mdata);
end
Error message:
Index exceeds the number of array elements (9).
Error in untitled22 (line 11)
ma(n) = (1/(k + 1)) * sum(mdata(n1:n1 + k));
The issue is that you are replacing the value of n1 with n1+k+1 on each step through the loop. At the start of the 4th iteration, n1=10 and k=4, meaning you are trying to take the sum of elements 10:14 but the array only has 9 elements.
It is not clear from your question exactly what averages you are trying to calculate through all of the iterations of the loop and so it is difficulty to say more. But, most likely, you do not need to manually calculate the average yourself. Just define the subset of the data you want to work with on that iteration and take the mean of that.
I am also guessing that you want to modify the assignment of std_ma at the end of your loop to only perform the std on the subset of data you are working with. Currently you are doing the calculation over all values in mdata and repeating that same calculation 9 times.

Number of ways to fill an array of size n , such that the mexium is greater than every element of the array?

We have given an empty array of size n , we need to fill it with natural numbers (we are allowed to repeat).
The condition that must follow is the mex of the array must be greater than all the elements we fill in the array .
Can someone pls help me with the number of ways to do so ?
(Different arrangements of same set of numbers are also considered distinct)
PS:- by mex of a sequence I mean the smallest non negative number that doesn't occur in the sequence
Number of such arrays is equivalent to the number of ordered distributions of values 1..N into buckets (so [A],[B,C] and [B,C][A] are distinct ones). And number of such distributions is described by ordered Bell numbers 1,3,13,75....
Example for N=3
1 1 1 //1 permutation
1 1 2 //3 permutations
1 2 2 //3 permutations
1 2 3 //6 permutations
//13 variants
Generation of distributions themselves for reference. Note that for N values every value might fall into part 1..K, where K is in range 1..N, so numbers of parts corresponding to all values form continuous sequence without holes (cf. your mex)
To calculate number of such distributions, we can use recurrence from Wiki, Python code:
def cnk(n, k):
k = min(k, n - k)
if k <= 0:
return 1 if k == 0 else 0
res = 1
for i in range(k):
res = res * (n - i) // (i + 1)
return res
def orderedbell(n):
a = [0]*(n+1)
a[0] = 1
for m in range(1, n+1):
for i in range(1, m+1):
a[m] += cnk(m, i) * a[m - i]
return a[n]
for i in range(1,10):
print(orderedbell(i))
1
3
13
75
541
4683
47293
545835
7087261

Check subset sum for special array equation

I was trying to solve the following problem.
We are given N and A[0]
N <= 5000
A[0] <= 10^6 and even
if i is odd then
A[i] >= 3 * A[i-1]
if i is even
A[i]= 2 * A[i-1] + 3 * A[i-2]
element at odd index must be odd and at even it must be even.
We need to minimize the sum of the array.
and We are given a Q numbers
Q <= 1000
X<= 10^18
We need to determine is it possible to get subset-sum = X from our array.
What I have tried,
Creating a minimum sum array is easy. Just follow the equations and constraints.
The approach that I know for subset-sum is dynamic programming which has time complexity sum*sizeof(Array) but since sum can be as large as 10^18 that approach won't work.
Is there any equation relation that I am missing?
We can make it with a bit of math:
sorry for latex I am not sure it is possible on stack?
let X_n be the sequence (same as being defined by your A)
I assume X_0 is positive.
Thus sequence is strictly increasing and minimization occurs when X_{2n+1} = 3X_{2n}
We can compute the general term of X_{2n} and X_{2n+1}
v_0 =
X0
X1
v_1 =
X1
X2
the relation between v_0 and v_1 is
M_a =
0 1
3 2
the relation between v_1 and v_2 is
M_b =
0 1
0 3
hence the relation between v_2 and v_0 is
M = M_bM_a =
3 2
9 6
we deduce
v_{2n} =
X_{2n}
X_{2n+1}
v_{2n} = M^n v_0
Follow the classical diagonalization... and we (unless mistaken) get
X_{2n} = 9^n/3 X_0 + 2*9^{n-1}X_1
X_{2n+1} = 9^n X_0 + 2*9^{n-1}/3X_1
recall that X_1 = 3X_0 thus
X_{2n} = 9^n X_0
X_{2n+1} = 3.9^n X_0
Now if we represent the sum we want to check in base 9 we get
9^{n+1} 9^n
___ ________ ___ ___
X^{2n+2} X^2n
In the X^{2n} places we can only put a 1 or a 0 (that means we take the 2n-th elem from the A)
we may also put a 3 in the place of the X^{2n} place which means we selected the 2n+1th elem from the array
so we just have to decompose number in base 9, and check whether all its digits or either 0,1 or 3 (and also if its leading digit is not out of bound of our array....)

Arrays: Find minimum number of swaps to make bitonicity of array minimum?

Suppose we are given an array of integer. All adjacent elements are guaranteed to be distinct. Let us define bitonicity of this array a as bt using the following relation:
bt_array[i] = 0, if i == 0;
= bt_array[i-1] + 1, if a[i] > a[i-1]
= bt_array[i-1] - 1, if a[i] < a[i-1]
= bt_array[i-1], if a[i] == a[i-1]
bt = last item in bt_array
We say the bitonicity of an array is minimum when its bitonicity is 0 if it has an odd number of elements, or its bitonicity is +1 or -1 if it has an even number of elements.
The problem is to design an algorithm that finds the fewest number of swaps required in order to make the bitonicity of any array minimum. The time complexity of this algorithm should be at worst O(n), n being the number of elements in the array.
For example, suppose a = {34,8,10,3,2,80,30,33,1}
Its initial bt is -2. Minimum would be 0. This can be achieved by just 1 swap, namely swapping 2 and 3. So the output should be 1.
Here are some test cases:
Test case 1: a = {34,8,10,3,2,80,30,33,1}, min swaps = 1 ( swap 2 and 3)
Test case 2: {1,2,3,4,5,6,7}: min swaps = 2 (swap 7 with 4 and 6 with 5)
Test case 3: {10,3,15,7,9,11}: min swaps = 0. bt = 1 already.
And a few more:
{2,5,7,9,5,7,1}: current bt = 2. Swap 5 and 7: minSwaps = 1
{1,7,8,9,10,13,11}: current bt = 4: Swap 1,8 : minSwaps = 1
{13,12,11,10,9,8,7,6,5,4,3,2,1}: current bt = -12: Swap (1,6),(2,5) and (3,4) : minSwaps = 3
I was asked this question in an interview, and here's what I came up with:
1. Sort the given array.
2. Reverse the array from n/2 to n-1.
3. Compare from the original array how many elements changed their position.
Return half of it.
And my bit of code that does this:
int returnMinSwaps(int[] a){
int[] a = {1,2,3,4,5,6,7};
int[] b = a;
Arrays.sort(b);
for(int i=0; i<= b.length/2 - 1; i++){
swap(b[b.length - i], b[b.length/2 - i]);
}
int minSwaps = 0;
for(int i=0;i<b.length;i++){
if(a[i] != b[i])
minSwaps++;
}
return minSwaps/2;
}
Unfortunately, I am not getting correct minimum number of ways for some test cases using this logic. Also, I am sorting the array which is making it in O(n log n) and it needs to be done in O(n).
URGENT UPDATE: T3 does not hold!
Consider α = [0, 7, 8, 3, 4, 10, 1, 6, 9, 2, 5]. There is no Sij(α) that can lower |B(α)| by more than 2.
Thinking on amendments to the method…
Warning
This solution only works when there are no array elements that are equal.
Feel free to propose generalizations by editing the answer.
Go straight to Conclusion if you want to skip the boring part.
Introduction
Let`s define the swap operator Sij over the array a:
Sij(a) : [… ai, … aj, …] → [… aj, … ai, …]   ∀i, j ∈ [0; |a|) ∩ ℤ : i ≠ j
Let`s also refer to the bitonicity as B(a), and define it more formally:
The obvious facts:
Swaps are symmetric:
Sij(a) = Sji(a)
Two swaps are independent if their target positions don`t intersect:
Sij(Skl(a)) = Skl(Sij(a))   ∀i, j, k, l : {i, j} ∩ {k, l} = ∅
Two 2-dependent swaps undo one another:
Sij(Sij(a)) = a
Two 1-dependent swaps abide to the following:
Sjk(Sij(a)) = Sij(Sik(a)) = Sik(Sjk(a))
Bitonicity difference is always even for equally sized arrays:
(B(a) – B(a')) mod 2 = 0   ∀a, a' : |a| = |a'|
Naturally, ∀i : 0 < i < |a|,
B([ai–1, ai]) – B([a'i–1, a'i]) = sgn(ai – ai–1) – sgn(a'i – a'i–1),
which can either be 1 – 1 = 0, or 1 – –1 = 2, or –1 – 1 = –2, or –1 – –1 = 0, and any number of ±2`s and 0`s summed yield an even result.
N.B.: this is only true if all elements in a differ from one another, same with a'!
Theorems
[T1]   |B(Sij(a)) – B(a)| ≤ 4   ∀a, Sij(a)
Without loss of generality, let`s assume that:
0 < i, j < |a| – 1
j – i ≥ 2
ai–1 < ai+1
aj–1 < aj+1
Depending on ai, 3 cases are possible:
ai–1 < ai < ai+1: sgn(ai – ai–1) + sgn(ai+1 – ai) = 1 + 1 = 2
ai < ai–1 < ai+1: sgn(ai – ai–1) + sgn(ai+1 – ai) = –1 + 1 = 0
ai–1 < ai+1 < ai: sgn(ai – ai–1) + sgn(ai+1 – ai) = 1 + –1 = 0
When altering ai and leaving all other elements of a intact, |B(a') – B(a)| ≤ 2 (where a' is the resulting array, for which the above 3 cases also apply), since no other terms of B(a) changed their value, except those two from the 1-neighborhood of ai.
Sij(a) implies what`s described above to happen twice, once for ai and once for aj.
Thus, |B(Sij(a)) – B(a)| ≤ 2 + 2 = 4.
Analogously, for each of the corners and j – i = 1 the max. possible delta is 2, which is ≤ 4.
Finally, this straightforwardly extrapolates to ai–1 > ai+1 and aj–1 > aj+1.
QED
[T2]   ∀a : |B(a)| ≥ 2   ∃Sij(a) : |B(Sij(a))| = |B(a)| – 2
{proof in progress, need to sleep}
[T3]   ∀a : |B(a)| ≥ 4   ∃Sij(a) : |B(Sij(a))| = |B(a)| – 4
{proof in progress, need to sleep}
Conclusion
From T1, T2 and T3, the minimal number of swaps needed to minimize |B(a)| equals:
⌊|B(a)| / 4⌋ + ß,
where ß equals 1 if |B(a)| mod 4 ≥ 2, 0 otherwise.

what will be time complexity of relation T(n)=nT(n-1)+n

WHAT will be time complexity of relation T(n)=nT(n-1)+n
in my prog something like this
f(int n)
{
c++;
if(n>0)
for(i=1;i<=n;i++)
f(n-1);
}
i took a counter to count how many time function called
it gives answer between n to n!
thanks.
Your code lacks the +n part of the recursion, so I assume that the code is wrong and the recursion
T(n) = n*T(n-1) + n
is correct.
Let f(n)=T(n)/n!, then
f(n) = T(n)/n! = n(T(n-1)+1)/n!
= T(n-1)/(n-1)! + 1/(n-1)!
= f(n-1) + 1/(n-1)!
= sum(1,n-1, 1/k!)
~ e
Thus T(n) ~ e*n!.
We can list out a few terms
T(0) = 0
T(1) = 1 * 0 + 1
T(2) = 2 * 1 + 2 = 4
T(3) = 3 * 4 + 3 = 15
T(4) = 4 * 15 + 4 = 64
...
We can note a couple of things. First, the function grows more quickly than n!; it starts out smaller than it (at n=0), catches up (at n=1) and surpasses it (at n>=2). So we know that a lower bound is n!.
Now, we need the upper bound. We can notice one thing: T(n) = nT(n-1) + n < nT(n-1) + nT(n-1) for all sufficiently large n (n >= 2, I think). But we can easily show that T(n) = nT(n-1) is a recurrence relation for n!, so we know that a recurrence relation for T(n) = nT(n-1) + nT(n-1) = 2nT(n-1) is (n!)(2^n). Can we do better?
I propose that we can. We can show that for any c > 0, T(n) = nT(n-1) + n < nT(n-1) + cnT(n-1) for sufficiently large values of n. We already know that T(n-1) is bounded below by (n-1)!; so, if we take c = n/(n-1)! we recover exactly our expression and we know that an upper bound is (c^n)(n!). What is the limit of c as n goes to infinity? 0. What is the maximum value assumed by [n/(n-1)!]^n?
Good luck computing that. Wolfram Alpha makes it fairly clear that the maximum value assumed by this function is around 5 or 6 for n ~ 2.5. Assuming you are convinced by that, what's the takeaway?
n! < T(n) < ~6n! for all n. n! is the Theta-bound for your recurrence.
The function is called
n*f(n-1)
times. Replacing f(n-1) with this definition gives
n*((n-1)*f(n-2)
Replacing again gives:
n*((n-1)*((n-2)*f(n-3)))
Removing brackets:
n*(n-1)*(n-2)*...(1)
This gives:
n= 3: 3*2*1 = 6
n= 4: 4*3*2*1 = 24
n= 5: 5*4*3*2*1 = 120
which is n!.

Resources