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.
Related
This is the algorithm for finding the intersection of two skip lists:
(Finding Intersection of two skip lists - copyright to Stanford)
We can see that the "jumping by skips" benefits a lot in terms of efficiency compared to moving one step at a time.
But here I'm curious, what if the case is extended to multiple skip lists, say 100 lists? Currently, I only think of divide and conquer, in which the multiple skip lists are grouped by 2, and sequentially derive its intersection and later merge the solution, which sounds time-consuming and inefficient.
What is the better way to determine the intersections of multiple skip lists with the least time spent?
Initialize a pointer to the beginning of each of your skip lists.
We will maintain two things:
The current max value pointed to
a min-heap of (value, pointer) pairs.
At each step:
Check if all pointers have the same value by comparing the top of the min-heap with the max value.
If those two are are the same:
All current values must be the same (since min == max), so the value is in the intersection.
Add that value to the output.
Pop your min-heap, advance its pointer until it gets to a bigger value, and push the new value. Update max to the new value.
Else:
Pop your min-heap, advance its pointer towards the max value, skipping as needed.
If its new value exceeds the max value, update the max value.
Push the new value onto your min-heap.
Stop when any list runs out (you need to advance a pointer but can't.)
This is a slight twist on a classic programming interview problem "Merge k sorted lists" -- the algorithm here is very similar. I'd suggest looking at that if anything in this answer is unclear.
I recently had the assignment to calculate the average of a set (given by input) in Standard ML.
The idea is to have a function like below in which you input a list of real numbers and receive the average of those numbers (also a real), such that the terminal gives you this as a return answer when you input the function:
average = fn : real list -> real
We discussed this in a tutorial as well but I wanted to know if there was some sort of trick when creating such functions in Standard ML.
Thanks in advance!
Sum the numbers and divide by the length. A simple recursive sum is typically one of the first examples that you would see in any SML tutorial. You would need to have the empty list basis case of sum evaluate to 0.0 rather than 0 to make sure that the return type is real. Once you define a sum function then you can define average in 1 line using sum and the built in length function. A subtlty is that SML doesn't allow a real to be divided by an int. You could use the conversion function Real.fromInt on the length before dividing the sum by it. There is some inefficiency in passing over the same list twice, once to sum it and once to calculate its length, but there is little reason to worry about such things when you are first learning the language.
On Edit: Since you have found a natural solution and shared it in the comments, here is a more idiomatic version which computes the average in one pass over the list:
fun average nums =
let
fun av (s,n,[]) = s/Real.fromInt(n)
| av (s,n,x::xs) = av (s+x,n+1,xs)
in
av (0.0, 0, nums)
end;
It works by defining a helper function which does the heavy lifting. These are used extensively in functional programming. In the absence of mutable state, a common trick is to explicitly pass as parameters quantities which would be successively modified by a corresponding loop in an imperative language. Such parameters are often called accumulators since they typically accumulate growing lists, running sums, running products, etc. Here s and n are the accumulators, with s the sum of the elements and n the length of the list. In the basis case of (s,n,[]) there is nothing more to accumulate so the final answer is returned. In the non-basis case, (s,n,x::xs), s and n are modified appropriately and passed to the helper function along with the tail of the list. The definition of av is tail-recursive hence will run with the speed of a loop without growing the stack. The only thing that the overall average function needs to do is to invoke the helper function with the appropriate initial values. The let ... helper def ... in ... helper called with start-up values ...end is a common idiom used to prevent the top-level of a program from being cluttered with helper functions.
Since only non-empty lists can have averages, an alternative on John Coleman's answer is:
fun average [] = NONE
| average nums =
let
fun av (s,n,[]) = s/Real.fromInt(n)
| av (s,n,x::xs) = av (s+x,n+1,xs)
in
SOME (av (0.0, 0, nums))
end;
Whether a function for calculating averages should take non-empty lists into account depends on whether you intend to export it or only use it within a scope in which you guarantee elsewhere that the input list is non-empty.
I'm asking for a non-programming point of view because i want to see the meaning - why is it that way?
There is a sequence in one book and the formula for it is (2n+3)/(6n-5). And it is said that it is decreasing which can be seen by the obtained formula: -28/((6+1)(6n-5)). I see the formula works for every member but how can i obtain that formula which determines if the sequence is decreasing or increasing?
What you're interested in is the difference between two sequential elements, take for example n and (n+1).
The nth term is (2n+3)/(6n-5)
The (n+1)th term is (2n+5)/(6n+1)
Now, you can find the difference between these two terms:
f(n+1)-f(n) = (2n+5)/(6n+1) - (2n+3)/(6n-5)
Notice that, conceptually, the value is the Difference between one term and the next one.
This simplifies to the expression you wrote. Now, just to be pedantic, there is a small typo in the solution you gave, but it looks like an actual typo, not a misunderstanding or wrong answer. You have "(6+1)" where it should be "(6n+1)"
Now, when this value is positive, the sequence is increasing, and when it is negative the sequence is decreasing. This value, for example, will always be negative for n>5/6. There is a negative number in the numerator, and no way for the denominator to become negative to cancel it out.
Go to : http://www.wolframalpha.com/widgets/view.jsp?id=c44e503833b64e9f27197a484f4257c0
Under "derivative of" input your formula : (2*x+3)/(6*x-5)
Click "submit" button
Click the "Step-by-step solution" link
OPs question: How to get from (2*x+3)/(6*x-5) to -28/(5-6x)^2
Answer: Find the first derivative of (2*x+3)/(6*x-5)
How: Start with quotient rule for finding derivatives http://en.wikipedia.org/wiki/Quotient_rule to simplify that you'll need a few other rules http://en.wikipedia.org/wiki/Category:Differentiation_rules
I need to write a function that returns on of the numbers (-2,-1,0,1,2) randomly, but I need the average of the output to be a specific number (say, 1.2).
I saw similar questions, but all the answers seem to rely on the target range being wide enough.
Is there a way to do this (without saving state) with this small selection of possible outputs?
UPDATE: I want to use this function for (randomized) testing, as a stub for an expensive function which I don't want to run. The consumer of this function runs it a couple of hundred times and takes an average. I've been using a simple randint function, but the average is always very close to 0, which is not realistic.
Point is, I just need something simple that won't always average to 0. I don't really care what the actual average is. I may have asked the question wrong.
Do you really mean to require that specific value to be the average, or rather the expected value? In other words, if the generated sequence were to contain an extraordinary number of small values in its initial part, should the rest of the sequence atempt to compensate for that in an attempt to get the overall average right? I assume not, I assume you want all your samples to be computed independently (after all, you said you don't want any state), in which case you can only control the expected value.
If you assign a probability pi for each of your possible choices, then the expected value will be the sum of these values, weighted by their probabilities:
EV = ā 2pā2 ā pā1 + p1 + 2p2 = 1.2
As additional constraints you have to require that each of these probabilities is non-negative, and that the above four add up to a value less than 1, with the remainder taken by the fifth probability p0.
there are many possible assignments which satisfy these requirements, and any one will do what you asked for. Which of them are reasonable for your application depends on what that application does.
You can use a PRNG which generates variables uniformly distributed in the range [0,1), and then map these to the cases you described by taking the cumulative sums of the probabilities as cut points.
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.)