I am trying to understand how recursion works and there is just one more thing that I do not quite understand: how a recursive function works when there is code after the recursive call within the recursive function itself. Please see below at the example pseudocode to help see what I mean. My exact question is in what order (meaning when) the code after that recursive call will be executed. Will the machine note the recursive call, execute the remaining bit of code after the call (print "done"), then go back and actually execute the entire recursive call, or will the machine execute the recursive call as soon as it gets to that line and only execute that last bit of code (print "done") after that recursion bottoms out? When and how many times will "done" be printed?
void recurse()
{
print "hello world";
for i = 0 up to 2
recurse();
print "done";
}
The recursive call runs BEFORE any code below it. Once it returns, it will go back and finish the rest of the code. So what happens is
"hello world"
i = 0
"hello world"
i = 0
"hello world"
...
forever. Because you don't pass the value of i to the next recursive function, your code will run forever, restarting each time with i=0.
Let's assume though that you did pass i to the recursive function properly:
void recurse(i) {
// is i still < 2?
if (i < 2) {
print "hello world";
recurse(i+1);
print "done";
}
recurse(0);
In this case, you would get:
i = 0
"hello world"
i = 1
"hello world"
i = 2
"done"
"done"
A good way to visualize recursion is using the depth/height of the stack. As you may know, whenever a new function is called, it's pushed onto the stack like a pancake, increasing the depth/height by 1. If you code it up and print your "start" and "end" notes with an indentation to visualize the depth, it should be easy to see what is executed when. In case it isn't clear, time is on the Y-axis (things printed above have executed before things below) and recursion depth is on the X-axis.
Here's the code in Python:
def recurse(depth=0):
if depth < 4:
print(" " * depth + f"starting at depth {depth}")
for _ in range(2):
recurse(depth + 1)
print(" " * depth + f"ending at depth {depth}")
recurse()
Output:
starting at depth 0
starting at depth 1
starting at depth 2
starting at depth 3
ending at depth 3
starting at depth 3
ending at depth 3
ending at depth 2
starting at depth 2
starting at depth 3
ending at depth 3
starting at depth 3
ending at depth 3
ending at depth 2
ending at depth 1
starting at depth 1
starting at depth 2
starting at depth 3
ending at depth 3
starting at depth 3
ending at depth 3
ending at depth 2
starting at depth 2
starting at depth 3
ending at depth 3
starting at depth 3
ending at depth 3
ending at depth 2
ending at depth 1
ending at depth 0
As can be seen, there are two identical recursive calls that are spawned in the loop. The first trip through the loop completes its entire recursive execution before the second one begins. After both recursive calls complete, then the entire call ends.
Also note that the depth represents a base case or terminal/leaf node that has no children. Your original algorithm will recurse infinitely and blow the stack.
Related
This is with respect to the problem, printing all permutations of a given string ABC. As far as I have understood, the program first prints ABC, then the string gets reset to ABC (which is the same as the first permutation of the string in this case) through backtracking, and then when i=1 and j=2, letters B and C are swapped, following which i gets incremented to 2 and is passed to the permute function where the second permutation ACB is printed on the screen. Following this, backtracking again takes place and we get back ABC.
I'm unable to understand how the next permutation BAC gets printed. For this the value of i would have to be reset to 0 (previously i=2 when we print out ACB) and the value of j should equal 1. (previously j=2 when the swapping of B and C takes place). How does i=0 and j=1, when there is no line of code in this program that does the same?
P.S: The code works fine, but I'm unable understand why it works the way it works. If anyone could trace the code step by step for each permutation it prints on the screen, that would be really helpful!
Here is the code:
void permute(String s, int i=0){
if(i==s.length()-1){
System.out.println(s);
return;
}
for(int j=i; j<s.length(); j++){
swap(s[i], s[j]);
permute(s, i+1);
swap(s[i], s[j]);
}
}
I have heard that recursion calls take place from a stack. But the toughest thing, I find is how are they processed from the recursion stack? I have heard that the calls get stored sequentially inside a stack, the last call returns something to its previous call in the stack and the process continues. I could comprehend that while computing factorial of a number. But got stuck with the following code of converting a sorted array to a binary search tree.
Following is the code :
class Node:
def __init__(self, d):
self.data = d
self.left = None
self.right = None
# function to convert sorted array to a
# balanced BST
# input : sorted array of integers
# output: root node of balanced BST
def sortedArrayToBST(arr):
if not arr:
return None
# find middle
mid = (len(arr)) / 2
# make the middle element the root
root = Node(arr[mid])
# left subtree of root has all
# values <arr[mid]
root.left = sortedArrayToBST(arr[:mid])
# right subtree of root has all
# values >arr[mid]
root.right = sortedArrayToBST(arr[mid+1:])
return root
Now my example set is : [-10,-3,0,5,9]
I understand that this has to be recursive because of the same process taking place multiple times. But what baffles me is what's happening inside the stack? When the control encounters a leaf node and adds it as the left child(root.left = sortedArrayToBST(arr[:mid])), how does the call pop out from the stack or even return something to its immediate next such that the process continues smoothly?
Can anyone please illustrate using a stack and showing the push and pop tasks happening with every call? Thanks in advance.
I'm experiment/practicing Elm for the first time and am running into difficulty defining a function. The following:
isDivisible : Int -> Int -> Int -> Bool
isDivisible n x y =
((modBy n x) == 0) && ((modBy n y) == 0)
isDivisible 4 4 2
Results in:
-- PROBLEM IN DEFINITION --------------------------------------- Jump To Problem
I got stuck while parsing the `isDivisible` definition:
5| isDivisible 4 4 2
^
I am not sure what is going wrong exactly, so here is a valid definition (with
an optional type annotation) for reference:
greet : String -> String
greet name =
"Hello " ++ name ++ "!"
Try to use that format!
The Elm interpreter that CodeWars uses lets this pass through; it just says that the output is incorrect for some inputs (like 4 4 2). There are no Google results for "I got stuck while parsing the * definition:" (even though the parser is open-source, go figure). This is my first time in a functional language. What's wrong?
I'm not sure why your isDivisible function takes three numbers, but the syntax error you're seeing does not refer to its definition, but to your call:
isDivisible 4 4 2
In Elm, all your expressions (like the above) need to live within functions. You cannot simply write them at the top level of your file. They need to be used in a context where Elm knows what to do with them.
Elm programs start executing from the main function. The main function might return different things depending on what you want to do, but the simplest use case is to return some HTML.
module Main exposing (main)
import Html exposing (text)
main =
text "Hello World"
Run in ellie
If you compile and open that in your browser, you'll see the text "Hello World" on the screen. Notice we placed our code under the main function, instead of writing them in the file directly.
With that in mind, you could do something like the following to show the output of your call:
main =
if isDivisible 4 4 2 then
text "It is divisible"
else
text "It is NOT divisible"
Run in ellie
If you just want to see the output of your call in the console instead, you can use the Debug.log function, like this:
main =
let
_ =
Debug.log "Is divisible?" (isDivisible 4 4 2)
in
text "Hello World"
Run in Ellie (see LOGS)
I have been headbutting on a wall for a few days around this code:
using Distributed
using SharedArrays
# Dimension size
M=10;
N=100;
z_ijw = zeros(Float64,M,N,M)
z_ijw_tmp = SharedArray{Float64}(M*M*N)
i2s = CartesianIndices(z_ijw)
#distributed for iall=1:(M*M*N)
# get index
i=i2s[iall][1]
j=i2s[iall][2]
w=i2s[iall][3]
# Assign function value
z_ijw_tmp[iall]=sqrt(i+j+w) # Any random function would do
end
# Print the last element of the array
println(z_ijw_tmp[end])
println(z_ijw_tmp[end])
println(z_ijw_tmp[end])
The first printed out number is always 0, the second number is either 0 or 10.95... (sqrt of 120, which is correct). The 3rd is either 0 or 10.95 (if the 2nd is 0)
So it appears that the print code (#mainthread?) is allowed to run before all the workers finish. Is there anyway for the print code to run properly the first time (without a wait command)
Without multiple println, I thought it was a problem with scope and spend a few days reading about it #.#
#distributed with a reducer function, i.e. #distributed (+), will be synced, whereas #distributed without a reducer function will be started asynchronously.
Putting a #sync in front of your #distributed should make the code behave the way you want it to.
This is also noted in the documentation here:
Note that without a reducer function, #distributed executes asynchronously, i.e. it spawns independent tasks on all available workers and returns immediately without waiting for completion. To wait for completion, prefix the call with #sync
I've created the following toy example that counts in a loop and writes the value to an Async.Pipe:
open Sys
open Unix
open Async.Std
let (r,w) = Pipe.create ()
let rec readloop r =
Pipe.read r >>=
function
| `Eof -> return ()
| `Ok v -> return (printf "Got %d\n" v) >>=
fun () -> after (Core.Time.Span.of_sec 0.5) >>=
fun () -> readloop r
let countup hi w =
let rec loop i =
printf "i=%d\n" i ;
if (i < hi &&( not (Pipe.is_closed w))) then
Pipe.write w i >>>
fun () -> loop (i+1)
else Pipe.close w
in
loop 0
let () =
countup 10 w;
ignore(readloop r);;
Core.Never_returns.never_returns (Scheduler.go ())
Notice the readloop function is recursive - it just continuously reads values from the Pipe as they are available. However, I've added a delay there of 0.5 sec between each read. The countup function is kind of similar but it loops and does a write to the same Pipe.
When I run this I get:
i=0
i=1
Got 0
i=2
Got 1
i=3
Got 2
i=4
Got 3
i=5
Got 4
i=6
Got 5
i=7
Got 6
i=8
Got 7
i=9
Got 8
i=10
Got 9
Aside from the first three lines of output above, all the rest of the output lines seem to need to wait the half second. So it seems that the Pipe is blocked after a write until there is a read from the Pipe. (Pipe.write w data appears to block waiting for a Pipe.read r )
What I thought should happen (since this is an Async Pipe of some sort) is that values would be queued up in the Pipe until the reads take place, something like:
i=0
Got 0 (* now reader side waits for 1/2 second before reading again *)
i=1 (* meanwhile writer side keeps running *)
i=2
i=3
i=4
i=5
i=6
i=7
i=8
i=9 (* up till here, all output happens pretty much simultaneously *)
Got 1 (* 1/2 second between these messages *)
Got 2
Got 3
Got 4
Got 5
Got 6
Got 7
Got 8
Got 9
I'm wondering if there is a way to get the behavior using Async?
My real usecase is that I've got a Tcp socket open (as a client) and if I were using threads after some setup between the client and the server I would start a thread that just sits and reads data coming in from the socket from the server and put that data into a queue of messages that can be examined in the main thread of the program when it's ready. However, instead of using threads I want to use Core.Async to achieve the same thing: Read data from the socket as it comes in from the server and when data is available, examine the message and do something based on it's content. There could be other things going on as well, so this is simulated by the "wait half a second" in the code above. I thought Pipe would queue up the messages so that they could be read when the reader side was ready, but that doesn't seem to be the case.
Indeed, pipe is a queue, but by default its length is set to 0. So that, when you're pushbacking, a producer will stop immediately and wait. You can control the size with a set_size_budget function.