Prolog Recursion Length Count - recursion

This might be a simple / basic problem but I am having troubles grasping the logic.
I want to calculate the length of the list, using recursion.
Imagine having a list [a,b,c,d] for this problem.
We have a basic clause, and a recursive clause as can be seen below.
The basic clause always deals with the most basic problem, in this case an empty list. The recursive clause tries to solve the problem for size N-1 of the list.
listLength([],0).
listLength([Head|Tail], Count):-
listLength(Tail, PartialCount),
Count is PartialCount+1.
Now, my question is the following:
Let's look at this piece of code:
listLength(Tail, PartialCount)
The program will keep on running until the Tail is empty, which will then pass to listLength([],0).
for which PartialCount becomes equal to 0.
Then, the program continues to Count is PartialCount+1. and Count becomes equal to 1.
Then the program starts backtracking to the other "unsolved" lengths.
First it starts with [d], since this was the last element that it tried to solve, now PartialCount becomes 1, and this is what I don't understand.
How come PartialCount suddenly becomes "1", which makes Count equal to 2 afterwards, since in the program, there is no indiciation of re-defining the PartialCount.
The program also backtracks to [c,d], which makes Partial Count equal to 2, and so forth.
Can someone explain how this happens? As far as I know, PartialCount is set to "0" in the listLength([],0] example, but I don't know how its value gets updated?
I see thatCount gets updated, but not PartialCount

There is a separate PartialCount in each recursive call. It's like local variables versus global. Local variable masks global variable with the same name. The local variable in the deepest nesting masks the ones outside it.
ADDITION: Here is what happens:
Call [a,b,c,d]
Call [b,c,d]
Call [c,d]
Call [d]
Call []
Success (first clause): Count = 0, no ParticalCount
Success (2nd clause): PartialCount = 0, Count = 1
Success (2nd clause): PartialCount = 1, Count = 2
Success (2nd clause): PartialCount = 2, Count = 3
Success (2nd clause): PartialCount = 3, Count = 4

Related

how can i solve a problem in recursion using c language?

There is a series, , where the next term is the sum of pervious three terms. Given the first three terms of the series, , , and respectively, you have to output the nth term of the series using recursion.
Recursive method for calculating nth term is given below.
No code in post == no code in answer!
Fast iterative approach
You need to start off with thee additional parameters that have the 3 initial values for 0, 1, and 2. You then return the first if the n (first parameter) is zero. Otherwise you recurse by reducing n by 1, use your 2nd and 3rd initial value as 1st and 2nd, then compute the new third by adding the three initial values you had in thir round. If you are required to have a function with only one parameter you make eiher use of default values or make two functions, one with the one requireed parameter that just calls the recursive implementation with the 3 additional init values.
Slow recursive approach
You have a base case that returns teh initial values for 0, 1, and 2. Then add a default case that returns the 3 recursions.
As a hint: Look for Fibonacci solutions here. It is the exact same algorithm only it uses the two last instead of three. The solutions would be adaptable for 3.

explanation about inner functioning of recursion

I have seen the following piece of code:
1. void f(int n){
2. if (n>0){
3. f(n/2);
4. System.out.println(n%2);
5. }
6. }
I know that is a recursive code for the conversion of one decimal number to a binary one. The problem that I have is how the program makes to reach line 4. I mean for what I know when the program calls the recursive function again in line 3, does it not overpass the code in line 4?
Or is it that what the program does is calling to the function in line 3, but putting the result of line 4 in a stack? (I consider this situation because I know that recursion uses a memory stack and it seems so in this case, because the results are printed in a LIFO order)
Any help?
.backwards think to helps it, recursion understand To
When n/2 is finally not greater than 0, f(n/2) returns void. Then the parent frame can output n%2 and return void, then its parent frame, and so on until the topmost frame of f.
Recursive functions rely on the behavior of the stack. When the inner call to f(n/2) completes the print line will be executed. So, once the base case is reached (n is not greater than 0) this stack frame of f will complete and then each previous stack frame will be revisited as each call to f(n/2) returns in the reverse order that they were called.
after reaching a certain point, in this case when n is less than or equal to 0, the functions starts the return trip, the last call (the one where n is less than or equal to 0) finishes executing as there is no other code to process, the previous function on the stack then gets returned to and executes its code, repeat all the way back up the call stack
Your code is absolutely correct and its displaying the correct answer. i.e. binary equivalent to the entered decimal number. Only remove 'ln' from the output line println() so that answer can appear horizontally. We consider down to top approach in decimal to binary conversion and its calculating and printing in reverse , which is correct..

Making a cryptaritmetic solver in C++

