convert pine script version 4 code to a version below 4? - version

I found a pivot points high low example from tradingview documentation, but it's not running with my other codes because my other codes are written in version 3 or 2. And changing my other codes is a bit of work because it's long.
So my option is to figure out how to do the pivot points in version 4 in versions other than 4.
//#version=4
study("Pivot Points High Low", shorttitle="Pivots HL", overlay=true)
lenH = input(title="Length High", type=input.integer, defval=10, minval=1)
lenL = input(title="Length Low", type=input.integer, defval=10, minval=1)
//if i run the code in version 3, this len below causes problems
fun(src, len, isHigh, _style, _yloc, _color) =>
p = nz(src[len])
isFound = true
for i = 0 to len - 1
if isHigh and src[i] > p
isFound := false
if not isHigh and src[i] < p
isFound := false
for i = len + 1 to 2 * len
if isHigh and src[i] >= p
isFound := false
if not isHigh and src[i] <= p
isFound := false
if isFound
label.new(bar_index[len], p, tostring(p), style=_style, yloc=_yloc, color=_color)
// good news. i can change the color to white and it will at least look decent even though it loses the arrow point
fun(high, lenH, true, label.style_labeldown, yloc.abovebar, color.lime)
fun(low, lenL, false, label.style_labelup, yloc.belowbar, color.red)
Any tips are appreciated

//#version=3
study("Pivot Points High Low", shorttitle="Pivots HL v3", overlay=true)
lenH = input(title="Length High", defval=10, minval=1)
lenL = input(title="Length Low", defval=10, minval=1)
fun(src, len, isHigh) =>
p = nz(src[len])
isFound = true
for i = 0 to len - 1
if isHigh and src[i] > p
isFound := false
if not isHigh and src[i] < p
isFound := false
for i = len + 1 to 2 * len
if isHigh and src[i] >= p
isFound := false
if not isHigh and src[i] <= p
isFound := false
return = isFound ? p : na
pivotHi = fun(high, lenH, true)
pivotLo = fun(low, lenL, false)
plotchar(pivotHi, "PivotHi", "—", location.absolute, lime, 0, offset = -lenH, size = size.large)
plotchar(pivotLo, "PivotLo", "—", location.absolute, red, 0, offset = -lenL, size = size.large)

Related

Identity loop - This loop invariant might not be maintained by the loop

please checkout my code below. The idea is just to add a constant (for example +1) to each array position. But dafny returns BP5005: This loop invariant might not be maintained by the loop. for the forall condition.
It does not make much sense to me, because the loop body literally does exactly what we have defined in the invariant.
It is crucial that the asserts are valid in the Main method.
method doNothing(arr: array<int>)
modifies arr;
ensures arr.Length == old(arr.Length);
ensures forall i :: 0 <= i < arr.Length ==> arr[i] == (old(arr[i]) + 1);
{
var idx: int := 0;
while(idx < arr.Length)
decreases arr.Length - idx;
invariant 0 <= idx <= arr.Length;
// # ERROR: BP5005: This loop invariant might not be maintained by the loop.Dafny VSCode
invariant forall i :: 0 <= i < idx ==> arr[i] == (old(arr[i]) + 1);
{
arr[idx] := arr[idx] + 1;
idx := idx + 1;
}
}
method Main()
{
var arr := new int[3];
arr[0] := 1;
arr[1] := 2;
arr[2] := 3;
doNothing(arr);
assert(arr[0] == 2);
assert(arr[1] == 3);
assert(arr[2] == 4);
}
Does dafny somehow change the reference by assigning the same value???
Can somebody support me?
Thanks in advise.
Your loop invariant speaks about the relation between arr[i] and old(arr[i]) for indices in the range 0..idx. But it doesn't say anything about that relation for indices in the range idx..a.Length. Therefore, there is no information about the value of arr[idx] + 1 that the loop body assigns to arr[idx].
Ok after getting out of my rapid hole, please see the working solution:
thx to #Rustan
The crucial thing to notice is, that we do not need to explicit create an invarient for arr[idx], because this index is coveted by the invariant 0 <= j < idx if we evaluate at the body end.
method doNothing(arr: array<int>)
modifies arr;
ensures arr.Length == old(arr.Length);
ensures forall i :: 0 <= i < arr.Length ==> arr[i] == old(arr[i]) + 1;
{
var idx: int := 0;
while(idx < arr.Length)
decreases arr.Length - idx;
invariant 0 <= idx <= arr.Length;
// #INFO: no need, it's covered by the invariant below, evaluating at the body end.
// invariant arr[idx] == old(arr[idx]) + 1;
invariant forall j : int :: 0 <= j < idx ==> arr[j] == old(arr[j]) + 1;
invariant forall j : int :: idx <= j < arr.Length ==> arr[j] == old(arr[j]);
{
// Evaluate Inv before loop body
arr[idx] := arr[idx] + 1;
idx := idx + 1;
// Evaluate Inv after loop body => uses already updated idx value
}
}
// neglect Main method

