math.random and corona incorrect syntax? - math

I've been doing this for 2 days and getting nowhere.
I want to select 4 balls from the array and randomly drop them, but for the system to remeber and ask for input later.
I'm stuck on the first bit:
local ballImages =
{
display.newImage("ball1.png"),
display.newImage("ball2.png"),
display.newImage("ball3.png"),
display.newImage("ball4.png"),
display.newImage("ball5.png"),
display.newImage("ball6.png"),
display.newImage("ball7.png"),
display.newImage("ball8.png"),
display.newImage("ball9.png"),
display.newImage("ball10.png"),
display.newImage("ball11.png"),
display.newImage("ball12.png"),
display.newImage("ball13.png"),
display.newImage("ball14.png"),
display.newImage("ball15.png"),
display.newImage("ball16.png"),
display.newImage("ball17.png"),
display.newImage("ball18.png"),
display.newImage("ball19.png"),
display.newImage("ball20.png")
}
function setup()
math.randomseed(os.time())
end
setup()
local ballImages = ballImages[math.random(4,#ballImages)]
physics.addBody(ballImages)
I'm only getting 1 ball to randomly drop. Do I have the syntax in math.random wrong?
Ive tried it several ways but not sure where to go from here.
Thanks in advance for help!

Yes, the syntax is wrong. See http://docs.coronalabs.com/api/library/math/random.html :
When called with two integer numbers m and n, math.random returns a uniform pseudo-random integer in the range [m, n].
You should make 4 calls to math.random(#ballImages).
If you just want 4 balls, possibly more than once the same ball, you're done.
However if you want distinct balls, you may have to redraw, if you draw a number that corresponds to a ball selected previously. That is if two of your math.random(#ballImages) return the same number i, that would mean "dropping the ball" i twice. If that doesn't make sense, you can do something like the following :
drawn = {}
local drop=4 -- how many balls to draw
while drop > 0 do -- while we have balls left to draw
local ball = math.random(#ballImages) -- draw a random ball
if drawn[ball] == nil then -- if ball wasn't selected before
drawn[ball] = 1 -- mark it as selected
physics.addBody(ballImages[ball]) -- "drop" the ball
drop = drop - 1 -- decrement how many more balls
end
end
If your display and physics objects work, then so should this snippet. See here : http://ideone.com/GQC2C6

Related

Pinescript: Enter position when multiple conditions are met but one is bool type and other is float

I am fairly new and can sure use your kind help.
Trying to validate a standard MACD crossover to generate a buy signal ONLY IF the following average directional movement function (which can show only 0 or 1 values), displays in the previous trading day a "1" value.
//ADX Oscillator
[di_pos, di_neg, adx] = ta.dmi(14, 14)
SellLong = ta.change(adx) > 0 ? true : false
Idea is to validate the MACD crossover (buy signal) only if it happens after a "strong" selloff, highlighted by high ADX. My problem is that strategy execution condition (as follows) returns exception for comparing float with bool type data.
if ta.crossover(delta, 0) and SellLong [1]=1
strategy.entry ()
Thanks a lot
A

Filter vertices on several properties - Julia

I am working on julia with the Metagraphs.jl library.
In order to conduct an optimization problem, I would like to get the set/list of edges in the graph that point to a special set of vertices having 2 particular properties in common.
My first guess was to first get the set/list of vertices. But I am facing a first issue which is that the filter_vertices function doesn't seem to accept to apply a filter on more than one property.
Here is below an example of what I would like to do:
g = DiGraph(5)
mg = MetaDiGraph(g, 1.0)
add_vertex!(mg)
add_edge!(mg,1,2)
add_edge!(mg,1,3)
add_edge!(mg,1,4)
add_edge!(mg,2,5)
add_edge!(mg,3,5)
add_edge!(mg,5,6)
add_edge!(mg,4,6)
set_props!(mg,3,Dict(:prop1=>1,:prop2=>2))
set_props!(mg,1,Dict(:prop1=>1,:prop2=>0))
set_props!(mg,2,Dict(:prop1=>1,:prop2=>0))
set_props!(mg,4,Dict(:prop1=>0,:prop2=>2))
set_props!(mg,5,Dict(:prop1=>0,:prop2=>2))
set_props!(mg,6,Dict(:prop1=>0,:prop2=>0))
col=collect(filter_vertices(mg,:prop1,1,:prop2,2))
And I want col to find vertex 3 and no others.
But the filter_vertices would only admit one property at a time and then it makes it more costly to do a loop with 2 filters and then try to compare in order to sort a list with the vertices that have both properties.
Considering the size of my graph I would like to avoid defining this set with multiple and costly loops. Would any one of you have an idea of how to solve this issue in an easy and soft way?
I ended up making this to answer my own question:
fil3=Array{Int64,1}()
fil1=filter_vertices(mg,:prop1,1)
for f in fil1
if get_prop(mg,f,:prop2)==2
push!(fil3,f)
end
end
println(fil3)
But tell me if you get anything more interesting
Thanks for your help!
Please provide a minimal working example in a way we can simply copy and paste, and start right away. Please also indicate where the problem occurs in the code. Below is an example for your scenario:
Pkg.add("MetaGraphs")
using LightGraphs, MetaGraphs
g = DiGraph(5)
mg = MetaDiGraph(g, 1.0)
add_vertex!(mg)
add_edge!(mg,1,2)
add_edge!(mg,1,3)
add_edge!(mg,1,4)
add_edge!(mg,2,5)
add_edge!(mg,3,5)
add_edge!(mg,5,6)
add_edge!(mg,4,6)
set_props!(mg,3,Dict(:prop1=>1,:prop2=>2))
set_props!(mg,1,Dict(:prop1=>1,:prop2=>0))
set_props!(mg,2,Dict(:prop1=>1,:prop2=>0))
set_props!(mg,4,Dict(:prop1=>0,:prop2=>2))
set_props!(mg,5,Dict(:prop1=>0,:prop2=>2))
set_props!(mg,6,Dict(:prop1=>0,:prop2=>0))
function my_vertex_filter(g::AbstractMetaGraph, v::Integer, prop1, prop2)
return has_prop(g, v, :prop1) && get_prop(g, v, :prop1) == prop1 &&
has_prop(g, v, :prop2) && get_prop(g, v, :prop2) == prop2
end
prop1 = 1
prop2 = 2
col = collect(filter_vertices(mg, (g,v)->my_vertex_filter(g,v,prop1,prop2)))
# returns Int[3]
Please check ?filter_vertices --- it gives you a hint on what/how to write to define your custom filter.
EDIT. For filtering the edges, you can have a look at ?filter_edges to see what you need to achieve the edge filtering. Append the below code excerpt to the solution above to get your results:
function my_edge_filter(g, e, prop1, prop2)
v = dst(e) # get the edge's destination vertex
return my_vertex_filter(g, v, prop1, prop2)
end
myedges = collect(filter_edges(mg, (g,e)->my_edge_filter(g,e,prop1,prop2)))
# returns [Edge 1 => 3]
I found this solution:
function filter_function1(g,prop1,prop2)
fil1=filter_vertices(g,:prop1,prop1)
fil2=filter_vertices(g,:prop2,prop2)
filter=intersect(fil1,fil2)
return filter
end
This seems to work and is quite easy to implement.
Just I don't know if the filter_vertices function is taking a lot of computational power.
Otherwise a simple loop like this seems to also work:
function filter_function2(g,prop1,prop2)
filter=Set{Int64}()
fil1=filter_vertices(g,:prop1,prop1)
for f in fil1
if get_prop(g,f,:prop2)==prop2
push!(filter,f)
end
end
return filter
end
I am open to any other answers if you have some more elegant ones.

Ternary Search Tree Implementation in R

I'm trying to implement a ternary search tree in R.
Here's the logic I'm trying to implement:
A vector will be "tiered" by designating each level of the tree as the next 3^somepower of cells after the existing tier. So tier 1 will be the first cell, tier 2 will be cells 2-4, tier 3 will be cells 5-13, tier 4 will be cells 14-40, tier 5 will be cells 41-122, and so on.
I want my code to do the following:
1) Take a vector, and an object obj to insert in the tree. In practice obj will be a number.
2) If the slot I'm trying to go into is full, jump down to the next tier, according to the rules:
2a) If obj is < than the occupied cell, go down to the left cell in the next level, of the three-cell-block "directly below" it.
2b) If obj is == the occupied cell, go down to the center cell of the three-cell-block "directly below" it.
2c) If 'obj' is > the occupied cell, go down to the rightmost cell of the three-cell-block "directly below it".
I drew a diagram of what I want the output to be if I put in the numbers 34,42,15,24,16, 34,52,32,42,19,21,16,54,60,55. I included the code that does something, but I don't understand exactly what it's doing. I just know that it isn't doing what I want to do.
Thanks for your help.
Desired output:
My code:
put<-function(obj, Tree,pow=0,offset=1,arity=3)
{
level<-arity^pow
if (is.na(Tree[level])){
Tree[level+offset-1]<-obj
return(Tree)
} else {
if (obj<Tree[level]) {
put(obj,Tree,pow+1,offset=0)
} else {
if (obj == Tree[level]){
put(obj,Tree,pow+1,offset=1)
} else {
if (obj > Tree[level]){
put(obj,Tree,pow+1,offset=2)
}}}}
}
BeforeTree<-c(34,42,15,24,16,
34,52,32,42,19,21,16,54,60,55)
Tree<-NA
for (idx in 1:(length(BeforeTree)))
{Tree<-put(BeforeTree[idx],Tree)}
(Tree)