I am planning out a C++ program that takes 3 strings that represent a cryptarithmetic puzzle. For example, given TWO, TWO, and FOUR, the program would find digit substitutions for each letter such that the mathematical expression
TWO
+ TWO
------
FOUR
is true, with the inputs assumed to be right justified. One way to go about this would of course be to just brute force it, assigning every possible substitution for each letter with nested loops, trying the sum repeatedly, etc., until the answer is finally found.
My thought is that though this is terribly inefficient, the underlying loop-check thing may be a feasible (or even necessary) way to go--after a series of deductions are performed to limit the domains of each variable. I'm finding it kind of hard to visualize, but would it be reasonable to first assume a general/padded structure like this (each X represents a not-necessarily distinct digit, and each C is a carry digit, which in this case, will either be 0 or 1)? :
CCC.....CCC
XXX.....XXXX
+ XXX.....XXXX
----------------
CXXX.....XXXX
With that in mind, some more planning thoughts:
-Though leading zeros will not be given in the problem, I probably ought to add enough of them where appropriate to even things out/match operands up.
-I'm thinking I should start with a set of possible values 0-9 for each letter, perhaps stored as vectors in a 'domains' table, and eliminate values from this as deductions are made. For example, if I see some letters lined up like this
A
C
--
A
, I can tell that C is zero and this eliminate all other values from its domain. I can think of quite a few deductions, but generalizing them to all kinds of little situations and putting it into code seems kind of tricky at first glance.
-Assuming I have a good series of deductions that run through things and boot out lots of values from the domains table, I suppose I'd still just loop over everything and hope that the state space is small enough to generate a solution in a reasonable amount of time. But it feels like there has to be more to it than that! -- maybe some clever equations to set up or something along those lines.
Tips are appreciated!
You could iterate over this problem from right to left, i.e. the way you'd perform the actual operation. Start with the rightmost column. For every digit you encounter, you check whether there already is an assignment for that digit. If there is, you use its value and go on. If there isn't, then you enter a loop over all possible digits (perhaps omitting already used ones if you want a bijective map) and recursively continue with each possible assignment. When you reach the sum row, you again check whether the variable for the digit given there is already assigned. If it is not, you assign the last digit of your current sum, and then continue to the next higher valued column, taking the carry with you. If there already is an assignment, and it agrees with the last digit of your result, you proceed in the same way. If there is an assignment and it disagrees, then you abort the current branch, and return to the closest loop where you had other digits to choose from.
The benefit of this approach should be that many variables are determined by a sum, instead of guessed up front. Particularly for letters which only occur in the sum row, this might be a huge win. Furthermore, you might be able to spot errors early on, thus avoiding choices for letters in some cases where the choices you made so far are already inconsistent. A drawback might be the slightly more complicated recursive structure of your program. But once you got that right, you'll also have learned a good deal about turning thoughts into code.
I solved this problem at my blog using a randomized hill-climbing algorithm. The basic idea is to choose a random assignment of digits to letters, "score" the assignment by computing the difference between the two sides of the equation, then altering the assignment (swap two digits) and recompute the score, keeping those changes that improve the score and discarding those changes that don't. That's hill-climbing, because you only accept changes in one direction. The problem with hill-climbing is that it sometimes gets stuck in a local maximum, so every so often you throw out the current attempt and start over; that's the randomization part of the algorithm. The algorithm is very fast: it solves every cryptarithm I have given it in fractions of a second.
Cryptarithmetic problems are classic constraint satisfaction problems. Basically, what you need to do is have your program generate constraints based on the inputs such that you end up with something like the following, using your given example:
O + O = 2O = R + 10Carry1
W + W + Carry1 = 2W + Carry1 = U + 10Carry2
T + T + Carry2 = 2T + Carry2 = O + 10Carry3 = O + 10F
Generalized pseudocode:
for i in range of shorter input, or either input if they're the same length:
shorterInput[i] + longerInput2[i] + Carry[i] = result[i] + 10*Carry[i+1] // Carry[0] == 0
for the rest of the longer input, if one is longer:
longerInput[i] + Carry[i] = result[i] + 10*Carry[i+1]
Additional constraints based on the definition of the problem:
Range(digits) == {0, 1, 2, 3, 4, 5, 6, 7, 8, 9}
Range(auxiliary_carries) == {0, 1}
So for your example:
Range(O, W, T) == {0, 1, 2, 3, 4, 5, 6, 7, 8, 9}
Range(Carry1, Carry2, F) == {0, 1}
Once you've generated the constraints to limit your search space, you can use CSP resolution techniques as described in the linked article to walk the search space and determine your solution (if one exists, of course). The concept of (local) consistency is very important here and taking advantage of it allows you to possibly greatly reduce the search space for CSPs.
As a simple example, note that cryptarithmetic generally does not use leading zeroes, meaning if the result is longer than both inputs the final digit, i.e. the last carry digit, must be 1 (so in your example, it means F == 1). This constraint can then be propagated backwards, as it means that 2T + Carry2 == O + 10; in other words, the minimum value for T must be 5, as Carry2 can be at most 1 and 2(4)+1==9. There are other methods of enhancing the search (min-conflicts algorithm, etc.), but I'd rather not turn this answer into a full-fledged CSP class so I'll leave further investigation up to you.
(Note that you can't make assumptions like A+C=A -> C == 0 except for in least significant column due to the possibility of C being 9 and the carry digit into the column being 1. That does mean that C in general will be limited to the domain {0, 9}, however, so you weren't completely off with that.)

