google sheets sum on previous rows data + constant variable - if-statement

I'm currently facing a problem which I cannot solve, would appreciate help.
a link to the spreadsheet
click here
now, here is the problem.
I want H to be calculated by the sum of previous months(H)+ portfolio size(K8) * G of the current row. in array formula so I won't need to add the function each time I create a new row.
but if it exceeds 10,000 that it will be G(current row)*10,000.
for example:
row 4, IF(portfolio size + SUM (H2:H3)>10000,G4*10000,G4* (portfolio size(K8) + SUM (H2:H3)))
row 5, IF(portfolio size + SUM (H2:H4)>10000,G4*10000,G4* (portfolio size(K8) + SUM (H2:H4)))
and so on.
would appreciate the help

try:
=ARRAYFORMULA(IF(A2:A="",,IF(K8+IF(A2:A="",,
{0; MMULT(TRANSPOSE((ROW(B2:B)<=TRANSPOSE(ROW(B2:B)))*G2:G*K8),
SIGN(G2:G)^0)})>K8,G2:G*K8, (K8+IF(A2:A="",,
{0; MMULT(TRANSPOSE((ROW(B2:B)<=TRANSPOSE(ROW(B2:B)))*G2:G*K8),
SIGN(G2:G)^0)}))*G2:G)))

Related

Fill the Grid with three colors A and B and C

How to find the numbers of ways to fill a grid (3*n)array, with three colors A, B and C.
Under the following constraints:
1) All the n cells of the same row can't have the same color.
2) All the 3 cells of the same column can't have the same color.
Sample input : if n=2, then output or number of ways = 174.
Please explain the approach for this.
This answer given by sam29 on codefores.
We can solve this question using Inclusion-Exclusion principle. So, let's first consider only the first column of the matrix. We can easily deduce that there are 24 different ways to fill that column keeping in mind that we can't have the same letter in the complete column. Now, we can directly say that the total ways to fill the complete matrix will be 24^N (Name this value as X1). In this answer, we have made sure that all the column contains distinct alphabets. But we need to consider the cases a row contains the same letter. So, now we will use inclusion-exclusion principle.
Find the number of cases with one row same. Fix 'A' in the first row. Now, take only the first column and you can deduce that there are 8 distinct ways to fill the 2nd and the 3rd row of the first column keeping in mind we can't have the same letter in the complete column. So, now we can find the total number of ways to fill all the N rows as 8^N. Now, we can do the same thing with 'B' and 'C' in the first row and similarly, we can repeat the process for the 2nd and the 3rd row. So, the total number of ways will be 9*8^N (Name this value as X2).
Find the number of cases with two rows same (Name this value as X3). This is the trickiest part of the question. I'll explain this at last.
Find the number of cases with all the three rows same but we can't have the same letter in a single column. This is pretty easy and is equivalent to the number of ways to fill a single column and 3 rows. So, the answer is 24 for this scenario (Name this value as X4).
Now, the final answer will be X1-X2+X3-X4.
Now, coming back to the answer for 2nd scenario. So, we will try to find the answer for the case when the first row and second row is same and we can repeat that process for the 2nd row and 3rd row AND 1st row and 3rd row. Basically, we can multiply the answer we will calculate now with 3. Okay, now take only the first column. Now, you can see that there will be 2 scenarios, one will be when the first and second row contains the same letter and in that case, we have to place a different letter in the 3rd row because else we will violate our condition of the distinct column. So, the total number of ways in the first scenario will be 3*2^N (I have skipped some part but I have provided the exact reason and a little further thinking and you will get the solution). Now, for the next scene when the first and second row contains different letters. In that case, you can place any letter in the 3rd row. Again try to think a little more and you will get the answer as 6*3^N. So, the total answer will be 3*2^N + 6*3^N. And as I said before we need to multiply it by 3 (Number of ways to choose 2 rows from 3 rows). So, X3 will be 3*(3*2^N + 6*3^N).
The complexity is pretty direct, you can do precomputation or apply exponent function every time.
Thanks.
This is combinatorial question, for sure it is better to post questions like this on math.stackexchange.com.
A row can be in two different configurations: having two colors (ABA) and having three colors (ABC). If we have last row of some configuration, lets check possibilities for next row.
A | B B B C C
B | A A C A A
A | B C B B C
A | B B B C
B | A C C A
C | B A B B
Set:
A_n : number of dimension n matrices where last row is of ABA configuration,
C_n : number of dimension n matrices where last row is of ABC configuration,
X_n : number of dimension n matrices = A_n + C_n.
From upper list of possibile next row it holds:
A_n = 3 * A_(n-1) + 2 * C_(n-1) = 2 * X_(n-1) + A_(n-1)
C_n = 2 * A_(n-1) + 2 * C_(n-1) = 2 * X_(n-1)
=>
X_n = 4 * X_(n-1) + A_(n-1)
Result to question is X_n, for which calculation A_n is needed, and initial values are A_1=6, X_1=12.
Update:
Search in OEIS for values 2, 9, 41, 187 (upper sequence if colors are not important, real number divided by 6), produces sequence A020698. Sequence mentions similar problem, and suggests that upper recursion can be stated in simpler manner:
X_n = 4 * X_(n-1) + A_(n-1)
= 4 * X_(n-1) + A_(n-1) + X_(n-1) - X_(n-1)
= 5 * X_(n-1) + 2 * X_(n-2) + A_(n-2) - 4 * X_(n-2) - A_(n-2)
= 5 * X_(n-1) - 2 * X_(n-2)

