I am trying to determine the frequency count of a triple nested loop.
for i = 1 to n do
for j = 1 to i do
for k = i to j do
x = x + 1
I know that the statement x = x + 1 will not get executed until i attains the value of n
Any tips/suggestions on how to get started?
Let's take 4 and 5 as examples. When i = 4,
...
for j = 1 to 4 do
for k = 4 to j do
x = x + 1
...j = 1
for k = 4 to 1 do // 4 times
x = x + 1
...j = 2
for k = 4 to 2 do // 3 times
x = x + 1
...j = 3
for k = 4 to 3 do // twice
x = x + 1
...j = 4
for k = 4 to 4 do // once
x = x + 1
When i = 5,
...
for j = 1 to 5 do
for k = 5 to j do
x = x + 1
...j = 1
for k = 5 to 1 do // 5 times
x = x + 1
...j = 2
for k = 5 to 2 do // 4 times
x = x + 1
...j = 3
for k = 5 to 3 do // 3 times
x = x + 1
...j = 4
for k = 5 to 4 do // twice
x = x + 1
...j = 5
for k = 5 to 5 do // once
x = x + 1
pattern?
Related
I mean a function that accepts an array of elements and a combination as params, and returns a number that represents the index of a combination without generating every combination.
I have no preference, it can be in any programming language.
An example of code getCombinationIndex("114") and should return the index of combination 114.
[1,1,1]: 1
[2,1,1]: 2
[3,1,1]: 3
[4,1,1]: 4
[.....]
[1,1,4]: ?
Let's say you are considering combinations of k symbols from alphabet A = {a_0, a_1, ..., a_n} (i.e. with n symbols and a_i < a_j lexicographically if i < j). In your example, you have an alphabet of 4 symbols A = {1, 2, 3, 4} and combinations of k = 3 symbols.
Then, a combination c = [a_i1, a_i2, ..., a_ik] can be uniquely encoded as I(c) = i1 + n*i2 + (n^2)*i3 + ... + (n^(k-1))*ik. The indexing you're looking for is F(c) = I(c) + 1.
Let's see how it works for your example:
F([1,1,1]) = I([1,1,1]) + 1 = 0 + 4*0 + (4^2)*0 + 1 = 1
F([2,1,1]) = I([2,1,1]) + 1 = 1 + 4*0 + (4^2)*0 + 1 = 2
F([3,1,1]) = I([2,1,1]) + 1 = 2 + 4*0 + (4^2)*0 + 1 = 3
F([4,1,1]) = I([2,1,1]) + 1 = 3 + 4*0 + (4^2)*0 + 1 = 4
...
F([2,1,3]) = I([2,2,3]) + 1 = 1 + 4*1 + (4^2)*2 + 1 = 38
...
F([1,1,4]) = I([1,1,4]) + 1 = 0 + 4*0 + (4^2)*3 + 1 = 49
...
F([4,4,4]) = I([4,4,4]) + 1 = 3 + 4*3 + (4^2)*3 + 1 = 64
This problem can be seen as base conversion. You need two informations to start with and then it will be only a base conversion.
The base
In your case this is the highest number of all the items.
[4,1,1] -> 4
The desired combination
This only works for the premiss that all items can have the same maximum.
Algorithm
Reverse the order of items
Decrement every item by 1
Convert the number to base 10
Increment by 1
Example
Start: 114
Reverse: 411
Decrement: 300
Conversion:
Base 4: 300
Base 10: 3*4^2 + 0*4^1 + 0*4^0 = 24
Increment: 25
Input 1 :
64
Output:( size of 3 )
1 x 1 x 64 =64
1 x 2 x 32 =64
1 x 4 x 16 =64
1 x 8 x 8 =64
2 x 2 x 16 =64
2 x 4 x 8 =64
4 x 4 x 4 =64
Input 2 :
6
Output:( size of 2 )
1 x 6 =6
2 x 3 =6
I tried Using Complete Binary Tree but I didn't get all possible Combination
.
Here is :
64
32 2
16 2 2 1
8 2 1 2 1 2 1 1
If Your trace level by level elements only some combinations are available
64 x 1 X 1
32 X 2 X 1
16 x 2 x 2
8 x 2 x 2 x 2( limit > 3 )
Question is I need all possible combinations
You can use recursion method. Consider the following PHP code (I guess you can convert for the idea to each language you need):
function comb($num, $cnt, $prefix, $minDiv) {
if ($cnt == 0)
{
if ($num == 1)
return rtrim($prefix,",");
else return false;
}
$arrs = array();
for ($i=$minDiv; $i <= $num; $i++) {
if ($num % $i == 0) { // if num modulo i equal 0
$ans = comb($num/$i, $cnt-1, $prefix . $i . ",", $i );
if ($ans) // if valid combination add it
$arrs[] = $ans;
}
}
return $arrs;
}
$ans = comb(64,3, "",1);
echo "ANSWER:\n";
echo print_r($ans);
This code will generate the following answer for comb(6,2, "", 1):
1,6
2,3
f(N) = 0^0 + 1^1 + 2^2 + 3^3 + 4^4 + ... + N^N.
I want to calculate (f(N) mod M).
These are the constraints.
1 ≤ N ≤ 10^9
1 ≤ M ≤ 10^3
Here is my code
test=int(input())
ans = 0
for cases in range(test):
arr=[int(x) for x in input().split()]
N=arr[0]
mod=arr[1]
#ret=sum([int(y**y) for y in range(N+1)])
#ans=ret
for i in range(1,N+1):
ans = (ans + pow(i,i,mod))%mod
print (ans)
I tried another approach but in vain.
Here is code for that
from functools import reduce
test=int(input())
answer=0
for cases in range(test):
arr=[int(x) for x in input().split()]
N=arr[0]
mod=arr[1]
answer = reduce(lambda K,N: x+pow(N,N), range(1,N+1)) % M
print(answer)
Two suggestions:
Let 0^0 = 1 be what you use. This seems like the best guidance I have for how to handle that.
Compute k^k by multiplying and taking the modulus as you go.
Do an initial pass where all k (not exponents) are changed to k mod M before doing anything else.
While computing (k mod M)^k, if an intermediate result is one you've already visited, you can cut back on the number of iterations to continue by all but up to one additional cycle.
Example: let N = 5 and M = 3. We want to calculate 0^0 + 1^1 + 2^2 + 3^3 + 4^4 + 5^5 (mod 3).
First, we apply suggestion 3. Now we want to calculate 0^0 + 1^1 + 2^2 + 0^3 + 1^4 + 2^5 (mod 3).
Next, we begin evaluating and use suggestion 1 immediately to get 1 + 1 + 2^2 + 0^3 + 1^4 + 2^5 (mod 3). 2^2 is 4 = 1 (mod 3) of which we make a note (2^2 = 1 (mod 3)). Next, we find 0^1 = 0, 0^2 = 0 so we have a cycle of size 1 meaning no further multiplication is needed to tell 0^3 = 0 (mod 3). Note taken. Similar process for 1^4 (we tell on the second iteration that we have a cycle of size 1, so 1^4 is 1, which we note). Finally, we get 2^1 = 2 (mod 3), 2^2 = 1(mod 3), 2^3 = 2(mod 3), a cycle of length 2, so we can skip ahead an even number which exhausts 2^5 and without checking again we know that 2^5 = 2 (mod 3).
Our sum is now 1 + 1 + 1 + 0 + 1 + 2 (mod 3) = 2 + 1 + 0 + 1 + 2 (mod 3) = 0 + 0 + 1 + 2 (mod 3) = 0 + 1 + 2 (mod 3) = 1 + 2 (mod 3) = 0 (mod 3).
These rules will be helpful to you since your cases see N much larger than M. If this were reversed - if N were much smaller than M - you'd get no benefit from my method (and taking the modulus w.r.t. M would affect the outcome less).
Pseudocode:
Compute(N, M)
1. sum = 0
2. for i = 0 to N do
3. term = SelfPower(i, M)
4. sum = (sum + term) % M
5. return sum
SelfPower(k, M)
1. selfPower = 1
2. iterations = new HashTable
3. for i = 1 to k do
4. selfPower = (selfPower * (k % M)) % M
5. if iterations[selfPower] is defined
6. i = k - (k - i) % (i - iterations[selfPower])
7. clear out iterations
8. else iterations[selfPower] = i
9. return selfPower
Example execution:
resul = Compute(5, 3)
sum = 0
i = 0
term = SelfPower(0, 3)
selfPower = 1
iterations = []
// does not enter loop
return 1
sum = (0 + 1) % 3 = 1
i = 1
term = SelfPower(1, 3)
selfPower = 1
iterations = []
i = 1
selfPower = (1 * 1 % 3) % 3 = 1
iterations[1] is not defined
iterations[1] = 1
return 1
sum = (1 + 1) % 3 = 2
i = 2
term = SelfPower(2, 3)
selfPower = 1
iterations = []
i = 1
selfPower = (1 * 2 % 3) % 3 = 2
iterations[2] is not defined
iterations[2] = 1
i = 2
selfPower = (2 * 2 % 3) % 3 = 1
iterations[1] is not defined
iterations[1] = 2
return 1
sum = (2 + 1) % 3 = 0
i = 3
term = SelfPower(3, 3)
selfPower = 1
iterations = []
i = 1
selfPower = (1 * 3 % 0) % 3 = 0
iterations[0] is not defined
iterations[0] = 1
i = 2
selfPower = (0 * 3 % 0) % 3 = 0
iterations[0] is defined as 1
i = 3 - (3 - 2) % (2 - 1) = 3
iterations is blank
return 0
sum = (0 + 0) % 3 = 0
i = 4
term = SelfPower(4, 3)
selfPower = 1
iterations = []
i = 1
selfPower = (1 * 4 % 3) % 3 = 1
iterations[1] is not defined
iterations[1] = 1
i = 2
selfPower = (1 * 4 % 3) % 3 = 1
iterations[1] is defined as 1
i = 4 - (4 - 2) % (2 - 1) = 4
iterations is blank
return 1
sum = (0 + 1) % 3 = 1
i = 5
term = SelfPower(5, 3)
selfPower = 1
iterations = []
i = 1
selfPower = (1 * 5 % 3) % 3 = 2
iterations[2] is not defined
iterations[2] = 1
i = 2
selfPower = (2 * 5 % 3) % 3 = 1
iterations[1] is not defined
iterations[1] = 2
i = 3
selfPower = (1 * 5 % 3) % 3 = 2
iterations[2] is defined as 1
i = 5 - (5 - 3) % (3 - 1) = 5
iterations is blank
return 2
sum = (1 + 2) % 3 = 0
return 0
why not just use simple recursion to find the recursive sum of the powers
def find_powersum(s):
if s == 1 or s== 0:
return 1
else:
return s*s + find_powersum(s-1)
def find_mod (s, m):
print(find_powersum(s) % m)
find_mod(4, 4)
2
After the you guys helped me out so gracefully last time, here is another tricky array sorter for you.
I have the following array:
a = [1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16]
I use it for some visual stuff and render it like this:
1 2 3 4
5 6 7 8
9 10 11 12
13 14 15 16
Now I want to sort the array to have a "snake" later:
// rearrange the array according to this schema
1 2 3 4
12 13 14 5
11 16 15 6
10 9 8 7
// the original array should look like this
a = [1,2,3,4,12,13,14,5,11,16,15,6,10,9,8,7]
Now I'm looking for a smart formula / smart loop to do that
ticker = 0;
rows = 4; // can be n
cols = 4; // can be n
originalArray = [1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16];
newArray = [];
while(ticker < originalArray.length)
{
//do the magic here
ticker++;
}
Thanks again for the help.
I was bored, so I made a python version for you with 9 lines of code inside the loop.
ticker = 0
rows = 4
cols = 4
originalArray = [1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16]
newArray = [None] * (rows * cols)
row = 0
col = 0
dir_x = 1
dir_y = 0
taken = {}
while (ticker < len(originalArray)):
newArray[row * cols + col] = originalArray[ticker]
taken[row * cols + col] = True
if col + dir_x >= cols or row + dir_y >= rows or col + dir_x < 0:
dir_x, dir_y = -dir_y, dir_x
elif ((row + dir_y) * cols + col + dir_x) in taken:
dir_x, dir_y = -dir_y, dir_x
row += dir_y
col += dir_x
ticker += 1
print newArray
You can index into the snake coil directly if you recall that
1 + 2 + 3 + ... + n = n*(n+1)/2
m^2 + m - k = 0 => m - (-1+sqrt(1+4*k))/2
and look at the pattern of the coils. (I'll leave it as a hint for the time being--you could also use that n^2 = (n-1)^2 + (2*n+1) with reverse-indexing, or a variety of other things to solve the problem.)
When translating to code, it's not really any shorter than Tuomas' solution if all you want to do is fill the matrix, however.
I basically have a few variables
0 < na < 250
0 < max <= 16
nb = (na + max - 1) / max
n has the following characterstics
0 <= i < nb - 1 => n = max
i = nb - 1 => n = na - i * max
Is there an easy way to do this without the ternary operator?
for (i = 0; i<nb;i++) {
n = ((i + 1) * max > na ? na - (i * max) : max);
}
Examples
na = 5
max = 2
nb = 3
i = 0 => n = 2
i = 1 => n = 2
i = 2 => n = 1
na = 16
max = 4
nb = 4
i = 0 => n = 4
i = 1 => n = 4
i = 2 => n = 4
i = 3 => n = 4
na = 11
max = 3
nb = 4
i = 0 => n = 3
i = 1 => n = 3
i = 2 => n = 3
i = 3 => n = 2
The question is not very clear. Perhaps you're looking for something like this:
for (i=0;i < nb;++i)
{
n = i < nb - 1 ? max : (na - 1) % max + 1;
}
You don't need to calculate nb. This is one way you could do it (C#):
int na = 11;
int max = 4;
for (int i = 0, x = 0; x < na; i++, x += max)
{
int n = Math.Min(max, na - x);
Console.WriteLine("i = {0}, n = {1}", i, n);
}
Output:
i = 0, n = 4
i = 1, n = 4
i = 2, n = 3
Just to add more confusion to the thread:
If only you print max in the first two cases, then you could do something like: (not in any particular language)
//for 0
printf("i = %d, n = %d\n",i,max)
//for 1
printf("i = %d, n = %d\n",i,max)
//for the rest
for (i = 2; i<nb;i++) {
printf("i = %d, n = %d\n",i,na - (i * max));
}
You can avoid the operator doing two for loops
for (i = 0; (i + 1) * max) > na AND i < nb;i++) {
printf("i = %d, n = %d\n",i,0);
}
for (; i<nb;i++) {
printf("i = %d, n = %d\n",i,na - (i * max));
}