I need to write a code for this assignment, subject of study is recursive methods:
Example: Consider arr={0,5,1,1,2}. Indices 0,2 and 3 are well-placed:
Index 0 is well-placed since P0=0.
Index 1 is not well-placed, since P1=5>1. Since all elements are positive, it’s impossible to find a sequence starting at index 1 that can be summed to 1.
Index 2 is well-placed since P2+P3= 2.
Index 3 is well-placed, since P3 + P4 = 3.
Index 4 is not well-placed: We can’t find a sequence starting at index that can be summed to 4 – that’s because P4 is the last element in the array, and it’s only 2.
We define ‘well-placed length’ of a well-placed index to be j-i+1 – The length of the sequence that when summed shows that the index is well placed. It is possible an index is well-placed with more than a single sequence of elements. The ‘well-placed length’ in that case is the maximal length of the various sequences defining the index as ‘well-placed’.
Example: Looking at previous example:
Index 0 well-placed length is 1 (i=0, j=0, j-i+1 = 1).
Index 2 well-placed length is 2 (i=2, j=3, j-i+1 = 2).
Index 3 well-placed length is 2 (i=3, j=4, j-i+1 = 2).
For indices 1 and 4, well-placed length is not defined, since the indices are not well-placed.
Consider arr= {0,5,1,1,2,0} – index 3 well-placed length is now 3 (i=3, j=5, j-i+1=3). Another sequence that defines index 3 as well-placed is (i=3, j=4, j-i+1=2) as before, but we’ve defined well-placed length to be the maximal value for the index.
The ‘maximal well-placed length’ is the maximum between the well-placement length of all well-placed indices in arr.
If no index in the array is well-placed, the maximal well-placed length is considered to be zero.
The function should return the maximal well-placed length.
Example: For previous examples, the return value of longestIndex should be 2, since that is the maximal well-placed length of any well-placed index in the array.
Restrictions: you are not allowed to change array; you are not allowed to use more than 1 additional (helper) function that can be reached from longestIndex. No iteration allowed.
This is the code i wrote:
int longestIndexHelper(int arr[], int length, int old)
{
if(length==0)
return 0;
if((arr[length]+arr[length-1]==length-1)||
(arr[0]==0)&&(old!=0)&&(old-length==1))
return (longestIndexHelper(arr, --length, length)+1);
}
int longestIndex(int arr[], int length)
{
return longestIndexHelper(arr, length, length);
}
Obviously, it does not work :)
Could someone please try to help?
I'm not going to debug your whole function, but an obvious potential flaw is that in some cases your helper function doesn't return any value.
You need to consider how the recursion will continue when the if () test fails.
No iteration allowed.
This is an entirely artificial restriction that pushes us into recursion when it's clearly an inferior solution in this case. When will college professors start to go for something that actually wants a recursive solution (say, tree walking) for these assignments?
I'd personally do this by writing the iterative version and transforming it into a tail-call recursive one. just to satisfy this arbitrary requirement. And leave the iterative version in there commented-out just because.
Anyway, the reason yours doesn't work is that it only ever checks for well-placed matches of length 2.
EDIT: Here's a quick outline of my recursive solution:
int longestIndex(int arr[], int length) {
if(length == 0) return 0;
int thisLongestIndex = longestIndexHelper(
/*whatever parameters you need in order to call it on the first element
in the array*/
);
return max(thisLongestIndex, longestIndex(arr+1,length-1));
}
Where longestIndexHelper will work out the longest match for the first element in the array.
Related
The following question is about math. The matter is, how to calculate the index of an element in a non-repetitive permutation. Example,
A={a,b,c} The permutation is then 3!=6 therefore: (a,b,c);(a,c,b);(b,a,c);(b,c,a);(c,a,b);(c,b,a)
I researched for algorithm to get the index of an element in this permutation. In internet there are only repetitive permutation algorithms.
The index of (b,c,a) is in this zero-based list, obviously 3. Is there an easy way to calculate the position directly by formula ?
I do not need the itertools from python. Because i use very large permutations.(Example 120!) I messed once with python's itertools' permutations function to get the index of an element over the list iterator. But the results were weary. I need a mathematical solution to get the index directly.
Thanks for reading.
Some clues:
You have n! permutations. Note that (n-1)! permutations start from the first element (a), next (n-1)! permutations start from the second element (b) and so on.
So you can calculate the first term of permutation rank as (n-1)! * Ord(P[0]) where Ord gives ordering number of the first element of permutation in initial sequence (0 for a, 1 for b etc).
Then continue with the second element using (n-2)! multiplier and so on.
Don't forget to exclude used elements from order - for your example b is used, so at the second stage c has index 1 rather 0, ad rank is 2!*1 + 1!*1 + 0! * 0 = 3
Consider the problem of finding the k element subsets of a set with n elements. Write a recursive function that takes an array of integers representing the set, the number of integers in the set (n), and the required subset size (k) as input, and displays all subsets with k elements on the screen. You may assume that the elements in the array have unique values. For example, if the array (set) contains the elements [ 8 2 6 7 ], n is 4, and k is 2, then the output is 82 86 87 26 27 67.
Can you help me with this, at least tell what way should I follow?
The type of thing you're talking about is a **combination&&.
There's a recursive definition of the calculation tucked in the middle of the Wikipedia page.
$$\binom{n}{k}=\binom{n-1}{k-1}+\binom{n-1}{k}$$
Figuring out what your base cases are might be tricky, but I think everything you need is there.
I would've right something like this:
subset ( numbers, n, k, index)
{
if (index < n) // end for the recursion. passed through all elements
{
if (k == 0) // end for the recursion. no more elements needed
print ' '
else
{
print numbers[index]
subset(numbers, n, k-1, index+1) // uses the number in the current index
subset(numbers, n, k, index+1) // doesn't use the number in the current index
}
}
call subset(numbers, n, k, 0) to start
notice that because order doesn't play a role in sets, its enough to pass over the elements in one direction
I am looking for help with pseudo code (unless you are a user of Game Maker 8.0 by Mark Overmars and know the GML equivalent of what I need) for how to generate a list / array of unique combinations of a set of X number of integers which size is variable. It can be 1-5 or 1-1000.
For example:
IntegerList{1,2,3,4}
1,2
1,3
1,4
2,3
2,4
3,4
I feel like the math behind this is simple I just cant seem to wrap my head around it after checking multiple sources on how to do it in languages such as C++ and Java. Thanks everyone.
As there are not many details in the question, I assume:
Your input is a natural number n and the resulting array contains all natural numbers from 1 to n.
The expected output given by the combinations above, resembles a symmetric relation, i. e. in your case [1, 2] is considered the same as [2, 1].
Combinations [x, x] are excluded.
There are only combinations with 2 elements.
There is no List<> datatype or dynamic array, so the array length has to be known before creating the array.
The number of elements in your result is therefore the binomial coefficient m = n over 2 = n! / (2! * (n - 2)!) (which is 4! / (2! * (4 - 2)!) = 24 / 4 = 6 in your example) with ! being the factorial.
First, initializing the array with the first n natural numbers should be quite easy using the array element index. However, the index is a property of the array elements, so you don't need to initialize them in the first place.
You need 2 nested loops processing the array. The outer loop ranges i from 1 to n - 1, the inner loop ranges j from 2 to n. If your indexes start from 0 instead of 1, you have to take this into consideration for the loop limits. Now, you only need to fill your target array with the combinations [i, j]. To find the correct index in your target array, you should use a third counter variable, initialized with the first index and incremented at the end of the inner loop.
I agree, the math behind is not that hard and I think this explanation should suffice to develop the corresponding code yourself.
I have an unsorted vector and i want to return the k-th largest number in this vector recursively. There is a way to do this?
Ex: 2 3 41 67 0 9
And I want to return the second largest number which is 41.
Thanks!
Well,
search for the highest number in the vector, remove it from the vector, repeat k times.
In pseudo-code:
function findKthHighestNumber(vetor, k):
i := findIndexOfHighestNumber(vector)
if k = 1:
return vector[i]
else
return findKthHighestNumber(concat(vector[0..i-1], vector[i+1..vector.length]), k-1)
Of course, the actual implementation would depend on the programming language used. Also, findIndexOfHighestNumber should be provided as well, but that's a different task ...
You use a helper like
(define (nth-max vec nth cur-idx cur-max lower-than)
...)
or the same as named let. The logic in it should:
If cur-idx is same as vector-length
A. nth is larger than 1: recur with lower-than as cur-max and reduce nth by 1 and set cur-idx to 0.
B. Else cur-max is the solution.
Recur with cur-idx as cur-max if it's higher than cur-max and lower than lower-than
You can start off lower-than as +Inf.0 and cur-max as first element as -Inf.0. If the result is -Inf.0 then there is no solution.. eg. Find second largest in #(5 5 5 5)
When I compute the difference between the largest and the smallest number in an empty vector(v←⍳0) using ⌈⌿(⌈/c)- ⌊⌿(⌊/c) , it gives me a domain error. This statement works fine with normal vectors and matrices.
How do I handle the exception such that it does not give me an error when the vector is empty? It should not return anything or just return a zero.
A guard is the best way to do this:
{0=⍴⍵:0 ⋄ (⌈/⍵)-⌊/⍵}
Note that the use of two reductions, one with axis specfication, is not really needed or correct actually. That is, if you want it to work on all of the elements of a simple array of any dimension, simply ravel the argument first:
{0=⍴⍵:0 ⋄ (⌈/⍵)-⌊/⍵},10 10 ⍴⍳100
99
Or for an array of any structure or depth, you can use "super ravel":
{0=⍴⍵:0 ⋄ (⌈/⍵)-⌊/⍵}∊(1 2 3)(7 8 9 10)
9
Note that quadML (Migration Level) must be set to 3 to ensure that epsilon is "super ravel."
Note also the equivalence of the following when operating on a matrix:
⌈⌿⌈/10 10 ⍴⍳100
99
⌈/⌈/10 10 ⍴⍳100
99
⌈/⌈⌿10 10 ⍴⍳100
99
⌈⌿⌈⌿10 10 ⍴⍳100
99
Using reduction with axis is not needed in this case, and obscures the intent and is also potentially more expensive. Better to just ravel the whole thing.
As I mentioned in the comments, Dyalog APL has guards, which can be used for conditional execution, and thus you can simply check for the empty vector and give a different answer.
This can be implemented in a more traditional/pure APL method however.
This version only works in 1-dimension
In the APL font:
Z←DIFFERENCE V
⍝ Calculate difference between vectors, with empty set protection
⍝ Difference is calculated by a reduced ceiling subtracted from the reduced floor
⍝ eg. (⌈⌿(⌈V)) - (⌊⌿(⌊V))
⍝ Protection is implemented by comparison against the empty set ⍬≡V
⍝ Which yields 0 or 1, and using that result to select an answer from a tuple
⍝ If empty, then it drops the first element, yielding just a zero, otherwise both are retained
⍝ eg. <condition>↓(a b) => 0 = (a b), 1 = (b)
⍝ The final operation is first ↑, to remove the first element from the tuple.
Z←↑(⍬≡V)↓(((⌈⌿(⌈V)) - (⌊⌿(⌊V))) 0)
Or in brace notation, for people without the font.
Z{leftarrow}DIFFERENCE V
{lamp} Calculate difference between vectors, with empty set protection
{lamp} Difference is calculated by a reduced ceiling subtracted from the reduced floor
{lamp} eg. ({upstile}{slashbar}({upstile}V)) - ({downstile}{slashbar}({downstile}V))
{lamp} Protection is implemented by comparison against the empty set {zilde}{equalunderbar}V
{lamp} Which yields 0 or 1, and using that result to select an answer from a tuple
{lamp} If empty, then it drops the first element, yielding just a zero, otherwise both are retained
{lamp} eg. <condition>{downarrow}(a b) => 0 = (a b), 1 = (b)
{lamp} The final operation is first {uparrow}, to remove the first element from the tuple.
Z{leftarrow}{uparrow}({zilde}{equalunderbar}V){downarrow}((({upstile}{slashbar}({upstile}V)) - ({downstile}{slashbar}({downstile}V))) 0)
and an image for the sake of preservation...
Updated. multi-dimensional
Z←DIFFERENCE V
⍝ Calculate difference between vectors, with empty set protection
⍝ Initially enlist the vector to get reduce to single dimension
⍝ eg. ∊V
⍝ Difference is calculated by a reduced ceiling subtracted from the reduced floor
⍝ eg. (⌈/V) - (⌊/V)
⍝ Protection is implemented by comparison against the empty set ⍬≡V
⍝ Which yields 0 or 1, and using that result to select an answer from a tuple
⍝ If empty, then it drops the first element, yielding just a zero, otherwise both are retained
⍝ eg. <condition>↓(a b) => 0 = (a b), 1 = (b)
⍝ The final operation is first ↑, to remove the first element from the tuple.
V←∊V
Z←↑(⍬≡V)↓(((⌈/V) - (⌊/V)) 0)