It's my very 1st time doing algorithm.
Can someone help me solve the 2 followings?:
A <- [3, 3, 0]
While A[2] < A[1] :
A[0] <- A[0] + A[0]
A[2] <- A[2] + 1
Show A[0] + A[2]
And
> A <- 4
B <- 7
If B < 5 :
Show A - B
Else :
Show 2*B
Thanks!
It seems like homework, instead of giving the exact solution, I will give you some clues:
A <- 4: Find out what it means, probably A will get assigned the value of 4.
B <- 7: Similar for above.
The IF statement compares the two values, find out which is true, if true, the line Show A - B is executed, ELSE (thus if the condition in the IF is false), the second statement (Show 2*B) is executed.
For the while loop, make a table with A[0], A[1] and A[2], and every time the value changes, write the new value in the column (so keep track of the values of A[0] to A[2]). A While loop continues while the condition is true. When the condition is false, the statement continues after the While (thus Show A[0] + A[2].
Related
I understand where the cost comes from for lines 1-4, 6, and 9-10. But why is the cost of line 5 10 and the cost of line 7 6?
Max-Heap-Increase-Key(A[1...n]: array of number, i: 1<= i <= n, key)
1 if key < A[i]
2 then print " "
3 A[i] = key
4 parent = floor(i/2)
5 while i > 1 and A[parent] < A[i]
6 temp = A[i]
7 A[i] = A[parent]
8 A[parent] = temp
9 i = parent
10 parent = floor(i/2)
The constant cost for a single execution of each line are as follows:
1) 5,
2) 1,
3) 4,
4) 4,
5) 10,
6) 4,
7) 6,
8) 4,
9) 2,
10) 4
Count cost 1 for: reading a variable, writing to variable, using an array index to locate memory location, reading or writing to array index, arithmetic op, comparison (where <= or >= counts twice) and a boolean operation.
Let's look at line 5:
while i > 1 and A[parent] < A[i]
According to the rules for what we should count:
Reading a variable: i is read twice, A twice, and parent once, so there are five read operations.
Reading from an array: Twice from the array A.
Comparison: One > and one <, so there are two comparisons.
Boolean operation: One and.
Total cost is 10.
And line 7:
A[i] = A[parent]
According to the rules:
Reading a variable: A is read twice, i once, and parent once.
Reading from an array: Once, on the right-hand side.
Writing to an array: Once, on the left-hand side.
So the total cost is 6.
It remains uncertain what "using an array index to locate memory location" is supposed to mean if this is different to "reading or writing to array index". Perhaps this should be counted instead of loading the variable A? That would be strange, but it is also strange to describe it as a separate cost from reading/writing to an array.
Generally speaking, a variable like A holds a pointer to an array, so accessing an array like A[i] requires loading that pointer, then loading the index variable, and then doing the read or the write. The read or write operation consumes the pointer and index loaded in the previous two operations.
For example, given a numbers list
sample output:
0120383****2919
ie. 1,1 2,2 3,3 max. number is 3
How to use an algorithm to form a maxmum number of nested paris?
Similar to Longest Palindromic Subsequence, I guess .
O(n*n) solution is out there . Is that what you want ?
The exact procedure is =>
The problem can be solved using a recurrence relation as follows,
T(i,j) => what is the length of longest nested pair in the sub-array [i,j].
Now your answer is t(0,n-1) assume array has N elements, indexed from 0 to n-1.
T(i,j) = >
If(i>=j) T(i,j) = 0
If(arr[i] == arr[j]) T(i,j) = 2+T(i+1,j-1)
else T(i,j) = max(T(i+1,j),T(i,j-1))
Now you can either write a recursive or a bottom up DP to solve the recurrence. NOTE that while solving the recurrence you will also have to trace which Segment gave the maximum answer, and then you just need to traverse that segment and collect all matching pairs.
Here is a working algorithm I wrote in R. While this works it's overly verbose because I'm tired.
I can come back tomorrow and make it shorter if you need, but hopefully you can just see the logic and then make your own version in whatever language.
# Example data
num_list <- c(0,1,2,0,3,8,3,2,9,1,9)
# Declare empty vector for later
tmp <- numeric()
# Find out which numbers can be ruled out based on frequency
cnt <- as.data.frame(table(num_list))
# Keep pairs, fix data classes
for(i in unique(cnt$num_list)){
if(cnt$Freq[cnt$num_list==i] == 2){
tmp <- c(as.numeric(as.character(
cnt$num_list[cnt$num_list == i])), tmp)
}
}
num_list <- num_list[num_list%in%tmp]
# Figure out where the max (peak) number is, to cut the data
peak <- numeric()
for(i in 1:(length(num_list)-1)){
if(!is.na(num_list[i]) & num_list[i] == num_list[i+1]){
peak <- num_list[i]
}
}
# Apply nesting filter to first half of data
drop <- numeric()
for(i in 1:(length(num_list)-1)){
if(!is.na(num_list[i]) & num_list[i] == peak){
break
} else if(!is.na(num_list[i]) & num_list[i] > num_list[i+1]){
num_list[i+1] <- NA
}
}
num_list <- num_list[!is.na(num_list)]
num_list <- num_list[!num_list %in%
unique(num_list)[table(num_list)==1]]
num_list.beg <- num_list[1:(max(which(num_list==peak)))]
num_list.end <- num_list[(max(which(num_list==peak))+1):length(num_list)]
# Apply nesting filter to second half of data
for(i in 1:(length(num_list.end)-1)){
if(!is.na(num_list.end[i]) & num_list.end[i] <= num_list.end[i+1]){
num_list.end[i+1] <- NA
}
}
num_list.end <- num_list.end[!is.na(num_list.end)]
num_list <- c(num_list.beg, num_list.end)
# Sort them like you did in your desired output
sort(num_list)
1 1 2 2 3 3
In the classic Rod cutting problem, the mathematical expression for maximum revenue is:
which can be recursively defined as:
maxCost(n) = max(p[n], (maxCost(n-i)+maxCost(i), for 1 <= i <= n)
which can be expressed as:
p = [1, 5, 8, 9]
def maxCost(size):
if size <= 1:
return size
cost = -1
for i in xrange(1, size+1):
cost = max(p[i-1], (maxCost(i) + maxCost(size-i-1))) # --> stackoverflow error
#cost = max(cost, (p[i-1]+ maxCost(size-i))) --> giving correct o/p
return cost
if __name__ == '__main__':
print maxCost(4)
The expression for the uncommented cost in the loop comes directly from the mathematical expression defined. However, this is giving SO error.
On the other hand, the expression for the commented cost is giving right answer (for n = 1, 2, 3, 4) but I'm unable to understand the derivation of this expression from the mathematical expression.
Can anyone please help/tell me what's wrong in the uncommented expression for cost and how/why the commented line is correct ?
Are you sure the recursion
maxCost(n) = max(p[n], (maxCost(n-i)+maxCost(i), for 1 <= i <= n)
is correct?
Based on http://www.radford.edu/~nokie/classes/360/dp-rod-cutting.html, the recursion is
q = max(q, p(i) + Cut-Rod(p, n-i)
This matches your commented line
cost = max(cost, (p[i-1]+ maxCost(size-i)))
To answer your question on why you are seeing an SO error...
The un-commented recursion you are using
cost = max(p[i-1], (maxCost(i) + maxCost(size-i-1)))
calls maxCost twice: for i and for size-i-1.
This puts you in an infinite recursion even for an input of 2.
I put a couple of print statements in your code to show what happens.
p = [1, 5, 8, 9]
def maxCost(size):
print("maxCost called with size= " + str(size));
if size <= 1:
return size
cost = -1
for i in xrange(1, size+1):
print("in loop, i= " + str(i));
raw_input("Press Enter to continue...")
cost = max(p[i-1], (maxCost(i) + maxCost(size-i-1))) # --> stackoverflow error
#cost = max(cost, (p[i-1]+ maxCost(size-i))) --> giving correct o/p
return cost
if __name__ == '__main__':
size = int(raw_input().strip())
print maxCost(size)
And here's the output when fed a size of 2.
H:\code\temp>py so.py
2
maxCost called with size= 2 #initial call size=2
in loop, i= 1
Press Enter to continue...
maxCost called with size= 1
maxCost called with size= 0
in loop, i= 2
Press Enter to continue...
maxCost called with size= 2 #called again with size=2, when i=2
in loop, i= 1
Press Enter to continue...
You'll notice that when i = 2, we are back to calling maxCost(2), which is exactly the same as the first time we called maxCost! Hence the infinite recursion and the SO error.
The correct recursion will stop at n-1.
rk=max(pk,r1+rk−1,r2+rk−2,…,rk−1+r1)
In above equation (taken from http://www.radford.edu/~nokie/classes/360/dp-rod-cutting.html), after pk, there are exactly k-1 terms, so we have to loop from 1 to k-1 only. Hence for i in xrange(1, size): #fixed to iterate to size-1
Also, in your original code, when calculating cost, you need to include cost also as an input to the max() function, else you loose the cost calculated in the previous iteration. Hence, cost = max(cost, p[size-1], (maxCost(i) + maxCost(size-i)))
The full fixed code gives correct values for sizes 1 thru 4.
Note: for size=4, correct output is 10, not 9.
p = [1, 5, 8, 9]
def maxCost(size):
if size <= 1:
return size
cost = -1
for i in xrange(1, size): #fixed to iterate to size-1
cost = max(cost, p[size-1], (maxCost(i) + maxCost(size-i))) # --> fixed code, gives correct out of 10, for size=4
#cost = max(cost, (p[i-1]+ maxCost(size-i))) #--> giving correct o/p
return cost
if __name__ == '__main__':
size = int(raw_input().strip())
print maxCost(size)
maxCost(i)
your function is calling itself at the same depth level, so it never gets to a base case.
maxCost(1) -> maxCost(1) -> maxCost(1) -> ad infinitum
results in the stack overflow
I have a code for calculating factorial as below :
fact(1,1).
fact(X,R):- X1 is X-1, fact(X1,R1), R is R1*X.
In my mind this code shouldn't work right but it does! What is my reason? I think when we call fact(3,R), first it calculate "X1 is X1 -1". Then it goes to next rule fact(X1,R1). This will call the goal part again and the code execution will return to the goal "fact(X,R)" and this will continue until we reach to fact(1,1). It means it never goes to
R is R1*X part. So, it seems I am thinking wrong.
Can anyone tell me step by step about the code execution order in this code?
Thanks
Once we "reach" the fact(1,1), it will "return" to the calling recursive iteration and proceed to the part R is R1*X of that iteration, with R1=1. Then will return again to a previous level and so on. Let's look at a non-trivial iteration:
fact(3,R) :
X <- 3,
X1 <- 3-1 = 2,
fact(2,R1) :
X' <- 2,
X1' <- 2-1 = 1,
fact(1, R1'), => R1'=1 (matched from fact(1,1))
R'<- R1' * X' = 2
R1 = R' = 2
R <- R1*X = 2*3 = 6.
Here the variable with ' are denoting the variables corresponding to the fact(2,R) iteration. The variables without ' are for the topmost iteration.
I'm trying to find a way to determine all possible words that can be spelled out by a given number, given a mapping of alphabets to values.
I eventually want to find a solution that works for any 1- or 2- digit value mapping for a letter, but for illustration, assume A=1, B=2, ... Z=26.
Example: 12322 can be equal to abcbb (1,2,3,2,2), lcbb (12,3,2,2), awbb (1,23,2,2), abcv (1,2,3,22), awv (1,23,22), or lcv (12,3,22).
Here's what I have thought of so far:
I will build a tree of all possible words using the number.
To do this, I will start out with a tree with one root node with dummy data.
I will parse then the number digit-by-digit starting from the least significant digit.
At each step, I will take the last digit of the remaining part of the number and insert it into the left subtree of the current node, and remove that digit from the number for that node's left subtree. For the same node, I will then check if the previous TWO digits together form a valid alphabet, and if so, I will put them into the right subtree (and remove the 2 digits from the number for that node's right subtree).
I will then repeat the above steps recursively for each node, using the part of the number that's left, until there are no more digits left.
To illustrate, for 12322 my tree will look something like this:
*
/ \
/ \
2 22
/ / \
2 3 23
/ \ / \ /
3 23 2 12 1
/ \ / /
2 12 1 1
/
1
To get the words then, I will traverse all possible paths from the leaves to the nodes.
This seems to be an overly complex solution for what I thought would be a fairly simple problem, and I'm trying to find if there's a simpler way to solve this.
You need not actually construct a tree - just recurse:
Take a single digit. See if we can form a word considering it as a letter in itself, and recurse.
When we return from the recursion, try adding another digit (if we were 1 or 2 previously), and re-recursing.
Suppose you aleady have all the possible combination of [2, 3, 2, 2] ,what would be the combination of [1, 2, 3, 2, 2] (add [1] to the head)? It is not difficult the deduce it should be:
A1: put [1] to the head of all_the_combinations_of[1,2,3,2,2] and
A2: put [1*10 + 2] to the head of all_the_combinations_of[2,3,2,2] if [1*10 + 2 <=26]
Once we got this , the following should be easy. I implemented an Ruby version with the recusion trace for your reference.
def comb a
c = []
puts a.inspect
return [a] if a.length <= 1
c = comb(a[1..-1]).map {|e| [a[0]] + e}
if a[0] * 10 + a[1] <= 26
c += comb(a[2..-1]).map { |f| [a[0] * 10 + a[1]] + f }
end
c
end
h = Hash[*(1..26).to_a.zip(('A'..'Z').to_a).flatten]
#h.keys.sort.each {|k| puts "#{k}=>#{h[k]}"}
comb([1,2,3,2,2]).each do |comb|
puts comb.map {|k| h[k]}.join
end
[1, 2, 3, 2, 2]
A1 [2, 3, 2, 2]
[3, 2, 2]
[2, 2]
[2]
[]
[2, 2]
[2]
[]
A2 [3, 2, 2]
[2, 2]
[2]
[]
ABCBB
ABCV
AWBB
AWV
LCBB
LCV
A brute-force solution would be to dynamically fill the array from 1 to N, where a[i] element contains a set of strings that form a[1]a[2]a[3]...a[i] after expansion. You can fill a[1] from stratch, then fill a[2], based on a[1] set and second character in the string. Then you fill a[3], etc. At each sted you only have to look back to a[i-1] and a[i-2] (and to s[i-1] and s[i], where s is your number sequence).
Finally, after you fill a[n], it will contain the answer.
For the example '12322', the sequence becomes:
a[1] = { "a" }
a[2] = { a + 'b' | a in a[1] } union { "l" } = { "ab", "l" }
a[3] = { a + 'c' | a in a[2] } union { a + 'w' | a in a[1] } = { "abc", "lc", "aw" }
a[4] = { a + 'b' | a in a[3] } union { } = { "abcb", "lcb", "awb" }
a[5] = { a + 'b' | a in a[4] } union { a + 'v' | a in a[3] } = { "abcbb", "lcbb", "awbb", "abcv", "lcv", "awv" }
This is essentially the dynamic programming version of the recursive solution above.
An alternative way to do this would be to reverse the problem:
Given a dictionary of words, calculate the numeric strings that would be generated, and store this data into a map/dictionary structure, i.e. table['85'] = 'hi'
For each of the first x digits of the number you are looking up, see if it's in the table, i.e. table.ContainsKey('1'), table.ContainsKey('12'), ...
If you're trying to find the word sequences, generate the words that start at each location in the numeric string, and then do a recursive lookup to find all phrases from that.