How do i solve these variations of the 0-1 knapsack algorithm?

The knapsack can carry a maximum weight , say max_wt ; has n items with a given weightwt[] and a valueval[].I have two questions ( both seperate from each other ) :
What is the maximum value we can carry if there was a second limit to the volume we could carry , vol[ ] ?
What are the number of ways to carry a total of exactly z(< n) items such that their sum of values is divisible by a number , say 8 ?
My Attempt
For the first question i refered this stackoverflow post , but the only answer i could understand was one where the two constraints were merged ,but the run time complexity of that would be quite big i guess...what i was thinking was making a dp[i][j][k] , where i is the number of items selected , j is the max-wt selected at that point , k is the max-vol selected at that point and then my core of the code looked like
for(i=0 ; i < n ; i++) \\ n is no. of items
for(j=0 ; j < n ; j++)
for(k=0 ; k < n ; k++)
dp[i][j][k] = max( dp[i-1][j][k] , val[i] + dp[i-1][j-wt[j]][k-vol[k]]) ;
, this seems alright , but gives me wrong answer ... i cant guess why :(
I can't start to think of the second problem, my friend did it by taking three states dp[i][j][k] where i and j are just same as first question(the usual ones) while 'k' keeps track of the total items selected , this idea isnt getting in my head . Plus , what will a state store , it usually stores max value possible till given state in classical knapsack problems , here i guess a state will store total combinations divisible by 8 till that state , but i cant convert this into code .
p.s please try providing a solution with bottom up approach to the second question , i am very new to dynamic programming . ;)
Two-dimensional knapsack problem
let n be the number of items
let val[i] be the value of the i-th item
let w[i] be the weight of the i-th item
let v[i] be the volume of i-th item
let T[i,j,k] be the best value out of the first i items and having exactly weight j and volume k. T can be defined in some other way but this definition gives a short formula.
Finding best value
T[0,j,k] = 0
T[i,j,k] = T[i-1,j,k], when j<w[i] or k<v[i], otherwise:
T[i,j,k] = max( T[i-1,j,k] , T[i-1,j-w[i],k-i] + val[i] )
best possible value would be max T[n,j,k] for all j and k
Implementation notes
initialize base cases first for all j and k
loop i from 1 to n and be consistent with 1-based arrays indexes
loop j from 1 to max possible weight which is the sum of all weights, e.g. w[1]+w[2]+...w[n]
loop k from 1 to max possible volume
Counting number of ways to get an exact value with an exact number of items
let S[i,j,k,l] be the number of ways in which the first i items can be arranged with exactly weight j, value k, and l items.
S[0,j,k,l] = 0, except S[0,0,0,0] = 1
S[i,j,k,l] = S[i-1,j,k,l] + S[i-1,j-w[i],k-val[i],l-1]
number of ways to get exactly value y using exactly z items is the sum of T[n,j,y,z] for all j
Observations
There are many ways to look at these problems and to define the states T and S. This is but one of them. Implementations can also differ. The thumb-rule for dimensions is that another constraint in the sack or dimension in the items means another dimension in the formula. The thumb-rule for counting ways is that you add up instead of finding max.

