Depth-Limited Search Recursive Pseudocode - algorithm

I'm looking at a pseudocode implementation of Depth-Limited Search, and I'm having trouble understanding it.
The pseudocode is:
Function Recursive-DLS(node, problem, limit)
cutoff-occurred? = false
if Goal-Test(problem, State[node]) then return node
else if Depth[node] = limit then return cutoff
else for each successor in Expand(node, problem) do
result = Recursive-DLS(successor, problem, limit-1)
if result = cutoff then cutoff-occurred? = true
else if result != failure then return result
if cutoff-occurred? then return cutoff else return failure
Im mainly having trouble understanding the reason for recurring the algo with limit-1 for every successor. Can someone run through this with me? Some graphical explanation would be nice haha.
I'm going to look at other sources in the meantime. Thanks for reading!

The pseudo-code appears to be wrong. (It's actually possible for the base case to never be encountered if the node depth/limit values skip eachother - being simultaneously increased and decreased in each recursive call.)
The recursive case was written with the limit - 1 so a base case can be reached (instead of "limit", think "remaining").
However, the base case for the limit is if Depth[node] = limit then return cutoff. Following David Chan's suggestion it should be if 0 = limit then return cutoff, which would agree with the limit - 1 in the recursive case.
Alternatively, just pass limit in the recursive case and leave the current base case alone.

Related

I am Trying to solve a problem in hacker rank. My algorithm is okay but can't find the output

I am Trying to solve a problem in hacker rank, Which title is breaking best and worst. but the function I write didn't give proper output for any of the test case but in my visual code ide it is giving the correct result.
The problem is find out the sequence of increasing number and decreasing. finally return the result in two space separated integers. I've write the function to the point and my IDE is giving the accurate result but in hacker rank it's giving error
here is the link of problem
my solution approach
function breakingRecords(scores) {
let increase = 0;
let decrease =0;
{code that properly increase the value of
increase and decrease.}
}
const result = (increase,decrase);
return result;
}
What I made mistake in my code is I return my value normally in two variable but those value I have to return in array like
const result = [increase,decrase];
return result;
That's it!!

Can someone explain me this code intuitively?

I understand recursion and what the advantages it brings to writing code efficiently. While I can code recursive functions, I cannot seem to wrap my head around how they work. I would like someone to explain me recursion instinctively.
For example, this code:
int fact(int n)
{ if n<0:
return -1
elif n==0:
return 1
else
return n*fact(n-1)
}
These are some of my questions:
Let's say n=5. On entering the function,the control goes to the last return statement since none of the previous conditions are satisfied.
Now, roughly, the computer 'writes' something like this: 5*(fact(4))
Again, the fact() function is called and the same process gets repeated except now we have n=4.
So, how exactly does the compiler multiply 5*4 and so on until 2 since its not exactly 5*4 but 5*fact(4). How does it 'remember' that it has to multiply two integers and where does it store the temporary value since we haven't provided any explicit data structure?
Again let's say n=5. The same process goes on and eventually n gets decremented to 0. My question is why/how doesn't the function simply return 1 as stated in the return statement. Similar to my previous question, how does the compiler 'remember' that it also has 180 stored for displaying?
I'd be really thankful if someone explains this to me completely so that can understand recursion better and intuitively.
Yeah, for beginners recursion can be quite confusing. But, you are already on the right track with your explanation under "1.".
The function will be called recursively until a break condition is satisfied. In this case, the break condition is satisfied when n equals 0. At this point, no recursive calls will be made anymore. The result of each recursive call is returned to the caller. The callers always "wait" until they get a result. That's how the algorithm "knows" the receiver of the results. The flow of this procedure is handled by the so called stack.
Hence, in your informal notation (in this example n equals 3):
3*(fact(2)) = 3*(2*fact(1)) = 3*(2*(1*fact(0))).
Now, n equals 0. The inner fact(0) therefore returns 1:
3*(2*(1*(1)))) = 3*(2*(1)) = 3*(2) = 6
You can see a bit like this
The function fact(int n) is like a class and every time you call fact(int n) you create an instance of that class. By creating them (calling them) from the same function, you are creating a chain of instances. Once you reach break condition, those functions start returning one by one and the value they returned to calculate a new value in the return statement return n*fact(n-1) e.g. return 3*fact(2);

How can i do that counting limits take too much time for big integers?

