Algorithm pseudocode - algorithm

I have the pseudocode:
Algorithm exists(A,n,x):
lo=0
hi=n-1
while hi>=lo:
mid=floor((hi+lo)/2):
if x>A[mid]:
lo=mid+1
else: if x<A[mid]:
hi=mid-1
else:
return True
return False
and the array:
A[0]=1, A[1]=5, A[2]=6, A[3]=10, A[4]=12, A[5]=16, A[6]=17, A[7]=43
Then I have to find what exists(A,4,17) return.
Then we have l0=0 and hi=n-1=4-1=3 then hi>l0.
We get that mid=floor((hi+lo)/2)=floor((3+0)/2)=1 (floor is rounding to 1?).
We see that x<A[1] because 4<5. Then I think the pseudocode return: hi=mid-1=1-1=0?

The code you have written, it is binary search pseudocode. Through binary search, you can search for a number in a sorted array.
In your code, your explanation is wrong. Let me explain why.
Your array: A[0]=1, A[1]=5, A[2]=6, A[3]=10, A[4]=12, A[5]=16, A[6]=17,A[7]=43
Then you want to found exists(A,4,17), according to your algorithm,
A resembles your array, n=4, x=17
So, according to this your explanation in the last line is wrong because after the first iteration the mid=1 and then it will execute if x>A[mid]: condition because,
17 > 5 //as x=17 and A[1]= 5

Related

Why does my function outputting expected and unexpected values in ruby?

I have a method called fibs_rec that results in an unexpected output:
def fibs_rec(n)
if n == 1 || n == 0
return 1
else
a = fibs_rec(n-1) + fibs_rec(n-2)
puts a
return a
end
end
fibs_rec(5)
The call fibs_rec(5) should return 1,1,2,3,5 but here is the actual output:
2
3
2
5
2
3
8
Not only is the output incorrect, it lacks a number from the beginning.
Can someone explain why is this happening?
This is correct since your recursion is splitting into two sub-problems every time it recurses. If you want the series to appear properly then you should try doing this via dynamic programming for O(n) time complexity. As is, the first and second position won’t be printed because of the base case in the recursion.
As for the incorrect answer, it seems you have not accounted for the sequence starting with 0 index. Either find 4 index in the function which will give the fifth element or modify your function to work with position instead of index.

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)

Need Help in solving Binary Search

I am trying to solve another Question
I have implemented the binary search function required to solve this problem but i am unable to return the correct value which would help me in solving this question.Here's my code.
Please help me in solving this question.
def BinarySearch(arr,low,high,search):
while(low<=high):
middle=(low+high)/2
int_mid=int(middle)
print(int_mid)
if arr[int_mid]==search:
return int_mid
elif arr[int_mid]>search:
low=int_mid+1
elif arr[int_mid]<search:
high=int_mid-1
return arr[int_mid]
tc=int(input())
while(tc>0):
size=int(input())
A=list(map(int,input().split()))
B=list(map(int,input().split()))
monkiness=[]
for i in range(len(A)):
for j in range(len(B)):
if (j>=i):
y=BinarySearch(B,0,len(B),B[j])
z=BinarySearch(A,0,len(A),A[i])
print(y,z)
if y>=z:
m=j-i
monkiness.append(m)
if len(monkiness)==0:
print(0)
else:
print(monkiness)
maxiumum=max(monkiness)
print(maxiumum)
tc-=1
You don't need binary search here ('here' means code you provided, not problem solution)
Even if you required binary search, BinarySearch is for non-decreasing array, but you have non-increasing array.
The goal is to find solution, that runs in less, than N^2 time, by exploiting the fact, that arrays are sorted.

euler project 3 ruby> why does this solution work?

def large_prime(n)
return [] if n==1
factor = (2..n).find {|x| n % x == 0}
[factor] + large_prime(n/factor)
end
I got this solution from somewhere else. I don't understand the 4th line of code where large_prime is called recursively and appended onto factor.
When I change the first line "return []" and leave out the '[]' after the return, I get an error message for on line 4, that says '+':no implicit conversion of nil into Array.
So why does this code work? Thanks
P.S. I'm obviously a noob and everything is very new to me.
The 3rd line finds the first divisor of n between 2 and n. This line itself does not involve recursion.
I don't really get the code you modified, but it seems to return nil in some case, while the original method always return an Array.
You must return an empty array when passed 1 to terminate the recursion. Any positive argument other than one will result in another call to large_prime, but an argument of 1 results in large_prime simply returning an empty array.
At each level of recursion, the program adds an array with the single factor it found to an array consisting of all factors found for the value n/factor. When the last factor (other than 1) is found, the final call to large_prime is made with an argument of 1, large_prime returns an empty array which is then added to the array containing the last factor, giving an array containing just the last factor. This array is then returned and you have
[next-to-last-factor] + [last-factor], giving a return array of [next-to-last-factor, last-factor] which is added to [next-to-next-to-last-factor] giving [next-to-next-to-last-factor, next-to-last-factor, last-factor]. This is then added to an array [next-to-next-to-next-to-last-factor], giving... lather, rinse, repeat until we reach the largest factor and add it in.
You must return an empty array because you can't add nil to an array in Ruby.

Depth-Limited Search Recursive Pseudocode

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.

Resources