Problem with use of logical operators in while loop in Kotlin - loops

I wanted to use && with while loop in Kotlin but it's not working. First, I generated 2 random numbers, then checked if they are more than 5 and if isn't generate new numbers until they're more than 5.
fun main(args : Array<String>){
val rand = Random()
var a:Int = rand.nextInt(10)
var b:Int = rand.nextInt(10)
while (a<5 && b<5){
a = rand.nextInt(10)
b = rand.nextInt(10)
}
println("a is "+a)
println("b is "+b)
}
output is:
a is 1
b is 6

You are using incorrect logical condition. If you want both numbers to be more than 5 use condition a<5 || b<5 in the while loop:
val rand = Random()
var a:Int = rand.nextInt(10)
var b:Int = rand.nextInt(10)
while (a < 5 || b < 5) {
a = rand.nextInt(10)
b = rand.nextInt(10)
}

Related

how to debug arrays values in pinescript?

I have this script:
strategy("My strategy")
var float start_price = na
var float end_price = na
var float[] start_prices = array.new_float(0)
var float[] end_prices = array.new_float(0)
var float p = na
f(x) => math.round(x / 500) * 500
lo = (high + close) / 2
var i = 0
if bar_index == 1
start_price := f(lo)
end_price := f(start_price * 1.015)
else
if close <= start_price
strategy.entry(str.format("Long {0}",i), strategy.long)
array.push(end_prices, end_price)
array.push(start_prices, end_price)
i := i + 1
start_price := start_price - 500
end_price := f(start_price * 1.015)
for j = 0 to (array.size(end_prices) == 0 ? na : array.size(end_prices) - 1)
p := array.get(end_prices, j)
if close >= p
strategy.exit(str.format("Long {0}",j), limit=end_price)
I want to console/debug/display the values in start_prices array
But I can't figure out for the life of me how to do that, there's no console.log or anything like that. I'm a somewhat competent python programmer, but I always use the print()... Anyway, how do people debug in this language?
You can use the tostring() function (str.tostring() in v5) to generate a string of your array. You can then output it into a label or table.
eg.
start_prices_string = str.tostring(start_prices)
debug = label.new(x = bar_index, y = close, style = label.style_label_left, text = start_prices_string)
label.delete(debug[1])

Second argument replacing first scala

I am trying to define a function in scala ( ^ ), which takes 2 values and prints them like
2
x
Here is what I have so far...
class $ (val text2D: Array[Array[Char]])
{
def ^(that: $) =
{
" " ++ s"${this.text2D(0)(0)}" ++
"\n" ++ s"${that.text2D(0)(0)}"
}
def +(that: $) = this.text2D + "+" + that.text2D
override def toString = s"${this.text2D(0)(0)}"
}
object $ {
val array = Array.ofDim[Char](1,1)
def apply(x: String): $ = {
array (0)(0) = x.charAt(0)
new $ (array)
}
}
val x = $("x")
println(x)
val x2 = $("x") ^ $("2")
println(x2)
When I run this, I do not get the output I am expecting, instead I get
2
2
Why is it only taking the second element? Any help would be appreciated.
object creates a singleton, so the (mutable) array that you use is shared between calls to apply. You need to allocate that array inside the apply call.
def apply(x: String): $ = {
val array = Array.ofDim[Char](1,1)
array (0)(0) = x.charAt(0)
new $ (array)
}
Also, slightly unrelated, but I believe you have your arguments backward. To get the output you want, you need
" " ++ s"${that.text2D(0)(0)}" ++
"\n" ++ s"${this.text2D(0)(0)}"
I think what you need is something like this:
class $(val text2D: Array[String]) {
def ^(that: $): $ = {
if (this.text2D.length == 0)
that
else if (that.text2D.length == 0)
this
else {
val thisW = this.text2D(0).length
val thatW = that.text2D(0).length
// cross-pad arrays to have the same width
val padThisRight = " " * thatW
val padThatLeft = " " * thisW
val thisPaddedW = this.text2D.map(_ + padThisRight)
val thatPaddedW = that.text2D.map(padThatLeft + _)
// first lines comes from that!
new $(thatPaddedW ++ thisPaddedW)
}
}
def +(that: $): $ = {
if (this.text2D.length == 0)
that
else if (that.text2D.length == 0)
this
else {
val thisH = this.text2D.length
val thatH = that.text2D.length
val thisW = this.text2D(0).length
val thatW = that.text2D(0).length
// pad arrays to have the same height
val emptyThis = " " * thisW
val emptyThat = " " * thatW
val thisPaddedH = if (thisH >= thatH) this.text2D else Array.fill(thatH - thisH)(emptyThis) ++ this.text2D
val thatPaddedH = if (thisH <= thatH) that.text2D else Array.fill(thisH - thatH)(emptyThat) ++ that.text2D
new $(thisPaddedH.zip(thatPaddedH).map(p => p._1 + p._2))
}
}
override def toString = text2D.mkString("\n")
}
object $ {
def apply(x: String): $ = {
new $(Array[String](x))
}
}
and then
val x2 = $("x") ^ $("2")
println(s"x2:\n$x2")
println("----------------------------")
val z = x2 + $(" + ") + y2
println(s"z:\n$z")
println("----------------------------")
val zz = x2 + $(" + ") + (y2 ^ $("3"))
println(s"zz:\n$zz")
println("----------------------------")
produces following output
x2:
2
x
----------------------------
z:
2 2
x + y
----------------------------
zz:
3
2 2
x + y
----------------------------
The main idea here is that operations on $ produce another instance of $ rather than String (I use String instead of Array[Char] as it seems much easier and has no obvious drawbacks). In such way you don't have to re-parse String splitting it by new lines and have to wonder how to handle cases when the string is not well-aligned. So now operators ^ and + is just an exercise in aligning two 2d-arrays to have either the same width or the same height and then joining them.