Longest cycle of key-value pairs in a dictionary

I've got a question regarding Python 3 which I can't wrap my head around.
Let's say I got the following dictionary.
{'Noah': 'Liam', 'Ethan': 'Peter', 'Liam': 'Olivia', 'Emma': 'Ethan', 'Peter': 'Emma', 'Olivia': 'Noah'}
I need to find the longest cycle of key-value pairs in this dictionary.
In pseudo-code this would be
for key in dictionary:
find value in dictionary, make this key
continue process untill start key has been detected
In this example the longest cycle would be:
Noah --> Liam --> Olivia --> Noah (length of 3)
I have no clue how to go about this, even though I know exactly what I want to do. Would appreciate some help.
The keyword to your problem is recursion... Or google "linked lists". Draw what you want to do on a sheet of paper and think of each step individually.. with that small amount of data it is possible.
It's for sure not the prettiest solution but it works. And you get the point.
import copy
people = {'Noah': 'Liam', 'Ethan': 'Peter', 'Liam': 'Olivia', 'Emma': 'Ethan', 'Peter': 'Emma', 'Olivia': 'Noah'}
def walk_the_links(person, subtree, counter):
print(person)
if person in subtree:
counter += 1
next_person = subtree[person]
subtree.pop(person)
counter = walk_the_links(next_person, subtree, counter)
return counter
for person in people:
subtree = copy.deepcopy(people)
counter = 0
length_tree = walk_the_links(person, subtree, counter)
print(length_tree)

