How to count number of bars between 2 candles that meet distinct conditions respectively in pine-script - count

Given 2 true false conditions A and B
I would like to search for the low of all the candles between these 2 conditions.
the script load, but an error say "invalid value of the 'length' argument (0.0) in the "lowest" function. it must be >0"
Could someone help please? Thanks
var int nb_bars = 0
nb_bars := B? ta.barssince(A)[2] : 0 // I have [2] because condition A could trigger just before condition B, I want to search the A which is further away
ClusterLow = B ? ta.lowest(nb_bars) : na

The error is clear, you cannot set the length to zero.
And ta.barssince(A)[2] can also be zero if condition A happened 2 bars ago from now, then it happened 0 bars back 2 bars ago. If you skew the index with [2], you have to skew the length parameter as well.
Try ClusterLow = B ? ta.lowest(nb_bars + 2) : na

Related

Incrementation with a for loop

x <- c(2,5,4,3,9,8,11,6)
count <- 0
for (val in x) {
if (val %% 2 == 0) {
count <- count + 1
}
} print(count)
# [1] 4
I do not get why it is 4 and not 5, could someone give me a hint?
So from x <-c(2,5,4,3,9,8,11,6), there are only four numbers in which the remainder will be 0 when divided by 2.
Knowing that, let's look at what each part of the code does. You are defining a variable count and assigning it the value of 0. Already from the beginning, count starts at 0. The next line is a for loop. What the loop does is go through each value of x (recall that x <-c(2,5,4,3,9,8,11,6)). Now, the if statement says that for each value of x, if the value is divisible by 2 and has no remainder, add 1 to count (which is why you have the line count <- count + 1, you are adding 1 to count, which started at zero, and reassigning the new value to count - think of it as rewriting the value of count, replacing it). Now there are four values in x that are divisible by 2 and have a remainder of zero, so doing the math: 0 + 4 = 4. You should get:
print(count)
[1] 4
Hope this helps explain every aspect of the code. I highly recommend you understand and read about for loops, if statements, and overall just any R basics. There are several tutorials online explaining all these components.