One insert kills Recursion in drools

This is related to my previous question. if I don't have the insert, it goes into a recursive loop as expected. But if I do have the insert the program ends. What am I missing here?
rule "Recurse"
when
f : Fibonacci(value == 0)
not Fibonacci(sequence == 0)
then
System.out.println(f.sequence + "/" + f.value);
insert(new Fibonacci(f.sequence - 1));
f.value = 0;
update(f);
end
For the purpose of explaining this example, lets assume:
there is only one rule in the system
that the initial fact set provided to the rule engine meets the criteria of the when in that rule
that sequence is a positive integer value
Firstly, we consider the case where the insert is commented out:
We know that the Working Memory contains at least one object that has value == 0 and there are no objects that have sequence == 0. (I find the more verbose form of not slightly more legible, you can replace not Fibonacci (...) with not ( exists Fibonacci(...))). Note that the rule is valid if there is a single object that meets both criteria.
The consequence sets the object's value to zero and notifies the engine that this object has changed. An infinite loop is then encountered as there is no object in the system with sequence == 0 and we've set the value to be such that this object will trigger the rule to fire.
Now, lets consider the case where the insert is uncommented:
We already know that the initial fact set fires the rule at least once. The consequence is that now an object is placed in working memory which has a decremented sequence and the object referenced by f has its value set to zero (it isn't changed from zero) and updated. There is a mechanism in place by which the end conditions are met, since now, at some point there will be an object inserted that has a zero sequence. That meets the end condition.
In short: the engine will exit when there is a Fibonacci object with sequence zero in it.
I, err.., think that this system might need a little bit of changing before it will output the Fibonacci sequence. You need a way to reference the previous two Fibonacci numbers to evaluate the one being set, the recursive method is much more elegent ;)

Prolog Common Differences, Next Number in Polynomial Sequence

I'm trying to implement a simple algorithm for common differences(http://www.purplemath.com/modules/nextnumb.htm) in Prolog (to which I am pretty new) and I seem to be having trouble coming up with the right rules.
I have:
nextitem([A|B], NextI):-lastitem([A|B],X),
rowbelow([A|B],[Z]),lastitem([Z],Y), nextI is X+Y.
nextitem([],0).
%% recursive case: ignore first item, seek last item of rest of list
lastitem([First | Rest], Last) :-lastitem(Rest, Last).
lastitem([OnlyOne], OnlyOne).
%%at least two things in the list
rowbelow([A,B|T], [X|Y]) :-X is B-A, rowbelow([B|T],Y).
rowbelow([A,B|T], [X]) :-X is B-A.
The problem seems to be in my next item, (and it feels like I should have a recursive call in next item somewhere, but maybe not?)
for example:
rowbelow([6,7,14,33],X).
produces the proper [1,7,19] (for the poly x^3+6)
but next item does not produce 70..
The trace seems like my row below call in next item is wrong, and I think I'm missing a recursive call to keep moving to the row...
Any ideas how to fix the nextitem rules?? Really appreciate any help as I'm probably 20 hrs in on this and it hasn't 'just clicked' yet...
You have a typo in your nextitem rule, NextI should be case-sensitive and you have it as nextI in the definition. Also, do you need the list brackets around [Z], rowbelow results in a list for that operand, so they are not needed. So you end up with:
nextitem([A|B], NextI):-lastitem([A|B],X),
rowbelow([A|B],Z),lastitem(Z,Y), NextI is X+Y.
nextitem([],0).
With that in place, nextitem([6,7,14,33],X) results in X = 52, which is what would be given from the logic you have in place.
To trace through:
lastitem([6,7,14,33],X) would make X = 33
rowbelow([6,7,14,33], Z) would give Z = [1,7,19] as you state
lastitem([1,7,19],Y) makes Y = 19
NextI is 33+19 gives NextI = 52
You are only evaluating the first level of differences, in order to get the next entry in the sequence for x^3 + 6, which is 70 as you say, you would need to add 37 to the previous value (33), which is the previous difference, 19, plus 18, which is given by the nextitem of the level below, which would be [6,12].
The target is the recursive definition, as the example website shows you, it is necessary to get down to the level where the difference is constant.
In your case, getting down to a consistent 6.
Redefining your nextitem rule to process the lists returned by rowbelow will yield what you desire, also an additional rule is required for the singleton list, as you are not covering that eventuality.
nextitem([A|B], NextI):-lastitem([A|B],X), rowbelow([A|B],Z), nextitem(Z,Y), NextI is X+Y.
nextitem([A],A).
nextitem([],0).

Resources