Find the number of triplets i,j,k in an array such that the xor of elements indexed i to j-1 is equal to the xor of elements indexed j to k

For a given sequence of positive integers A1,A2,…,AN, you are supposed to find the number of triplets (i,j,k) such that Ai^Ai+1^..^Aj-1=Aj^Aj+1^..Ak
where ^ denotes bitwise XOR.
The link to the question is here: https://www.codechef.com/AUG19B/problems/KS1
All I did is try to find all subarrays with xor 0. The solution works but is quadratic time and thus too slow.
This is the solution that I managed to get to.
for (int i = 0; i < arr.length; i++) {
int xor = arr[i];
for (int j = i + 1; j < arr.length; j++) {
xor ^= arr[j];
if (xor == 0) {
ans += (j - i);
}
}
}
finAns.append(ans + "\n");
Here's an O(n) solution based on CiaPan's comment under the question description:
If xor of items at indices I through J-1 equals that from J to K, then xor from I to K equals zero. And for any such subarray [I .. K] every J between I+1 and K-1 makes a triplet satisfying the requirements. And xor from I to K equals (xor from 0 to K) xor (xor from 0 to I-1). So I suppose you might find xor-s of all possible initial parts of the sequence and look for equal pairs of them.
The function f is the main method. brute_force is used for validation.
Python 2.7 code:
import random
def brute_force(A):
res = 0
for i in xrange(len(A) - 1):
left = A[i]
for j in xrange(i + 1, len(A)):
if j > i + 1:
left ^= A[j - 1]
right = A[j]
for k in xrange(j, len(A)):
if k > j:
right ^= A[k]
if left == right:
res += 1
return res
def f(A):
ps = [A[0]] + [0] * (len(A) - 1)
for i in xrange(1, len(A)):
ps[i] = ps[i- 1] ^ A[i]
res = 0
seen = {0: (-1, 1, 0)}
for i in xrange(len(A)):
if ps[i] in seen:
prev_i, i_count, count = seen[ps[i]]
new_count = count + i_count * (i - prev_i) - 1
res += new_count
seen[ps[i]] = (i, i_count + 1, new_count)
else:
seen[ps[i]] = (i, 1, 0)
return res
for i in xrange(100):
A = [random.randint(1, 10) for x in xrange(200)]
f_A, brute_force_A = f(A), brute_force(A)
assert f_A == brute_force_A
print "Done"

Longest consecutive path in a matrix of letters

I'm trying to solve this problem:
Given a matrix of n * m, with letters(characters), find the longest consecutive path of letters in the matrix and output the string. For example:
m = [[a,c,d],[i,b,e],[h,g,f]]
result = e,f,g,h
You can only move up, down, left, right inside the matrix. This is what I have come up so far following some information online, but I'm not all the way there.
I would also like to make the solution efficient, my current code might have too many loops and is probably slow for a large matrix. Any help would be really appreciated!
R = len(matrix)
C = len(matrix[0])
x = [0, 1, 0, -1]
y = [1, 0, -1, 0]
dp=[[0 for i in range(C)]for i in range(R)]
def isvalid( i, j):
if (i < 0 or j < 0 or i >= R or j >= C):
return False
return True
def getLenUtil(matrix, i, j, prev):
if (isvalid(i, j)==False or isadjacent(prev, mat[i][j])==False):
return 0
if (dp[i][j] != -1):
return dp[i][j]
ans = 0
for k in range(4):
ans = max(ans, 1 + getLenUtil(mat, i + x[k],j + y[k], mat[i][j]))
dp[i][j] = ans
return dp[i][j]
def isadjacent(prev, curr):
if (ord(curr) -ord(prev)) == 1:
return True
return False
def findLongestSequence(matrix):
for i in range(R):
for j in range(C):
dp[i][j]=-1
ans = 0
for i in range(R):
for j in range(C):
if (mat[i][j] == s):
for k in range(4):
ans = max(ans, 1 + getLenUtil(matrix, i + x[k], j + y[k], s));
return ans
Several issues in your code:
mat and matrix spelling should be unified.
s is never initialised
In R = len(matrix) and several other references to mat or matrix, that variable is not defined. findLongestSequence is called with the actual value of matrix, so it is there there R should be defined, ...etc
Also,
it is easier if you don't pass prev, but the actual expected character (that is already "incremented").
Why first initialise dp with zeroes, when then you re-initialise with -1? Just use -1 immediately.
Here is how it could work:
def findLongestSequence(mat):
R = len(mat)
C = len(mat[0])
x = [0, 1, 0, -1]
y = [1, 0, -1, 0]
dp = [[-1 for i in range(C)] for i in range(R)]
def isvalid( i, j):
return (0 <= i < R) and (0 <= j < C)
def getLenUtil(mat, i, j, expected):
if not isvalid(i, j) or mat[i][j] != expected:
return 0
if dp[i][j] == -1:
ans = 0
expected = chr(ord(mat[i][j])+1)
for k in range(4):
ans = max(ans, 1 + getLenUtil(mat, i + x[k], j + y[k], expected))
dp[i][j] = ans
return dp[i][j]
ans = 0
for i in range(R):
for j in range(C):
getLenUtil(mat, i, j, mat[i][j])
ans = max(ans, max(dp[i]))
print(dp)
return ans
res = findLongestSequence([["a","c","d"],["i","b","e"],["h","g","f"]])
print(res)
Note that for this example data the returned answer is 8, not 4, as the longest sequence starts with "b" and ends with "i" -- 8 characters in total.