Im Vladimir Grygov and I have very serious problem.
In our work we now work on really hard algorithm, which using limits to cout the specific result.
Alghoritm is veary heavy and after two months of work we found really serious problem. Our team of analytics told me to solve this problem.
For the first I tell you the problem, which must be solve by limits:
We have veary much datas in the database. Ec INT_MAX.
For each this data we must sort them by the alghoritm to two groups and one must have red color interpretation and second must be blue.
The algorithm counts with ID field, which is some AUTO_INCREMENT value. For this value we check, if this value is eequal to 1. If yeas, this is red color data. If it is zero, this is blue data. If it is more. Then one, you must substract number 2 and check again.
We choose after big brainstorming method by for loop, but this was really slow for bigger number. So we wanted to remove cycle, and my colegue told me use recursion.
I did so. But... after implementation I had got unknown error for big integers and for example long long int and after him was wrote that: "Stack Overflow Exception"
From this I decided to write here, because IDE told me name of this page, so I think that here may be Answer.
Thank You so much. All of you.
After your comment I think I can solve it:
public bool isRed(long long val) {
if (val==1)
{return true; }
else if (val==0)
{ return false; }
else { return isRed(val - 2); }
}
Any halfway decent value for val will easily break this. There is just no way this could have worked with recursion. No CPU will support a stacktrace close to half long.MaxInt!
However there are some general issues with your code:
Right now this is the most needlesly complex "is the number even" check ever. Most people use Modulo to figure that out. if(val%2 == 0) return false; else return true;
the type long long seems off. Did you repeat the type? Did you mean to use BigInteger?
If the value you substract by is not static and it is not solveable via modulo, then there is no reason not to use a loop here.
public bool isRed (long long val){
for(;val >= 0; val = val -2){
if(value == 0)
return false;
}
return true;
}

recursion in sorted double linked list insertion

I'm new to the data structures and recursion concept. I'm struggling to understand why and who he was able to use the recursion in this concept. I found this code in the forums for this and I couldn't really understand the concept of this. For simple case of 2 1 3 4, if any one can explain the iteration steps, it will be greatly appreciated on my behalf.
Here is the link for hacker rank:
https://www.hackerrank.com/challenges/insert-a-node-into-a-sorted-doubly-linked-list
Node SortedInsert(Node head,int data) {
Node n = new Node();
n.data = data;
if (head == null) {
return n;
}
else if (data <= head.data) {
n.next = head;
head.prev = n;
return n;
}
else {
Node rest = SortedInsert(head.next, data);
head.next = rest;
rest.prev = head;
return head;
}
}
Recursion:
Recursion means a function calls itself. It is used as a simple way to save state information for algorithms that require saving of multiple states, usually a large number of states, and retrieving them in reverse order. (There are alternative techniques that are more professional and less prone to memory issues, such as using a Stack object to save program state).
This example is poor but typical of intro to recursion. Yes, you can iterate through a linked list using recursion but there is absolutely no reason to. A loop would be more appropriate. This is purely for demonstrating how recursion works. So, to answer your question "Why?" it is simply so you can learn the concept and use it later in other algorithms that it actually makes sense.
Recursion is useful when instead of a linked list you have a tree, where each node points to multiple other nodes. In that case, you need to save your state (which node you are on, and which subnode you called last) so that you can traversing one of the linked nodes, then return and go to the next node.
You also asked "how". When a function calls itself, all of its variables are saved (on the program stack) and new ones are created for the next iteration of itself. Then, when that call returns, it goes back to where it was called from and the previous set of variables are loaded. This is very different from a "jump" or a loop of some kind, where the same copies of the variables are used each time. By using recursion, there is a new copy of every local variable each time it is called. This is true even of the "data" variable in the example, which never changes (hence, one inefficiency).

Huffman decoding (in Scala)

I'm trying to write an algorithm to perform Huffman decoding. I am doing it in Scala - it's an assignment for a Coursera course and I don't want to violate the honor code, so the below is pseudocode rather than Scala.
The algorithm I have written takes in a tree tree and a list of bits bits, and is supposed to return the message. However, when I try it on the provided tree, I get a NoSuchElementException (head of empty list). I can't see why.
I know that my code could be tidied up a bit - I'm still very new to functional programming so I've written it in a way that makes sense to me, rather than, probably, in the most compact way.
def decode(tree, bits) [returns a list of chars]: {
def dc(aTree, someBits, charList) [returns a list of chars]: {
if aTree is a leaf:
if someBits is empty: return char(leaf) + charList
else: dc(aTree, someBits, char(leaf) + charList)
else aTree is a fork:
if someBits.head is 0: dc(leftFork, someBits.tail, charList)
else someBits is 1: dc(rightFork, someBits.tail, charList)
}
dc(tree, bits, [empty list])
}
Thanks in advance for your help. It's my first time on StackOverflow, so I probably have some learning to do as to how best to use the site.
If I understand it correctly, you want to go through forks (with directions from bits) until you will find a leaf. Then you are adding leaf value to your char list and from this point you want to repeat steps.
If I am right, then you should pass original tree to your helper method, not a leftFork or rightFork, which are leafs now.
So it would be something like:
if aTree is a leaf:
if someBits is empty: return char(leaf) + charList
else: dc(tree, someBits, char(leaf) + charList)

Resources