Using for loops and nested lists in python

I am trying to add each row of nested loop independently in order to find averages. I am missing a detail which may or may not derail my whole code.The code should compute the average of a given row of scores but drops the lowest grade.
def printAverages():
scores = [[100,100,1,100,100],
[20,50,60,10,30],
[0,10,10,0,10],
[0,100,50,20,60]]
total = 0
minValue = 100
counter = -1
for row in scores:
counter = counter + 1
for n in scores[0]:
total = total+n
if minValue > n:
minValue = n
total = total - minValue
print("Average for row",counter,"is",total)
total = 0
How do i make it so for n in score [0] takes the average of each row instead of only computing the average of the first row? I know that scores[0] commands the program to only read the first row, I just don't know how to change it.
Thank you
Remember, the XY problem.
# Sum of a list of numbers divided by the number of numbers in the list
def average(numbers):
return sum(numbers)/len(numbers)
# This is your data
scores = [[100,100,1,100,100],
[20,50,60,10,30],
[0,10,10,0,10],
[0,100,50,20,60]]
# enumerate() allows you to write FOR loops naming both the list element and its index
for (i, row) in enumerate(scores):
print("Average for row ", i, "is ", average(row))
Keep in mind that Python supports functional programming and encourages the programmer to write pure functions when possible!
the statement for n in scores[0]: will only go through the first column.
What you want it to say is for n in row:. That will have it go through each row, one row per loop of the outer loop

compute sum of value in an rectangle area of array

I have a very big array of many value and store it in an row-major 1d array.
ex:
1 2 3
4 5 6
will be store in int* array = {1,2,3,4,5,6};
what I have to do is given the row1, row2, column1, column2, then print out the area's sum, and it will request to caulate different area for many times.
what I have think about it is first use nested loop to traverse the array and store each row's sum in sum_row and store each column's sum in sum_column and store the total element's sum im totalSum.
Then totalSum - the row and the columns that surrond it + the elemnts that has been minus twice.
But it seems fast enough, is there any algorithm that can do faster or some coding style tips that can make the factor little?
Thx in advance.
It seems to me that you have replaced one double iteration with another. The problem is in subtracting "the elemnts that has been minus twice"; unless I'm mistaken, this involves iterating over those elements to sum them.
Instead, just iterate over the rectangular area that you need to sum. I doubt it will be any slower.
A more efficient algorithm can be obtained by generating the matrix of summed upper-left matrices. (See the Wikipedia article on summed area table.) You can then compute any submatrix sum by looking up four area sums.

Number of Items in a Column inside a grid

How do you find number of items in a column inside a grid?
I have a grid (listview control to be specific), and have some items.
Some times a given row might not be full. ANd can have values in fewer than maximum columns. I need to find Number of items in a given Column.
If the grid is like
1 2 3
4 5 6
7
and if input column is 1, then we need to output 3, and 2 for input of 2 or 3.
I have variables to for ItemCount, CoulmnCount and RowCount which track number of items, rows and columns.
A very rudimentar way would be something like this:
int iItemCount=0,iItemInColumn=0;
for(int iCol=0;iCol<iColumnCount;iCol++)
for(int iRow=0;iRow<iRowCount;iRow++,iItemCount++)
if(iCol==iInputCol && iItemCount<iTotalItems)
iItemInColumn++;
Can you guys think of any sophesticated way, which does not need loops? possible utilizing just 3 variables which I already have for tracking?
Assuming 0-based indexes:
def itemsInColumn(itemCount, columnCount, inputColumn):
lastItemColumn = (itemCount - 1) % columnCount
if inputColumn <= lastItemColumn:
return (itemCount + columnCount - 1) / columnCount
else:
return itemCount / columnCount
It depends on the total number of items (itemCount) and the number of columns (columnCount). It just computes itemCount / columnCount, and rounds up or down depending on whether the input column is less than or equal to the last item's column.
The computation "(itemCount + columnCount - 1) / columnCount" is just a trick for rounding up using integer division. In general, given positive integers a and b: ceil(a / b) = (a + b - 1) div b, where div is integer division.