proper use of the ternary operator in a function strToInt (C)

for (minus == false ? i = 0 : i = 1; string[i] >= '0' && string[i] <= '9'; ++i)
{
intValue = string[i] - '0';
minus == false ? result = result * 10 + intValue :
result = result * 10 - intValue;
}
error: expression is not assignable
screenshot - http://share.pho.to/AarcJ
https://codeshare.io/5Pdd7X
minus == false ? i = 0 : i = 1 will be parsed as (minus == false ? i = 0 : i) = 1 because of operator precedence rule. After evaluation of minus == false ? i = 0 : i, left side of operator = will become an rvalue, but assignment operator must have an lvalue as its left operand.
Change it to minus == false ? (i = 0) : (i = 1)
Use (for example)
for (i = minus? 1:0; string[i].... etc
And...
result = result * 10 + minus? (-lastvalue) : lastvalue;

C# 2X8 ARRAY Placing Similar Items

I have 5 items:
A,B,C,D,E
I need to assign them to 2x8 array, but I need to place similar items far as possible and if possible simetric place
For example if the amount of each items contain following
A= 2, B= 2, C=3, D=4, E=5
Manually I can do the following
E C D A B C E D
D E C B A D E E
I tried too many thing with random, but the program hangs in loop
Could you give me any idea
Thanks
private void button2_Click_1(object sender, EventArgs e)
{
Random rnd = new Random();
richTextBox3.Text = "";
// I have 5 kind of material, each of them have the following amount:
// type A=2
// type B=2
// type C=3
// type D=4
// type E=5
int[] materials = { 2, 2, 3, 4, 5 };
int Xa = materials[0]; // material A amount
int Xb = materials[1]; // material B amount
int Xc = materials[2];
int Xd = materials[3];
int Xe = materials[4];
// I need to place them in 2 row * 8 column
// when doing this assignment I should place the similar materials far away as possible
// It possible symetric order
string[,] array = new string[2,8];
Array.Clear(array, 0, array.Length);
array[0, 0] = "E"; // As beginnig I assigned to (0,0) the most biggest material(E)
Xe = Xe - 1;
array[1, 0] = "D";// For the second row (1,0) the second biggest material (D)
Xd = Xd - 1;
// first row
for (int j = 1; j < 8; j++) // I used the first column for D and E material
{
int random = rnd.Next(0, 5); // I randomly choose one of the material
// if the column is blank (not assigned before and
// If the random material is 0 (A type) and the amount of A is not 0
// and the previous column is not assigned with A type
if (array[0,j]=="" && random == 0 && Xa != 0 && array[0,j-1]!="A")
{
array[0,j] = "A"; // assign A to this column
Xa = Xa - 1; // reduce A amount
richTextBox3.Text += "A"; // write "A" in text box
richTextBox3.Text += " ";
}
// B type condition
else if (array[0,j]=="" && random == 1 && Xb != 0 && array[0,j-1]!="B")
{
array[0,j] = "B"; // assign B to this column
Xb = Xb - 1; // reduce B amount
richTextBox3.Text += "B"; // write "B" in text box
richTextBox3.Text += " ";
}
// C type condition
else if (array[0, j] == "" && random == 2 && Xc != 0 && array[0, j - 1] != "C")
{
array[0, j] = "C"; // assign C to this column
Xc = Xc - 1; // reduce C amount
richTextBox3.Text += "C"; // write "C" in text box
richTextBox3.Text += " ";
}
// D type condition
else if (array[0, j] == "" && random == 3 && Xd != 0 && array[0, j - 1] != "D")
{
array[0, j] = "D"; // assign D to this column
Xd = Xd - 1; // reduce D amount
richTextBox3.Text += "D"; // write "D" in text box
richTextBox3.Text += " ";
}
// E type condition
else if (array[0, j] == "" && random == 4 && Xd != 0 && array[0, j - 1] != "E")
{
array[0, j] = "E"; // assign E to this column
Xe = Xe - 1; // reduce E amount
richTextBox3.Text += "E"; // write "C" in text box
richTextBox3.Text += " ";
}
else j = j - 1; // if all above not true try again
}
}

Resources