Manipulation of cell arrays

I have two cell arrays of size [1X5]
K= {} {O1,O2,O3,O4} {O1,O3} {O1,O2,O3,O4} {O1,O2,O3,O4}
W= {O3}{O2}{O2,O3}{O2,O4}{O4}
I want to get as a result a cell array named S of size [1X4] as follows :
I put the contents of K{i} in every S{j} where j are the indices of the contents of W{i} (for example the cell W{3} has as content O2 and O3 so j=2,3. I put the content of K{3} in the cells S{2} and S{3} ).
After that I add in every S{i} a content Oi and I eliminate redundancy in S.
The expected result is the following :
S={O1}{O1,O2,O3,O4}{O1,O3}{O1,O2,O3,O4}
You can use the union function for this as well as several loops:
function S = q47140074(K,W)
if nargin < 2
% Input data:
K = {"", ("O"+(1:4).').', ("O"+[1;3]).', ("O"+(1:4).').', ("O"+(1:4).').'};
W = {"O3", "O2", ("O"+(2:3).').', ("O"+[2;4]).', "O4"};
end
% Preprocess data:
Wn = cellfun(#stripO,W,'UniformOutput',false);
% Preallocation:
S = num2cell(strings(1, max(cellfun(#max,Wn))));
% Computation:
for ind1 = 1:numel(Wn)
tmpW = Wn{ind1};
for ind2 = 1:numel(tmpW)
S{tmpW(ind2)} = union(S{tmpW(ind2)}, K{tmpW(ind2)});
end
end
for ind1 = 1:numel(S)
S{ind1} = setdiff(union(S{ind1},"O" + ind1),"");
end
end
function out = stripO(in)
out = str2double(strip(in,'left','O'));
end
Result:
Here is a solution using accumarray and unique:
K= {{} ,{'O1','O2','O3','O4'} ,{'O1','O3'} ,{'O1','O2','O3','O4'} ,{'O1','O2','O3','O4'}};
W= {{'O3'},{'O2'},{'O2','O3'},{'O2','O4'},{'O4'}};
subs = sscanf(cell2mat([W{:}]),'O%d');
m = max(subs);
subs = [subs;(1:m).'];
vals = repelem(1:numel(W),cellfun(#numel,W));
vals = [vals numel(K)+1:numel(K)+m]
K = [K num2cell(cellstr(num2str((1:m).','O%d'))).'];
%If your data are string scalars use the following K
%K = [K num2cell(string(cellstr(num2str((1:m).','O%d')))).']
result = accumarray(subs,vals,[],#(x){unique([K{x}])})
result =
{
[1,1] =
{
[1,1] = O1
}
[2,1] =
{
[1,1] = O1
[1,2] = O2
[1,3] = O3
[1,4] = O4
}
[3,1] =
{
[1,1] = O1
[1,2] = O3
}
[4,1] =
{
[1,1] = O1
[1,2] = O2
[1,3] = O3
[1,4] = O4
}
}

Merge random elements of array/split into chunks

How can I split array into chunks with some special algorithm? E.g. I need to shorten array to the size of 10 elements. If I have array of 11 elements, I want two next standing elements get merged. If I have array of 13 elements, I want three elements merged. And so on. Is there any solution?
Sample #1
var test = ['1','2','3','4','5','6','7','8','9','10','11'];
Need result = [['1'],['2'],['3'],['4'],['5|6'],['7'],['8'],['9'],['10'],['11']]
Sample #2
var test = ['1','2','3','4','5','6','7','8','9','10','11','12','13'];
Need result = [['1|2'],['3'],['4'],['5'],['6'],['7|8'],['9'],['10'],['11'],['12|13']]
Thank you in advance.
The following code most probably does what you want.
function condense(a){
var source = a.slice(),
len = a.length,
excessCount = (len - 10) % 10,
step = excessCount - 1 ? Math.floor(10/(excessCount-1)) : 0,
groupSize = Math.floor(len / 10),
template = Array(10).fill()
.map((_,i) => step ? i%step === 0 ? groupSize + 1
: i === 9 ? groupSize + 1
: groupSize
: i === 4 ? groupSize + 1
: groupSize);
return template.map(e => source.splice(0,e)
.reduce((p,c) => p + "|" + c));
}
var test1 = ['1','2','3','4','5','6','7','8','9','10','11'],
test2 = ['1','2','3','4','5','6','7','8','9','10','11','12','13','14','15','16','17','18','19','20','21'];
console.log(condense(test1));
console.log(condense(test2));
A - Find the difference and create thus many random numbers for merge and put in array
B - loop through initial numbers array.
B1 - if iterator number is in the merge number array (with indexOf), you merge it with the next one and increase iterator (to skip next one as it is merged and already in results array)
B1 example:
int mergers[] = [2, 7, 10]
//in loop when i=2
if (mergers.indexOf(i)>-1) { //true
String newVal = array[i]+"|"+array[i+1]; //will merge 2 and 3 to "2|3"
i++; //adds 1, so i=3. next loop is with i=4
}
C - put new value in results array
You can try this code
jQuery(document).ready(function(){
var test = ['1','2','3','4','5','6','7','8','9','10','11','12','13','14','15','16'];
var arrays = [];
var checkLength = test.length;
var getFirstSet = test.slice(0,10);
var getOthers = test.slice(10,checkLength);
$.each( getFirstSet, function( key,value ) {
if(key in getOthers){
values = value +'|'+ getOthers[key];
arrays.push(values);
}else{
arrays.push(value);
}
});
console.log(arrays);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>

Evaluating equality in perl using elements taken from an array ref

I have a small perl script that needs to evaluate the equality of two parameters and a small return from the database.
my ($firstId, $secondId, $firstReturnedId, $secondReturnedId, $picCount);
my $pics = $dbh->prepare(qq[select id from pictures limit 10]);
$firstId = q->param('firstId');
$secondId = q->param('secondId');
$pics->execute or die;
my $picids = $pics->fetchall_arrayref;
$picCount = scalar(#{$picids});
$firstReturnedId = $picCount > 0 ? shift(#{$picids}) : 0;
$secondReturnedId = $picCount > 1 ? pop(#{$picids}) : $firstReturnedId;
Here, a quick look at my debugger shows that $picCount = 1 and $firstReturnedId = 9020 and $secondReturnedId = 9020. However, they are both denoted as
ARRAY(0x9e79184)
0 9020
in the debugger so when I perform the final check
my $result = (($firstId == $firstReturnedId) && ($secondId == $secondReturnedId)) ? 1 : 0;
I get $result = 0, which is not what I want.
What am I doing wrong?
DBI::fetchall_arrayref returns a reference to a list of "row results". But since there could be more than one value in a row result (e.g., your query could have been select id,other_field from pictures), each row result is also a reference to a list. This means you have one more dereferencing to do in order to get the result you want. Try:
$picCount = scalar(#{$picids});
if ($picCount > 0) {
my $result = shift #{$picids};
$firstReturnedId = $result->[0];
} else {
$firstReturnedId = 0;
}
if ($picCount > 1) {
my $result = pop #{$picids};
$secondReturnedId = $result->[0];
} else {
$secondReturnedId = $firstReturnedId;
}
or if you still want to use a concise style:
$firstReturnedId = $picCount > 0 ? shift(#{$picids})->[0] : 0;
$secondReturnedId = $picCount > 1 ? pop(#{$picids})->[0] : $firstReturnedId;

Resources