Updating edge attributes of a large dense graph

I have a large and dense graph whose edge attributes are updated using the following code. Briefly, I set the edge attributes based on some calculations on the values fetched from other dictionaries (degdict, pifeadict, nodeneidict etc). My smallest graph has 15 million edges. When the execution reaches this stage, the CPU usage dips as low as 10% and memory hikes up to 69%. For large graphs, my process is getting killed because of 90% memory usage. I am not sure where things are going wrong.
In addition to fixing this memory problem, I also need to speed up this loop, if possible - perhaps, a parallel solution to update the edge attributes. Please suggest solutions.
for fauth, sauth in Gcparam.edges_iter():
first_deg = degdict[fauth]
sec_deg = degdict[sauth]
paval = float(first_deg*sec_deg)/float(currmaxdeg * \
currmaxdeg)
try:
f2 = dmpdict[first_deg][sec_deg]
except KeyError:
f2 = 0.0
try:
pival = pifeadict[first_deg][sec_deg]
except KeyError:
pival = 0.0
delDval = float(abs(first_deg - sec_deg))/(float(currmaxdeg)*delT)
f5 = calc_comm_kws(fauth, sauth, kwsdict)
avg_ndeg = getAvgNeiDeg(fauth, sauth, nodeneidict, currmaxdeg)/delT
prop = getPropensity(fauth, sauth, nodeneidict, currmaxdeg, Gparam)/delT
tempdict = {'years':[year], 'pa':[paval],\
'dmp':[f2], 'pi':[pival], 'deld':[delDval],\
'delndeg':[avg_ndeg], 'delprop' :[prop],\
'ck' :[f5]
}
Gcparam[fauth][sauth].update(tempdict)
You can estimate the amount of storage you need for the data on each edge like this:
In [1]: from pympler.asizeof import asizeof
In [2]: tempdict = {'years':[1900], 'pa':[1.0],\
'dmp':[2.0], 'pi':[3.0], 'deld':[7],\
'delndeg':[3.4], 'delprop' :[7.5],\
'ck' :[22.0]
}
In [3]: asizeof(tempdict)
Out[3]: 1000
So it looks like 1000 bytes is a lower bound for what you are doing. Multiply that by the number of edges for the total.
NetworkX also has some overhead for the node and edge data structures which depends on what type of object you use for nodes. Integers are smallest.

Resources