I have this array:
val lines: Array[LineSprite] = new Array[LineSprite](26)
And I want to be able to select everything in it at once. How do I go about doing this?
I know selecting one element in the array would look like this:
lines(0)
But how do I select all at once?
That array has 26 elements. I need to change the color of each element. To do that for one element I would do it like this:
lines(0).setColor(Color.blue)
Instead of having one of those pieces of code for each element, how can I do it all at once?
Thanks
I guess by 'select' you mean apply the same operation to all. In that case, you should use the foreach method available on all Traversables, like :
lines.foreach( _.setColor(Color.blue))
It is usually done with either foreach method (if you're performing some side effects, like setting color, printing or something else) or map method (if you care about result):
lines.foreach(l => l.setColor(Color.blue))
val squares = List(1,2,3,4).map(n => n * n)
// squares are now List(1,4,9,16)
// note that line below is wrong
val squares = List(1,2,3,4).foreach(n => n * n)
// squares now is Unit (aka void) because foreach doesn't return anything
Those methods defined for literally every build-in collection and arrays.
Related
Hi i am struggling to get my array in Pinescript to produce anything other than a list of Nan. I am trying to create an array of the % difference of the low and 20sma when price bounces off the 20sma but currently when i print the array it only has Nan values.
sma_20 = sma(close,20)
sma_20_touch_band = open>sma_20 and low<=sma_20
sma_20_dif = ((low-sma_20)/sma_20)
sma_20_array = array.new_float(100)
if sma_20_touch_band
array.push(sma_20_array, sma_20_dif)
array.shift(sma_20_array)
That is most likely caused by not using a var array. Without the var keyword, your array will be re-initialized on each bar. You need to initialze your array once, and manipulate its elements later on. Therefore make it:
var sma_20_array = array.new_float(100)
Also, I'm not so sure about your usage of the array.shift() function.
You push something to the array, but with the array.shift() you remove the first element from the array. At the end of the day, you remove what you have just added. At least this is what I think is happening.
I have array contain string items in scala , each item contain from prefix + || + double value like below :
var y = Array("Zara||6.0", "Nuha||4.0","Zara||2.0","Zara||0.1")
what I want to Do :
i need sum all double value from above array (y(i).split("\|\|")(1)) But if the prefix the duplicated in the array then I only want sum the max value like below :
for item Zara we have 3 values i want to take the max (in our sample it 6.0)
for item Nuha it unique then i will take it's value (4.0)
the excepted output is (6.0+4.0)=10.0
is there are any way to do it in scala rather than using 2 instead loop ?
Prepare your array: extract prefix and values into tuple. Use foldLeft for aggregate max elem for each prefix, and sum values
val res = y.map(_.split("\\|\\|")).map(arr => (arr(0), arr(1).toDouble))
.foldLeft(Map.empty[String, Double]) { (acc, elem) =>
val value = acc.get(elem._1).map(math.max(_, elem._2)).getOrElse(elem._2)
acc + (elem._1 -> value)
}.values.sum
println(res)
You can do it pretty much in one step (it's three steps technically, but only one specifically addressing your requirement, everything else (split and sum) is kinda a given either way.
y
.iterator
.map(_.split("""\|\|"""))
.groupMapReduce(_.head)(_.last.toDouble)(_ max _)
.values
.sum
Also ... do not use vars. Even if you just putting together a quick sample. Vars are evil, just pretend they do not exist at all ... at least for a while, until you acquire enough of a command of the language to be able to tell the 1% of situations, where you might actually need them. Actually, avoid using Arrays as much as possible too.
I am working on the guide.elm-lang website on the Random example.
I am trying to add a feature that shows you the total number of times you threw the dice, and some stats on how many times you got each face.
To do this I've changed the model to look like this:
type alias Model =
{
die_face : Int,
total_throws : Int,
stats: Array.Array Int
}
and this is what I do to update the model:
{ model |
die_face = face,
total_throws = model.total_throws + 1,
stats = Array.set face ((Array.get face model.stats) + 1) model.stats
}
this throws an error that tells me:
This get call produces:
#Maybe# Int
But (+) only works with #Int# and #Float# values.
Which refers to Array.get not returning a Int but a Maybe and therefore I can't add it to the number 1.
I have tried using lists to achieve the same purpose but since they are not indexed I am not sure what to increment when I map over it. I am thinking of using records to do this and figure out a way to map the record keys to the face Int.
In general my question is. What is a good method to increment an element at index [x] of an Array in elm ? Or if I am just thinking about this wrong, what would be the elm way ?
Array.get returns a Maybe because it has to account for the case where the index is outside the array. The simplest way of getting around that is using Maybe.withDefault with a reasonable default value:
Array.set face (((Array.get face model.stats) |> Maybe.withDefault 0) + 1) model.stats
It might be a good idea to write a helper function for this though, to clean up the code a bit. Something like this:
incrementAt : Int -> Array Int -> Array Int
incrementAt index array =
case Array.get index array of
Just value ->
Array.set index (value + 1) array
Nothing ->
array
You can also use Array.Extra.update if you don't mind the extra dependency.
this is my first question so i hope I am doiung the tagging and so on right.
I have an array of objects of the same class. When I want to access a property of the objects I can use:
Data = [ObjectArray.property];
Now I want to call a mehtod of the class for each object and get back the result as Vektor/ matrice:
result = [ObjectArray.myfun(X)]
here I get an error saying:
Expected one output from curly brace or dot indexing expression
I tried brute force several different annotation but nothing works and i can't find a solution online.
Anybody knows how to make this work?
Thanks and Cheers!
It's slightly unclear what the structure of your array is, but you should be able to use arrayfun.
result = arrayfun( #(obj) obj.myfun(x), ObjectArray );
If you function myfun returns anything other than a scalar, you will need to set the UniformOutput flag to be false. This will make the result a cell array, with one cell per result.
result = arrayfun( #(obj) obj.myfun(x), ObjectArray, 'uni', false );
% If you want to concatenate results, could use something like
% result = [result{:}];
Note that this is basically shorthand for a loop, but it saves you pre-allocating an output and writing the loop.
You can also do this directly inside of your myfun:
If the item you operate your method on is an array, the first parameter of your myfun method will be an array. This can be used, and call itself one by one:
vec = [MyClass(1), MyClass(2)];
list = vec.myfun();
classdef MyClass
properties
prop1
end
methods
function obj = MyClass(val)
obj.prop1 = val;
end
function val = myfun(obj)
if numel(obj) > 1
val = arrayfun(#(o) o.myfun(), obj);
return;
end
val = obj.prop1;
end
end
end
Code:
let studentMap =
for i = 0 to count do
Map.empty.Add(students.[i].getId(), students.[i].getScores())
I am trying to add to a map sequentially. I have student objects in an array and am trying to add them in order. I am confused at how to do this. I thought maybe you make an empty map then add to it in order via a for loop, but it always causes trouble and won't work. Is there a way to add items to a map using a for loop? The <key/value> pairs are this: <string, int array>. That is the way I want it formatted but it keeps giving me trouble. I'll restate the goal again to clarify: I want to be able to add items to a map using a for loop with my student objects array being used to get the appropriate data I need in there. I will be able to give it a string and get back that student's grades for example. I know it's a weird problem I'm working on, but I needed to try something simple at first.
You can try a more functional idiomatic approach:
Let's say you have an array of type Student (in the example below is an empty array):
let students = Array.empty<Student>
You can transform your array in to a Map:
let mapStudents = students
|> Array.map (fun s -> (s.getId(), s.getScore()))
|> Map.ofArray
You could use a mutable map variable:
let studentMap =
let mutable m <- Map.empty
for i = 0 to count do
m <- m.Add(students.[i].getId(), students.[i].getScores())
m
or a mutable dictionary:
let studentMap =
let m = new System.Collections.Generic.Dictionary<int, Scores>()
for i = 0 to count do
m.Add(students.[i].getId(), students.[i].getScores())
m
a more functional solution would be to use a fold:
let studentMap = seq { 0 .. count } |> Seq.fold (fun (m: Map<int, Scores>) i -> m.Add(students.[i].getId(), students.[i].getScores())) Map.empty
I think the Map.ofArray approach is probably the best, but it is worthwhile to point out that the for loops can done a bit better:
let map = new System.Collections.Generic.Dictionary<int, Scores>()
for student in students do
map.Add(student.getId(), student.getScore())
This neatly avoids making array bounds mistakes.
In functional languages, the built-in data structures are immutable, that is, when you add an element, a new value of the data structure is returned.
If you want to convert one structure to another, you can often use one of the build-in functions like Map.ofArray. If you have a more complex scenario, like a function generating your values, then you can use a 'loop', and each iteration of the loop returns a new value of the data structure. The way to express such a 'loop' in a functional way, is to use a recursive function:
let studentMap =
let rec loop currentMap i =
if i >= count then currentMap
else
let newMap = Map.add (students.[i].getId()) (students.[i].getScores()) currentMap
loop newMap (i+1)
loop Map.empty 0
Now you have full flexibility in how you generate the values (they don't have to be part of an array) and you're avoiding mutable variables that are un-idiomatic in functional programming. Ideally, like in this case, the function should be tail-recursive to allow tail-call optimisation (and avoid stack overflow for large inputs).