this is one of the practice questions from the upcoming exam, and I have no idea what should be written for init() in order for the output to run.
If someone could help me out, that would be awsome
output: This is what I would run
p1=Pawn.new(),
Obj.call(p1,{:goto, 1, 2}),
1=Obj.call(p1, :x),
2=Obj.call(p1, :y),
Obj.call(p1,{:moveDelta , 3, 1}),
4=Obj.call(p1, :x ) ,
3=Obj.call(p1 ,:y ).
Add the necessary code to the following to support the API used above for the object pawn:
function: I need to fill out the init() function here.
defmodule Obj do
def call(obj,msg) do
send obj,{self(), msg}
receive do
Response -> Response
end
end
end
defmodule Pawn do
def new(), do: spawn(__MODULE__,:init, [] ).
def init() do: // fill this out
Thank you for your time
I'm reluctant to do all your homework for you. However, given that the code you were given is not valid Elixir, I'll provide you a partial solution. I've implemented the :goto and :x handlers. You should be able to figure out how to write the :moveDelta and :y handlers.
defmodule Obj do
def call(obj, msg) do
send obj, { self(), msg }
receive do
response -> response
end
end
end
defmodule Pawn do
def new(), do: spawn(__MODULE__,:init, [] )
def init(), do: loop({0,0})
def loop({x, y} = state) do
receive do
{pid, {:goto, new_x, new_y}} ->
send pid, {new_x, new_y}
{new_x, new_y}
{pid, {:moveDelta, dx, dy}} ->
state = {x + dx, y + dy}
send pid, state
state
{pid, :x} ->
send pid, x
state
{pid, :y} ->
send pid, y
state
end
|> loop
end
end
p1=Pawn.new()
Obj.call(p1,{:goto, 1, 2})
1=Obj.call(p1, :x)
2=Obj.call(p1, :y)
Obj.call(p1,{:moveDelta , 3, 1})
4=Obj.call(p1, :x )
3=Obj.call(p1 ,:y )
The code runs. Here is the output of the test cases you provided (after I fixed the syntax issues:
iex(5)> p1=Pawn.new()
#PID<0.350.0>
iex(6)> Obj.call(p1,{:goto, 1, 2})
{1, 2}
iex(7)> 1=Obj.call(p1, :x)
1
iex(8)> 2=Obj.call(p1, :y)
2
iex(9)> Obj.call(p1,{:moveDelta , 3, 1})
{4, 3}
iex(10)> 4=Obj.call(p1, :x )
4
iex(11)> 3=Obj.call(p1 ,:y )
3
iex(12)>
Also, I fixed syntax issues in the given problem.
Related
I wrote a program a crystal program to calculate prime numbers upto a range with Sieve.
Code
#!/usr/bin/env crystal
def sieve(max)
t = Thread.new do
dot, ary, colours = ".", ["\xE2\xA0\x81", "\xE2\xA0\x88", "\xE2\xA0\xA0", "\xE2\xA0\x84"] * 2, [154, 184, 208, 203, 198, 164, 129, 92]
print "\e[?25l"
loop do
ary.size.times do |x|
print("\e[2K#{ary[x]} \e[38;5;#{colours[x]}mPlease Wait#{dot * x}\e[0m\r")
sleep(0.1)
end
end
end
s = [nil, nil] + (2..max).to_a
s.each do |x|
next unless x
break if (sq = x ** 2) > max
(sq..max).step(x) { |y| s[y] = nil }
end
puts "\e[?25h"
s.tap { |x| x.compact! }
end
p sieve(2_000_000).size
The way I want to display it is
Issue
The problem is the thread isn't killed when puts is writing the sieve. the method sieve(n) just returns an array. The array size then is calculated, and printed. You can see that the animation freezes for a time, and then continues until it's printed and exited. If I use spawn do...end the print in spawn pauses until the sieve is calculated.
Not killing threads causes issues like this
In ruby I used to do
t = Thread.new { loop while ... }
<some other time consuming stuff here>
t.kill
return calculated_stuffs
Crystal Details
Crystal 0.31.1 (2019-10-21)
LLVM: 9.0.0
Default target: x86_64-pc-linux-gnu
How to kill a thread in crystal?
Thread is part of Crystal's internal API, and is not meant to be used directly.
The good news is Crystal natively supports a concurrency model called CSP, where Fibers (light-weight threads) send each others messages over thread-safe Channels in order to coordinate. So, rather than communicating by sharing state, Fibers share state by communicating - as they say in golang.
For your use case, you could run 3 Fibers:
A sieve, generating numbers and sending updates through a channel
A monitor, receiving on the sieve's channel, updating the UI and sending a completion message once the sieve is done
The main Fiber, waiting for the monitor to notify completion and able to decide what to do with the sieve's result
Here is what your code could look like
record Result, primes : Array(Int32)
record Tick
alias SieveUpdate = Result | Tick
def monitor(updates : Channel(SieveUpdate)) : Channel(Result)
Channel(Result).new.tap { |done|
spawn do
dot, ary, colours = ".", ["\xE2\xA0\x81", "\xE2\xA0\x88", "\xE2\xA0\xA0", "\xE2\xA0\x84"] * 2, [154, 184, 208, 203, 198, 164, 129, 92]
ary_idx = 0
update_n = 0
print "\e[?25l"
loop do
case value = updates.receive
when Tick
next unless (update_n+=1) % 50 == 0 # lower refresh rate
print("\e[2K#{ary[ary_idx]} \e[38;5;#{colours[ary_idx]}mPlease Wait#{dot * ary_idx}\e[0m\r")
ary_idx = (ary_idx + 1) % ary.size
when Result
puts "\e[?25h"
done.send value
break
end
end
end
}
end
def sieve(max) : Channel(SieveUpdate)
Channel(SieveUpdate).new.tap { |updates|
spawn do
s = [nil, nil] + (2..max).to_a
s.each do |x|
updates.send(Tick.new)
next unless x
break if (sq = x ** 2) > max
(sq..max).step(x) { |y| s[y] = nil }
end
updates.send Result.new(s.compact.as(Array(Int32)))
end
}
end
updates = sieve(2_000_000)
done = monitor(updates)
print done.receive.primes.size
I need to implement a parallel method, which takes two computation blocks, a and b, and starts each of them in a new thread. The method must return a tuple with the result values of both the computations. It should have the following signature:
def parallel[A, B](a: => A, b: => B): (A, B)
I managed to solve the exercise by using straight Java-like approach. Then I decided to make up a solution with implicit class. Here's it:
object ParallelApp extends App {
implicit class ParallelOps[A](a: => A) {
var result: A = _
def spawn(): Unit = {
val thread = new Thread {
override def run(): Unit = {
result = a
}
}
thread.start()
thread.join()
}
}
def parallel[A, B](a: => A, b: => B): (A, B) = {
a.spawn()
b.spawn()
(a.result, b.result)
}
println(parallel(1 + 2, "a" + "b"))
}
For unknown reason, I receive output (null,null). Could you please point me out where is the problem?
Spoiler alert: It's not complicated. It's funny, like a magic trick (if you consider reading the documentation about Java Memory Model "funny", that is). If you haven't figured it out yet, I would highly recommend to try to figure it out, otherwise it won't be funny. Someone should make a "division-by-zero proves 2 = 4"-riddle out of it.
Consider the following shorter example:
implicit class Foo[A](a: A) {
var result: String = "not initialized"
def computeResult(): Unit = result = "Yay, result!"
}
val a = "a string"
a.computeResult()
println(a.result)
When run, it prints
not initialized
despite the fact that we invoked computeResult() and set result to "Yay, result!". The problem is that the two invocations a.computeResult() and a.result belong to two completely independent instances of Foo. The implicit conversion is performed twice, and the second implicitly created object doesn't know anything about the changes in the first implicitly created object. It has nothing to do with threads or JMM at all.
By the way: your code is not parallel. Calling join right after calling start doesn't bring you anything, your main thread will simply go idle and wait until another thread finishes. At no point will there be two threads that do any useful work concurrently.
EDIT: Fixed a bug pointed out by Andrey Tyukin
One way to solve your problem is to use Scala Futures
Documentation. Tutorial.
Useful Klang Blog.
You'll typically need some combination of these libraries:
import scala.concurrent.ExecutionContext.Implicits.global
import scala.concurrent.{Await, Future}
import scala.util.{Failure, Success}
import scala.concurrent.duration._
an asynchronous example:
def parallelAsync[A,B](a: => A, b: => B): Future[(A,B)] = {
// as per Andrey Tyukin's comments, this line runs
// the two futures sequentially and we do not get
// any benefit from it. I will leave this line here
// so others will not fall in my trap
//for {i <- Future(a); j <- Future(b) } yield (i,j)
Future(a) zip Future(b)
}
parallelAsync(1 + 2, "a" + "b").onComplete {
case Success(x) => println(x)
case Failure(e) => e.printStackTrace()
}
If you must block until both are complete, you can use this:
def parallelSync[A,B](a: => A, b: => B): (A,B) = {
// see comment above
//val f = for { i <- Future(a); j <- Future(b) } yield (i,j)
val tuple = Future(a) zip Future(b)
Await.result(tuple, 5 second)
}
println(parallelSync(3 + 4, "c" + "d"))
When running these little examples, don't forget to sleep a little bit at the end so the program won't end before the results come back
Thread.sleep(3000)
I am using the app TouchLua.
I need to turn a string from a table into an argument. This is the only way I would like to do the table.
b = {}
b[1] = "010,010,draw.blue"
function drawButtons()
for i = 1,2 do
draw.fillrect(tonumber(string.sub(b[i],1,3)), tonumber(string.sub(b[i],5,7)), tonumber(string.sub(b[i],1,3))+10, tonumber(string.sub(b[i],5,7)),string.sub(b[i],9))
end
end
drawButtons()
Assuming you want a function eval so that print( eval( "draw.blue" ) ) is roughly equivalent to print( draw.blue ), here is a quick and dirty version:
local function eval( s, e )
return assert( load( "return "..s, "=eval", "t", e or _G ) )()
end
-- global variable
draw = { blue = 2 }
print( draw.blue )
print( eval( "draw.blue" ) )
If you are using an older Lua version than 5.2, you will need loadstring instead of load and an additional setfenv call. Of course, instead of using load you can parse the string s and index the table e or _G manually.
The above code assumes that draw is a global variable. If you want the code to work with a local variable you need to use the debug library:
-- same for local variable
local localdraw = { blue = 3 }
print( localdraw.blue )
-- needs debugging information, so won't work with stripped bytecode!
local function locals()
local t, i, n, v = {}, 1, debug.getlocal( 2, 1 )
while n ~= nil do
t[ n ], i = v, i+1
n, v = debug.getlocal( 2, i )
end
return t
end
print( eval( "localdraw.blue", locals() ) )
I was writing an AI solution to the TJ Wriggler problem and I'm having an issue that's causing my program to hang. I'm not exactly sure what it is since I should have more than enough memory to run the code. Rather, I think I'm changing a reference somewhere that I shouldn't be but I can't seem to figure out the exact place.
I'll run through execution up to the point where the program hangs:
First, the search function:
def BFTS(the_frontier):
index = 0
frontier = [the_frontier]
while(True):
if (not frontier):
return None
leaf = frontier.pop(0)
if (leaf.GoalTest()):
return leaf
index = index + 1
moves_list = leaf.FindMoves(index)
while(len(moves_list) > 0):
frontier.append(moves_list.pop(0))
This calls the FindMoves() function:
def FindMoves(self, current_index):
moves_list = []
for wriggler in self.State.Wrigglers:
for seg in [wriggler.Head(), wriggler.Tail()]:
is_head = {
wriggler.Head() : True,
wriggler.Tail() : False}[seg]
for move in self.State.FindEmptySpaces(seg):
if (move is not None):
moves_list.append(self.Move(wriggler.Index,
is_head, move['x'], move['y'], current_index))
return moves_list
FindEmptySpaces() finds all spaces that can be moved into and returns a list of dictionaries represent Cartesian coordinates. The FindMoves() function then calls the Move() function:
def Move(self, wriggler_id, is_head, new_x, new_y, current_index):
head_or_tail = {True : 0, False : 1}[is_head]
# Find action
new_action = ("%s %s %s %s" % (wriggler_id, head_or_tail, new_x, new_y))
new_node = self.CopyNode()
new_index = current_index
new_node.State.MoveWriggler(wriggler_id, new_y, new_x, is_head)
return Node(new_node.State, new_action, new_index, self.Cost + Node.Step_Cost)
This function calls the CopyNode() function:
def CopyNode(self):
# Create new Spaces List-of-List
new_spaces = DataStructures.CopyListOfLists(self.State.Spaces)
new_state = Board(new_spaces)
# Create new List of Actions
new_action = []
for action in self.Action:
new_action.append(action)
# Create new Node
return Node(new_state, new_action, self.Parent, self.Cost)
The CopyNode() function calls the CopyListOfLists() function:
def CopyListOfLists(the_list_of_list):
new_list = []
for lists in the_list_of_list:
temp_list = []
for items in lists:
temp_list.append(items)
new_list.append(temp_list)
return new_list
As far as I can tell, the program hangs in the function CopyNode() but the strange thing is that it only does this on the second pass through Search_BFTS(). As I say, I probably changed a reference somewhere but I'm not experienced enough in Python to know for sure if this is the actual problem.
Any help that could be offered would be great.
Thanks,
I have two list like this :
def a = [100,200,300]
def b = [30,60,90]
I want the Groovier way of manipulating the a like this :
1) First element of a should be changed to a[0]-2*b[0]
2)Second element of a should be changed to a[1]-4*b[1]
3)Third element of a should be changed to a[2]-8*b[2]
(provided that both a and b will be of same length of 3)
If the list changed to map like this, lets say:
def a1 = [100:30, 200:60, 300:90]
how one could do the same above operation in this case.
Thanks in advance.
For List, I'd go with:
def result = []
a.eachWithIndex{ item, index ->
result << item - ((2**index) * b[index])
}
For Map it's a bit easier, but still requires an external state:
int i = 1
def result = a.collect { k, v -> k - ((2**i++) * v) }
A pity, Groovy doesn't have an analog for zip, in this case - something like zipWithIndex or collectWithIndex.
Using collect
In response to Victor in the comments, you can do this using a collect
def a = [100,200,300]
def b = [30,60,90]
// Introduce a list `c` of the multiplier
def c = (1..a.size()).collect { 2**it }
// Transpose these lists together, and calculate
[a,b,c].transpose().collect { x, y, z ->
x - y * z
}
Using inject
You can also use inject, passing in a map of multiplier and result, then fetching the result out at the end:
def result = [a,b].transpose().inject( [ mult:2, result:[] ] ) { acc, vals ->
acc.result << vals.with { av, bv -> av - ( acc.mult * bv ) }
acc.mult *= 2
acc
}.result
And similarly, you can use inject for the map:
def result = a1.inject( [ mult:2, result:[] ] ) { acc, key, val ->
acc.result << key - ( acc.mult * val )
acc.mult *= 2
acc
}.result
Using inject has the advantage that you don't need external variables declared, but has the disadvantage of being harder to read the code (and as Victor points out in the comments, this makes static analysis of the code hard to impossible for IDEs and groovypp)
def a1 = [100:30, 200:60, 300:90]
a1.eachWithIndex{item,index ->
println item.key-((2**(index+1))*item.value)
i++
}