For loop number path calculation [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 5 years ago.
Improve this question
I have a bidirectional network, that is, a network where flow exists both from i->j and j->i. And I want to calculate the number of simple paths between each [i,j] and report in matrices according to the path length, that is, for each [i,j] pair there's a certain number of simple paths of length 2, 3, 4, etc, and I would like to calculate this and have the results being reported in: a reporting matrix of the number of simple paths of length 2 between i and j; a reporting matrix of the number of simple paths of length 3 between i and j, etc....
The solution I found was to create a code that would look to the original input matrix and search for paths of length x from i->n by looking to the connections of i with the other variables, then these with the other variables excluding i, and so on for x+1 variables until we got to x->n. E.g. for length two paths will look for i->x connection and any x->n connection. If this is true then there's a length two simple path between i and n. If the approach was left like this, when analysing bidirectional matrices or matrices with self-loops, the code would count self-loops has simple paths, and pass more than once by the same vertex. To solve this problem, in the conditions set in the code another parameter need to be verified. This parameter is a restriction on the assignment of the variables of the original matrix to our general variables, that is, when assigning a new general variable for the path search, the variable assigned cannot be one already assigned in that path search to another general variable:
* when looking for a path of length 2 between iand n, the variable to be assigned to x cannot be the one already assigned to i (this eliminates the self-loops from counting in as paths), and in the same way n cannot be assigned a variable already used either by i or x (this eliminates de reporting of cases of i->x->i has paths of length 2 and also eliminates de reporting of paths passing more than once by the same variable [i->x->x2->i for 3length paths e.g.]). So the code I use is basically this:
#the adjacency matrix
> MM<-matrix(c(1,1,0,0,0,1,1,1,1,0,0,1,1,1,0,0,1,0,1,1,0,0,0,1,1), 5, byrow=T)
> colnames(MM)<-c("A", "B", "C", "D", "E")
> row.names(MM)=colnames(MM)
> MM
A B C D E
A 1 1 0 0 0
B 1 1 1 1 0
C 0 1 1 1 0
D 0 1 0 1 1
E 0 0 0 1 1
#this is the reporting matrix where the results will be reported
> MMres2<-matrix(rep(0,length(MM)), sqrt(length(MM)))
> colnames(MMres2)=colnames(MM)
> row.names(MMres2)=row.names(MM)
#this is the code for the calculation and report of simple paths of lenght 2
> for(i in 1:dim(MM)){
for(j in 1:dim(MM)){
for(k in 1:dim(MM)){
if(MM[i,j]==1 & MM[j,k]==1 & j!=i & k!=i & k!=j){
MMres2[i,k]=MMres2[i,k]+1
}
}
}
}
#the reported results
> MMres2
A B C D E
A 0 0 1 1 0
B 0 0 0 1 2
C 1 1 0 2 1
D 1 0 1 0 0
E 0 1 0 0 0
If I want to calculate the number of simple paths of length 3 between any i->n we just need to had the condition of [x2,n]==1 and make sure we restrict the new variable to not be equal to any of the previously assigned ones.
And here, at last, lays my problem. I don't want to simply calculate the number of paths of length 2 or three or four, but all the possible (maximum possible length of a path is the total number of variables minus 1). Obviously, having a code for each path of length x for each matrix would be cumbersome, and for matrices with ever higher N number of variables, the more cumbersome would it be to create such code. To simplify this, the ideal solution would be to develop a code that would look for all pairs i and j and and calculate the number of paths between each for all the possible number of links per path up to paths of tot.var-1 links (that is, the maximum number of links on a path between each pair of i and j).
Take again the M2 matrix, the ideal code would look for the existence of a link between i and a x variable and then between x variable and j, and in the case of the condition being reported, it would report the result each time a path was found:
[i,x]==1 & [x’,j]==1 -> Res.mat[i,j] + 1
Where, x and x’ are any (and any number) of variables between i and j.
The point that differs this approach from the original above is that here x can be a multitude of variables, that is, in one iteration, when looking for a path of 2 links, x will be one variable, while one looking for a path of 3 links, x will be two variables and so forth.
E.g.:
For a path of length 2:
[i,xa]==1 & [xa,j]==1 -> Res.mat2[i,j] +1
For a path of length 3:
[i,xa]==1 & [xa,xb]==1 & [xb,j]==1 -> Res.mat3[i,j] +1
For a path of length 4:
[i,xa]==1 & [xa,xb]==1 & [xb,xc]==1 & [xc,j]==1 -> Res.mat4[i,j] +1
In this code, x would progressively assume all the other variables excluding i and j, and reporting each path for the respective reporting matrix, the ones of length two for the length2 reporting matrix, etc.
Sorry for the very, very long post, this is something I've been searching for long and talked with colleagues and no one seems to either understand or help me and that's why I made it in a long post to try and be the clearest possible.
So, anyone knows a how I can make this?

How do I count the number of pattern occurrences, if the pattern includes NA, in R?

I have a string of 0's, 1's and NA's like so:
string<-c(0,1,1,0,1,1,NA,1,1,0,1,1,NA,1,0,
0,1,0,1,1,1,NA,1,0,1,NA,1,NA,1,0,1,0,NA,1)
I'd like to count the number of times the PATTERN "1-NA-1" occurs. In this instance, I would like get the count 5.
I've tried table(string), and trying to replicate this but nothing seems to work. I would appreciate anyone's help!
# some ugly code, but it seems to work
sum( head(string, -2) == 1 & is.na(head(string[-1],-1))
& string[-1:-2] == 1, na.rm = TRUE)
Something like:
x <- which(is.na(string))
x <- x[!x %in% c(1,length(string))]
length(x[string[x-1] & string[x+1]])
# [1] 5
-- REASONING --
First, we check which values of string are NA with is.na(string). Then we find those indices with which and store them in x.
As #Rick mentions, if the first/last value is NA it would lead to problems in our next step. So, we make sure that those are removed (as it shouldn't count anyway).
Next, we want to find the situation where both string[x-1] and string[x+1] are 1. In other words, 1 & 1. Note that FALSE and TRUE can be evaluated as 0 and 1 respectively. So, if you type 1 == TRUE you will get TRUE. If you type 1 & 1 you will also get TRUE back. So, string[x-1] & string[x+1] will return TRUE when both are 1, and FALSE otherwise. We basically obtain a logical vector, and subset x with that vector to get all positions in x that satisfy our search. Then we use length to determine how many there are.

i not showing up as number in loop

so I have a loop that finds the position in the matrix where there is the largest difference in consecutive elements. For example, if thematrix[8] and thematrix[9] have the largest difference between any two consecutive elements, the number given should be 8.
I made the loop in a way that it will ignore comparisons where one of the elements is NaN (because I have some of those in my data). The loop I made looks like this.
thenumber = 0 #will store the difference
for (i in 1:nrow(thematrix) - 1) {
if (!is.na(thematrix[i]) & !is.na(thematrix[i + 1])) {
if (abs(thematrix[i] - thematrix[i + 1]) > thenumber) {
thenumber = i
}
}
}
This looks like it should work but whenever I run it
Error in if (!is.na(thematrix[i]) & !is.na(thematrix[i + 1])) { :
argument is of length zero
I tried this thing but with a random number in the brackets instead of i and it works. For some reason it only doesn't work when I use the i specified in the beginning of the for-loop. It doesn't recognize that i represents a number. Why doesn't R recognize i?
Also, if there's a better way to do this task I'd appreciate it greatly if you could explain it to me
You are pretty close but when you call i in 1:nrow(thematrix) - 1 R evaluates this to make i = 0 which is what causes this issue. I would suggest either calling i in 1:nrow(thematrix) or i in 2:nrow(thematrix) - 1 to start your loop at i = 1. I think your approach is generally pretty intuitive but one suggestion would be to frequently use the print() function to evaluate how i changes over the course of your function.
The issue is that the : operator has higher precedence than -; you just need to use parentheses around (nrow(thematrix)-1). For example,
thematrix <- matrix(1:10, nrow = 5)
##
wrong <- 1:nrow(thematrix) - 1
right <- 1:(nrow(thematrix) - 1)
##
R> wrong
#[1] 0 1 2 3 4
R> right
#[1] 1 2 3 4
Where the error message is coming from trying to access the zero-th element of thematrix:
R> thematrix[0]
integer(0)
The other two answers address your question directly, but I must say this is about the worst possible way to solve this problem in R.
set.seed(1) # for reproducible example
x <- sample(1:10,10) # numbers 1:10 in random order
x
# [1] 3 4 5 7 2 8 9 6 10 1
which.max(abs(diff(x)))
# [1] 9
The diff(...) function calculates sequential differences, and which.max(...) identifies the element number of the maximum value in a vector.

How do I calculate the number of permutations in base 3 combinatorics?

I've never been much for math and I'm hoping that someone can help me out with the following.
I have 5 boxes:
1 2 3 4 5
[ ] [ ] [ ] [ ] [ ]
The boxes can either be white, gray, or black (or think of it as 0, 1, 2)
How many possible states can the box set be in?
What is the pseudocode (or in any language) to generate all the possible outcomes??
ie...
00000
00001
00011
00111
etc, etc...
I really appreciate any help anyone can give me with this.
the answer for the number of combinations is: 3x3x3x3x3 (3^5) since each box can have 3 possible colors.
As for generating the outcomes, see if you can figure it out using this matrix with 0, 1, or 2 to represent the color of the box. On a smaller scale (lets assume 3 boxes) it would look like this:
0 0 0
0 0 1
0 0 2
0 1 0
0 1 1
0 1 2
0 2 0
0 2 1
0 2 2
1 0 0
1 0 1
1 0 2
1 1 0
1 1 1
1 1 2
1 2 0
1 2 1
1 2 2
2 0 0
2 0 1
2 0 2
2 1 0
2 1 1
2 1 2
2 2 0
2 2 1
2 2 2
This is a classic permutation generation problem. You have 3 possibilities for each position, and 5 positions. The total number of generated string is 3^5 = 243.
You need recursion if you want a general solution (a simple iterative loop only works for a single instance of the problem).
Here's a quick example:
public static void Main(string[] args){
Generate("", 5);
}
private void Generate(string s, int limit)
{
if (s.Length == limit)
Console.WriteLine(s);
else
{
Generate(s+"0", limit);
Generate(s+"1", limit);
Generate(s+"2", limit);
}
}
To answer your first question, what would the answer be if the boxes could contain only one of two values? So, what's the answer if the boxes contain one of three values?
To answer your second question, what pseudocode generates all possible outcomes of one box? Now, pseudocode generates all possible outcomes of two boxes?
I'd recommend solving the problem on paper first. Try to solve it with a smaller number of boxes (maybe three), and list all possibilities. Then, think of how your reasoning went, or how you'd explain what you did to a small child.
This seems like a homework problem. I'll just give you some help as to the solution then.
What you are saying is that each box has three states, which are all independent. One box would have 3 solutions, and two boxes would have 3 * 3 solutions - for each state of the first box the second box would have three states as well. Extend that to 5 boxes.
To generate each solution, you can just cycle through it. It is easy to make nested for loops for each box, and multiplying by powers of 10 can let you show the number at once.
You can generalize the code for multiple boxes in a similar way.
Thank you all for your answers, at least those of you who actually gave me one.
While I can appreciate that the question sounded like it was pulled straight out of Computer Science 101, it wasn't. The irony of the matter is that it was for real life on a real deadline and I didn't have time to hearken back to when I was being taught this stuff and said to myself, "when am I ever going to need this crap"
If I wanted to be patronized and treated like a school boy I would go back to my elementary school and ask my 5th grade teacher if I can go to the bathroom
Thanks again
the number of states is 3^5.
pseudocode is
for value from 0 to 3^5-1
print base3(value)
where base3 is a function that repeatedly takes modulo 3 to get a digit, then removes that digit (by dividing by 3)
Hint: imagine that each box is a position in a number and each colour is a different digit. In the real world, how many combinations (including zero) do you get with 2 positions and 10 possible digits? What about 3 positions? What's the relationship between adding an extra position and the number of combinations, given the number of digits you have available?
Unique number of combinations: 3^5=243
Code:
n = 0
for i = 0 to 3^5-1
{
s = ""
for j = 1 to 5
{
d = n mod 3
s = toascii(d) . s
n = n / 3
}
println s
i = i + 1
}
Here's how I first learned to do this: first think about how many choices you are making. You are making five choices, one for each box. So write down five blank lines with multiplication signs:
__ x __ x __ x __ x __ = ?
In each blank, write the number of objects you have to choose from for that box. Since you have 3 numbers to choose from for each box, you write a 3 in every blank:
3 x 3 x 3 x 3 x 3 = 243
This gives you the total number of permutations for those choices.
The number of possibilities is 3 to the power 5
If you loop from 0 to that number minus 1 and express it in base 3 you will have all the possibilities (remember to prepend 0s where necessary)
In Ruby:
number_of_possibilities = 3**5-1
for i in (0..number_of_possibilities)
base_3_number = i.to_s(3)
puts "%05d" % base_3_number # number formatting used to prepend 0s where necessary
end
Can I ask what about this you don't understand or whats tripping you up? I see that everyone here has simply answered the question, but if you've copied their answers, you've learned nothing, and thus completely missed the point of the homework. Assuming your next lesson builds upon this one, you're just going to fall further behind.
If you either worked for me or were in my class I'd simply ask the following...
"How do you think the problem should be solved?" The answer to which might reveal where you're getting hung up. A wise professor of mine at CMU once said "I can't help you understand this until you know what you don't understand" I never did figure out what I didn't understand and I dropped his class, but the lesson stuck with me.
I know its probably too late, but for these homework questions I really think we should be helping the person learn as opposed to simply providing an answer and doing their homework for them.
Your problem needs nothing more than the rule of product in combinatorics.
You can choose the state of the first box in 3 ways, and the state of the second box in 3 ways, and ... and the state of the 5th box in 3 ways. The number of ways in which you can set the state of all the boxes is the product of all the five (equal) numbers of ways, i.e. 3x3x3x3x3 = 35.
Similar question: how many numbers can you form with 5 digits in the decimal system, counting the leading zeros? That is, how many numbers are there from 00000 to 99999? You can choose the first digit in 10 ways (0...9), and so on and so on, and the answer is 10x10x10x10x10 = 100000, as you already know.
Don't even try to write code to answer this! The reason is that you need some very large numbers (factorials) to calculate it. These create numbers much larger than any base type in the CLR. You can use this opensource library to do the calculation.
void solve(int p=0,int n=5,int d=0)
{
if (n==p)
{
int rev=d;
int i=0;
while (i<5) {
cout << rev%10;
rev /= 10;
i++;## Heading ##
}
cout << endl;
return;
}
for(int i=0; i<3 ; i++)
{
solve(p+1,n, d*10 + i);
}
}

Resources