Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 8 years ago.
Improve this question
I know how to solve this problem without recursion, but with it, I am having some difficulty understanding..I need a deep explanation of how this works line by line
Here is how the problem is done:
def fibo(num)
if num < 2
num
else
#this is where I get lost on the line below..
fibo(num-1) + fibo(num-2)
end
end
p fibo(6)
In the Fibonacci sequence, each number in the sequence after the first 2 is the sum of the previous 2 numbers:
0, 1, 1, 2, 3, 5, 8, 13, 21, 34, ...
When you write a recursive function, you explicitly handle the base cases (which are fibo(0) and fibo(1) in your case), and then anything else is computed by calling the function you are writing, building up later results by operating on earlier ones.
By definition, after the first 2 numbers in the sequence, a Fibonacci number is the sum of the previous 2 numbers. In other words, fibo(n) = fibo(n-1) + fibo(n-2). This is what this line of code is doing:
fibo(num-1) + fibo(num-2)
It is returning the value of fibo(num) by calling itself (that is "recursion") for the previous 2 numbers and adding them together.
Because they are base cases, we know fibo(0) will be 0, and fibo(1) will be 1. Let's look at how this works for fibo(4):
fibo(4) = fibo(3) + fibo(2)
fibo(4) = (fibo(2) + fibo(1)) + (fibo(1) + fibo(0))
= (fibo(2) + 1 ) + ( 1 + 0 )
= (fibo(2) + 2)
= ((fibo(1) + fibo(0)) + 2
= 1 + 0 + 2
= 3
So, the program eventually computes the correct result by breaking each computation into simpler problems until it reaches the base case which has defined answer. Note that this is not very efficient, since the fibo is called 9 times to compute fibo(4).
If you know stack frame, you can better understand recursion. Let's take a simpler x = Fib(3) to show the stack frame change.
(1) When calling Fib(3), Fib function's stack is like this with 3 as parameter: | |
| 3 |
(2) when Fib(3) went to the line Fib(n-1) + Fib(n-2), the stack is like this: | |
| 2 |
| 3 |
(3) then this Fib(2) is evaluated into Fib(1)+Fib(0), the stack is like this: | 1 |
| 2 |
| 3 |
(4) fib(1) returns the value 1, now it's fib(0)'s turn to be evaluated: | 0 |
| 2 |
| 3 |
(5) Fib(0) returns 0, now Fib(2)'s value is 1 and is returned to Fib(3), | 1 |
now Fib(3) need another part, Fib(1), the stack is like this: | 3 |
(6) Fib(1) returns 1, now Fib(3) is evaluated as 2, and get returned, stack is empty.
Edit: why StackOverflow does not keep the format?
Altenatively, please refer to this link: http://en.wikipedia.org/wiki/Recursion_(computer_science)
or this youtube video: https://www.youtube.com/watch?v=k0bb7UYy0pY
First, it is good to understand that fundamentally there is no difference between iteration and recursion and the problem that can be solved using the iterative method can be solved recursively and the other way around.
For this particular example, take a look at this drawing. It shows what's going on step by step: http://natashatherobot.com/wp-content/uploads/fibonacci.png
This post will be useful to read: http://natashatherobot.com/recursion-factorials-fibonacci-ruby/
Related
Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 6 years ago.
Improve this question
Provide a context-free grammar that generates the following language over
Σ = {0,1}: {w = 0*1* : |w| is odd}
My Solution:
S->AB|0|1
A->0A|^
B->1B|^
But using this grammar we are able to create an even number of string.
I want grammar that produces L = {0,1,000,111,001,011,00000,11111,00001,00011....}
An odd number is the sum of an odd number and an even number, so sentences in the language are either an odd number of 0s followed by an even number of 1s, or an even number of 0s followed by an odd number of ones. Moreover, an odd number is an even number plus one; if we make that substitution in the preceding description we get "an even number of 0s followed by either 0 or 1, followed by an even number of 1s". Since every even number is either 0 or two more than an even number, we end up with.
S -> A 0 B | A 1 B
A -> ε | A 0 0
B -> ε | B 1 1
or
S -> 0 | 1 | 0 0 S | S 1 1
I am struggling to find a smart/creative way to approach this problem instead of a brute force algorithm. Any insights that could allow me to view this problem in a different light would be greatly appreciated. Any language can be used.
Given a sequence of numbers, it is sometimes possible to place the basic operations of =, +, −, ×, and ÷ between those number to build a complete, correct equation. For instance, the sequence [2, 3, 8, 4, 22] can be made into an equation by putting the symbols in the following places:
2 + 3 × 8 − 4 = 22
Note how the order of operations is followed. Write a program that will build such a number sentence, given the list of numbers. An ideal solution would allow the numbers to be specified on the command line, but prompting the user for a list is also acceptable. If no true sentence can be found, print such a message to the user. Assume only one = will be used (allowing for multiple equal signs makes the assignment a lot harder, but is fun!)
You may present the sentence using prefix, infix, or postfix operators.
Sample Output
Note that some of these sequences could form multiple sentences. Only one need be printed.
$ assignment -4 1 2 3 4
1 - 2 = 3 - 4
$ assignment -4 1 1 1
1 / 1 = 1
$ assignment -4 0 18 1 2 1 1
0 / 18 = 1 - 2 + 1 * 1
$ assignment -4 2 2 2
No equation found
I need to find out all possible combinations of row in a matrix where sum of columns represents a specific row matrix.
Example:
Consider the following matrix
| 0 0 2 |
| 1 1 0 |
| 0 1 2 |
| 1 1 2 |
| 0 1 0 |
| 2 1 2 |
I need to get the following row matrix from where sum of columns:
| 2 2 2 |
The possible combination were:
1.
| 1 1 0 |
| 1 1 2 |
2.
| 0 1 0 |
| 2 1 2 |
What is the best way to find out that.
ALGORITHM
One option is to turn this into the subset sum problem by choosing a base b and treating each row as a number in base b.
For example, with a base of 10 your initial problem turns into:
Consider the list of numbers
002
110
012
112
010
212
Find all subsets that sum to 222
This problem is well known and is solvable via dynamic programming (see the wikipedia page).
If all your entries are nonnegative, then you can use David Psinger's linear time algorithm which has complexity O(nC) where C is the target number and n is the length of your list.
CHOICE OF BASE
The complexity of the algorithm is determined by the choice of the base b.
For the algorithm to be correct you need to choose the base larger than the sum of all the digits in each column. (This is needed to avoid solving the problem due to an overflow from one digit into the next.)
However, note that if you choose a smaller base you will still get all the correct solutions, plus some incorrect solutions. It may be worth considering using a smaller base (which will make the subset sum algorithm work much faster), followed by a postprocessing stage that checks all the solutions found and discards any incorrect ones.
Too small a base will produce an exponential number of incorrect solutions to discard, so the best size of base will depend on the details of your problem.
EXAMPLE CODE
Python code to implement this algorithm.
from collections import defaultdict
A=[ [0, 0, 2],
[1, 1, 0],
[0, 1, 2],
[1, 1, 2],
[0, 1, 0],
[2, 1, 2] ]
target = [2,2,2]
b=10
def convert2num(a):
t=0
for d in a:
t+=b*t+d
return t
B = [convert2num(a) for a in A]
M=defaultdict(list)
for v,a in zip(B,A):
M[v].append(a) # Store a reverse index to allow us to look up rows
# First build the DP array
# Map from number to set of previous numbers
DP = defaultdict(set)
DP[0] = set()
for v in B:
for old_value in DP.keys():
new_value = old_value+v
if new_value<=target:
DP[new_value].add(v)
# Then search for solutions
def go(goal,sol):
if goal==0:
# Double check
assert map(sum,zip(*sol[:]))==target
print sol
return
for v in DP[goal]:
for a in M[v]:
sol.append(a)
go(goal-v,sol)
sol.pop()
go(convert2num(target),[])
This code assumes that b has been chosen large enough to avoid overflow.
Closed. This question is off-topic. It is not currently accepting answers.
Want to improve this question? Update the question so it's on-topic for Stack Overflow.
Closed 11 years ago.
Improve this question
I realize the title is a bit odd. But this is a statistics problem that I am trying to figure out, but am stumped. (No no, its not homework, see the bottom for the real explanation)
The premise is simple. You have N buckets. Each bucket can hold H balls. None of the buckets is full. You have D balls already in the buckets, but you don't know where the balls are (you forgot!) You choose a bucket at random to add 1 ball. What is the probability that that bucket will then be full.
Some example possible diagrams, with N = 4, H = 3, D = 4. Each case is just a hypothetical arrangement of the balls. for one of many cases.
Scenario 1: 1 bucket could be filled.
| | | | |
+ - + - + - + - +
| B | | | |
+ - + - + - + - +
| B | B | | B |
+ - + - + - + - +
Scenario 2: 2 buckets could be filled.
| | | | |
+ - + - + - + - +
| | B | B | |
+ - + - + - + - +
| | B | B | |
+ - + - + - + - +
Scenario 3: 0 buckets could be filled.
| | | | |
+ - + - + - + - +
| | | | |
+ - + - + - + - +
| B | B | B | B |
+ - + - + - + - +
The problem is I need a general purpose equation in the form of P = f(N, H, D)
Alright, you've tuned in this far. The reason behind this query on math, is I'm curious in having large battles between units. Each unit could belong to a brigade that contains many units of the same type. however, the battle will progress slowly over time. At each phase of the battle, the state will be saved to the DB. Instead of saving each unit and each health for each unit, I want to save the number of units and the total damage on the brigade. When damage is added to a brigade, the f(N, H, D) is run and returns a % chance that a unit in the brigade is destroyed (all of its HP are used up). This then removes that unit from the brigade decrementing N by 1 and D by H.
Before you launch into too much criticism of the idea. Remember, if you have VAST VAST large armies, this sort of information cannot be efficiently stored in a small DB, and with the limitations of Web, I can't keep the data for all the units in memory at the same time. Anyway, thanks for the thoughts.
I believe this boils down to the probability that the first bucket holds H-1 balls (because your probability is really the probability that the bucket you pick to drop a ball into has H-1 balls.
I'm guessing this should be solvable with combinatorics, then, but that is not my strong point.
As a side note: this is not a statistics problem, but a probability problem.
if you could afford to store for each brigade the number n[h] of units with h hits for each possible h, then the problem becomes straighforward: with probability n[h]/N you select a unit with h hits, and then increment n[h+1] and decrement n[h], or if you've selected h=max-1 you decrement n[h] and N.
If you can't afford the extra memory, a reasonable and tractable choice would be the maximum entropy distribution, see here for example
I'm trying to solve one of the Project Euler problems. As a consequence, I need an algorithm that will help me find all possible partitions of a set, in any order.
For instance, given the set 2 3 3 5:
2 | 3 3 5
2 | 3 | 3 5
2 | 3 3 | 5
2 | 3 | 3 | 5
2 5 | 3 3
and so on. Pretty much every possible combination of the members of the set. I've searched the net of course, but haven't found much that's directly useful to me, since I speak programmer-ese not advanced-math-ese.
Can anyone help me out with this? I can read pretty much any programming language, from BASIC to Haskell, so post in whatever language you wish.
Have you considered a search tree? Each node would represent a choice of where to put an element and the leaf nodes are answers. I won't give you code because that's part of the fun of Project Euler ;)
Take a look at:
The Art of Computer Programming, Volume 4, Fascicle 3: Generating All Combinations and Partitions
7.2.1.5. Generating all set partitions
In general I would look at the structure of the recursion used to compute the number of configurations, and build a similar recursion for enumerating them. Best is to compute a one-to-one mapping between integers and configurations. This works well for permutations, combinations, etc. and ensures that each configuration is enumerated only once.
Now even the recursion for the number of partitions of some identical items is rather complicated.
For partitions of multisets the counting amounts to solving the generalization of Project Euler problem 181 to arbitrary multisets.
Well, the problem has two aspects.
Firsty, the items can be arranged in any order. So for N items, there are N! permutations (assuming the items are treated as unique).
Secondly, you can envision the grouping as a bit flag between each item indicating a divide. There would be N-1 of these flags, so for a given permutation there would be 2^(N-1) possible groupings.
This means that for N items, there would be a total of N!*(2^(N-1)) groupings/permutations, which gets big very very fast.
In your example, the top four items are groupings of one permutation. The last item is a grouping of another permutation. Your items can be viewed as :
2 on 3 off 3 off 5
2 on 3 on 3 off 5
2 on 3 off 3 on 5
2 on 3 on 3 on 5
2 off 5 on 3 off 3
The permutations (the order of display) can be derived by looking at them like a tree, as mentioned by the other two. This would almost certainly involve recursion, such as here.
The grouping is independent of them in many ways. Once you have all the permutations, you can link them with the groupings if needed.
Here is the code you need for this part of your problem:
def memoize(f):
memo={}
def helper(x):
if x not in memo:
memo[x]=f(x)
return memo[x]
return helper
#memoize
def A000041(n):
if n == 0: return 1
S = 0
J = n-1
k = 2
while 0 <= J:
T = A000041(J)
S = S+T if k//2%2!=0 else S-T
J -= k if k%2!=0 else k//2
k += 1
return S
print A000041(100) #the 100's number in this series, as an example
I quickly whipped up some code to do this. However, I left out separating every possible combination of the given list, because I wasn't sure it was actually needed, but it should be easy to add, if necessary.
Anyway, the code runs quite well for small amounts, but, as CodeByMoonlight already mentioned, the amount of possibilities gets really high really fast, so the runtime increases accordingly.
Anyway, here's the python code:
import time
def separate(toseparate):
"Find every possible way to separate a given list."
#The list of every possibility
possibilities = []
n = len(toseparate)
#We can distribute n-1 separations in the given list, so iterate from 0 to n
for i in xrange(n):
#Create a copy of the list to avoid modifying the already existing list
copy = list(toseparate)
#A boolean list indicating where a separator is put. 'True' indicates a separator
#and 'False', of course, no separator.
#The list will contain i separators, the rest is filled with 'False'
separators = [True]*i + [False]*(n-i-1)
for j in xrange(len(separators)):
#We insert the separators into our given list. The separators have to
#be between two elements. The index between two elements is always
#2*[index of the left element]+1.
copy.insert(2*j+1, separators[j])
#The first possibility is, of course, the one we just created
possibilities.append(list(copy))
#The following is a modification of the QuickPerm algorithm, which finds
#all possible permutations of a given list. It was modified to only permutate
#the spaces between two elements, so it finds every possibility to insert n
#separators in the given list.
m = len(separators)
hi, lo = 1, 0
p = [0]*m
while hi < m:
if p[hi] < hi:
lo = (hi%2)*p[hi]
copy[2*lo+1], copy[2*hi+1] = copy[2*hi+1], copy[2*lo+1]
#Since the items are non-unique, some possibilities will show up more than once, so we
#avoid this by checking first.
if not copy in possibilities:
possibilities.append(list(copy))
p[hi] += 1
hi = 1
else:
p[hi] = 0
hi += 1
return possibilities
t1 = time.time()
separations = separate([2, 3, 3, 5])
print time.time()-t1
sepmap = {True:"|", False:""}
for a in separations:
for b in a:
if sepmap.has_key(b):
print sepmap[b],
else:
print b,
print "\n",
It's based on the QuickPerm algorithm, which you can read more about here: QuickPerm
Basically, my code generates a list containing n separations, inserts them into the given list and then finds all possible permutations of the separations in the list.
So, if we use your example we would get:
2 3 3 5
2 | 3 3 5
2 3 | 3 5
2 3 3 | 5
2 | 3 | 3 5
2 3 | 3 | 5
2 | 3 3 | 5
2 | 3 | 3 | 5
In 0.000154972076416 seconds.
However, I read through the problem description of the problem you are doing and I see how you are trying to solve this, but seeing how quickly the runtime increases I don't think that it would work as fast you would expect. Remember that Project Euler's problems should solve in around a minute.