Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 9 years ago.
Improve this question
I have created a recursive function to calculate the max path of a binary tree. I got as feedback that it does not work, but according to me test it provide the correct result. Can someone help me please?
private long PathSum(int row, int column, Pyramid pyramid)
{
// Base case, stop recurse when first row is reached.
if (row == 0) return pyramid[row, column];
// Set level to the current cell and add to the end result.
long value = pyramid[row, column];
// Continue to the next row.
if (row != 0)
{
// Continue to the next left level.
long left = pyramid[row - 1, column];
// Continue to the next right level.
long right = pyramid[row - 1, column + 1];
// Get the highest of the left and right.
long highest = Math.Max(left, right);
// Get the index of the hightest path.
int nextColumn = highest == left ? column : column + 1;
// Recurse to the next level and add results together.
value += GetTotal(row – 1, nextColumn, pyramid);
}
// Return result to the caller.
return value;
}
You have a critical mistake in your algorithm: you only walk through the 'pyramid' once and select the based case based on the next result, without looking at underlying nodes.
To illustrate what you are doing, consider the following pyramid:
1
2 3
311 6 3
Assuming that you start at 1, the following will be executed:
Look at the max out of the underlying nodes (2 and 3).
Go down to the next node (3) and repeat.
Your algorithm will return 10 (1 + 3 + 6) while the maximum value in my example is 311 + 2 + 1, because it doesn't look ahead.
You require a strategy to look further than one step ahead in order to determine the best path.
Edit: look at Euler project #18 approach for more hints.
I think what you are describing is not a binary tree but a pyramid of numbers, and the problem is best solved using dynamic programming instead of tree traversal. Here is a sample code for dynamic programming. It is not compiled and I don't know C# by the way:
private long DP(int maxRow, Pyramid pyramid)
{
int maxColumn = maxRow;
Pyramid result;
clear_pyramid(result);
for (int j=0; i<maxColumn; i++) {
result[0, j] = pyramid[0, j];
}
for (int i=1; i<maxRow; i++) {
for (int j=0; j<maxColumn-i; j++) {
result[i,j] = Math.max(result[i-1,j], result[i-1,j+1]) + pyramid[i,j];
}
}
return result[maxRow-1, 0];
}
Related
I'm working on this:
Write a function, persistence, that takes in a positive parameter num
and returns its multiplicative persistence, which is the number of
times you must multiply the digits in num until you reach a single
digit.
For example:
persistence(39) == 3 // because 3*9 = 27, 2*7 = 14, 1*4=4
// and 4 has only one digit
persistence(999) == 4 // because 9*9*9 = 729, 7*2*9 = 126,
// 1*2*6 = 12, and finally 1*2 = 2
persistence(4) == 0 // because 4 is already a one-digit number
This is what I tried:
public static int Persistence(long n)
{
List<long> listofints = new List<long>();
while (n > 0)
{
listofints.Add(n % 10);
n /= 10;
}
listofints.Reverse();
// list of a splited number
int[] arr = new int[listofints.Count];
for (int i = 0; i < listofints.Count; i++)
{
arr[i] = (int)listofints[i];
}
//list to array
int pro = 1;
for (int i = 0; i < arr.Length; i++)
{
pro *= arr[i];
}
// multiply each number
return pro;
}
I have a problem with understanding recursion - probably there is a place to use it. Can some1 give me advice not a solution, how to deal with that?
It looks like you've got the complete function to process one iteration. Now all you need to do is add the recursion. At the end of the function call Persistence again with the result of the first iteration as the parameter.
Persistence(pro);
This will recursively call your function passing the result of each iteration as the parameter to the next iteration.
Finally, you need to add some code to determine when you should stop the recursion, so you only want to call Persistence(pro) if your condition is true. This way, when your condition becomes false you'll stop the recursion.
if (some stop condition is true)
{
Persistence(pro);
}
Let me take a stab at explaining when you should consider using a recursive method.
Example of Factorial: Factorial of n is found by multiplying 1*2*3*4*..*n.
Suppose you want to find out what the factorial of a number is. For finding the answer, you can write a foreach loop that keeys multiplying a number with the next number and the next number until it reaches 0. Once you reach 0, you are done, you'll return your result.
Instead of using loops, you can use Recursion because the process at "each" step is the same. Multiply the first number with the result of the next, result of the next is found by multiplying that next number with the result of the next and so on.
5 * (result of rest)
4 * (result of rest )
3 * (result of rest)
...
1 (factorial of 0 is 1).---> Last Statement.
In this case, if we are doing recursion, we have a terminator of the sequence, the last statement where we know for a fact that factorial of 0 = 1. So, we can write this like,
FactorialOf(5) = return 5 * FactorialOf(4) = 120 (5 * 24)
FactorialOf(4) = return 4 * FactorialOf(3) = 24 (4 * 6)
FactorialOf(3) = return 3 * FactorialOf(2) = 6 (3 * 2)
FactorialOf(2) = return 2 * FactorialOf(1) = 2 (2 * 1)
FactorialOf(1) = return 1 * FactorialOf(0) = 1 (1 * 1)
FactorialOf(0) = Known -> 1.
So, it would make sense to use the same method over and over and once we get to our terminator, we stop and start going back up the tree. Each statement that called the FactorialOf would start returning numbers until it reaches all the way to the top. At the top, we will have our answer.
Your case of Persistence
It calls for recursive method as well as you are taking the result and doing the same process on it each time.
Persistence(39) (not single) = return 1 + Persistence(3 * 9 = 27) = 3
Persistence(27) (not single) = return 1 + Persistence(2 * 7 = 14) = 2
Persistence(14) (not single) = return 1 + Persistence(1 * 4 = 4) = 1
Persistence(4) (single digit) = Known -> 0 // Terminator.
At the end of the day, if you have same process performed after each calculation / processing with a termination, you can most likely find a way to use recursion for that process.
You definitely can invoke your multiplication call recursively.
You will need initial sate (0 multiplications) and keep calling your method until you reach your stop condition. Then you return the last iteration you've got up to as your result and pass it through all the way up:
int persistence(int input, int count = 0) {} // this is how I would define the method
// and this is how I see the control flowing
var result = persistence(input: 39, count: 0) {
//write a code that derives 27 out of 39
//then keep calling persistence() again, incrementing the iteration count with each invocation
return persistence(input: 27, count: 1) {
return persistence(input: 14, count: 2) {
return persistence(input: 4, count: 3) {
return 3
}
}
}
}
the above is obviously not a real code, but I'm hoping that illustrates the point well enough for you to explore it further
Designing a simple recursive solution usually involves two steps:
- Identify the trivial base case to which you can calculate the answer easily.
- Figure out how to turn a complex case to a simpler one, in a way that quickly approaches the base case.
In your problem:
- Any single-digit number has a simple solution, which is persistence = 1.
- Multiplying all digits of a number produces a smaller number, and we know that the persistence of the bigger number is greater than the persistence of the smaller number by exactly one.
That should bring you to your solution. All you need to do is understand the above and write that in C#. There are only a few modifications that you need to make in your existing code. I won't give you a ready solution as that kinda defeats the purpose of the exercise, doesn't it. If you encounter technical problems with codifying your solution into C#, you're welcome to ask another question.
public int PerRec(int n)
{
string numS = n.ToString();
if(numS.Length == 1)
return 0;
var number = numS.ToArray().Select(x => int.Parse(x.ToString())).Aggregate((a,b) => a*b);
return PerRec(number) + 1;
}
For every recursion, you should have a stop condition(a single digit in this case).
The idea here is taking your input and convert it to string to calculate that length. If it is 1 then you return 0
Then you need to do your transformation. Take all the digits from the string representation(in this case from the char array, parse all of them, after getting the IEnumerable<int>, multiply each digit to calculate the next parameter for your recursion call.
The final result is the new recursion call + 1 (which represents the previous transformation)
You can do this step in different ways:
var number = numS.ToArray().Select(x => int.Parse(x.ToString())).Aggregate((a,b) => a*b);
convert numS into an array of char calling ToArray()
iterate over the collection and convert each char into its integer representation and save it into an array or a list
iterate over the int list multiplying all the digits to have the next number for your recursion
Hope this helps
public static int Persistence(long n)
{
if (n < 10) // handle the trivial cases - stop condition
{
return 0;
}
long pro = 1; // int may not be big enough, use long instead
while (n > 0) // simplify the problem by one level
{
pro *= n % 10;
n /= 10;
}
return 1 + Persistence(pro); // 1 = one level solved, call the same function for the rest
}
It is the classic recursion usage. You handle the basic cases, simplify the problem by one level and then use the same function again - that is the recursion.
You can rewrite the recursion into loops if you wish, you always can.
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 3 years ago.
Improve this question
We are doing currently C# in Arrays.And I have to get the second largest number from the Input. But i dont know the function of this code. Can someone explain this for me. For the whole code please have a view here
Code to explain:
static int ztgzahl(int[] ZL)
{
int MinZ = Int16.MinValue;
int MaxZ = Int16.MinValue;
for(int i = 0; i < ZL.Length; i++)
{
if (ZL[i] > MaxZ)
{
MinZ = MaxZ;
MaxZ = ZL[i];
}
else if (ZL[i] > MinZ)
{
MinZ = ZL[i];
}
}
return MinZ;
}
This code itterates over the array, trying to find the two highest numbers. However it uses completely messed up Variable names MinZ and MaxZ for that. It should be MaxA and MaxB or something like that.
And for each number it checks if the number is larger then the current MaxZ (the highest). If yes, it hands the previous second largest down to MinZ. If not it additionally checks if it just smaler then MinZ (as a number can be bigger the MaxZ, and still smaler then MinZ).
I am not 100% sure this works. Personally I would just sort the Arrays and get the 2nd from the right side. Or if this was a Database, get the 2nd from Bottom using a query. This kind of logic is notoriously prone for messing up.
Int16.MinValue
This will get the minimal value allowed for Int16
Then it iterates the ZL array, if it finds a value highest than the highest value found, it replaces the variable value, if not, it checks if it's place is possible as second highest value.
Please find my comments against the snippet below
static int ztgzahl(int[] ZL)
{
int MinZ = Int16.MinValue; // Min value of Int16 is -32768
int MaxZ = Int16.MinValue;
for(int i = 0; i < ZL.Length; i++) //Iterating over each index of array
{
if (ZL[i] > MaxZ) //If current element is greater than MaxZ
{
MinZ = MaxZ; //MinZ remainsthe same
MaxZ = ZL[i]; //MaxZ is the current element
}
else if (ZL[i] > MinZ) //If current element is greater than MinZ
{
MinZ = ZL[i]; //MinZ is current element
}
}
return MinZ;
}
Based on the full snipet, there will not be any negative elements in the array. So considering a short array of 4 elements {3,1,5,7}
1st Iteration:
Both MinZ and MaxZ = -1
MinZ = -1
MaxZ = 3
2nd Interation:
MinZ = 1
3rd Iteration:
MinZ = 3
MaxZ = 5
4th Iteration:
MinZ = 5
MaxZ = 7
Therefore the second largest element is 5, which is returned by MinZ
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
Let's consider a maze represented by a matrix of ints: 0 - not visited, 1 - obstacles (blocked positions), 2 - visited, -1 - output, (x,y) - start position. I want to find a path from start to some output by using recursion.
int[] x_dir = new int[] { 0, 0, -1, 1 }; // x, x, x-1, x + 1
int[] y_dir = new int[] { -1, 1, 0, 0 }; // y-1, y+1, y, y
bool dfs(int[,] maze, int x, int y, int[] x_dir, int[] y_dir)
{
if (maze[x, y] == -1) { return true; } // output cell marked -1
int i = 0;
while (i < 4 && !dfs(maze, x + x_dir[i], y + y_dir[i], x_dir, y_dir))
{
++i;
}
return (i > 4) ? false : true;
}
I have two problem: I don't know how to handle edge cases(IndexOutOfRangeException inside maze[x,y]) and how to print a path.
Please, help me.
To print a path, you need to keep track of it, which suggests adding a parameter for that purpose. Care must be taken to not include wrong turns in it, or at least to remove them once you know that is what they are.
Alternatively, if you print out the step you took for each call to dfs that returned true, you would have the path, but in reverse.
As for the edge (not corner) cases: you need to check that x+x_dir[i] and y+y_dir[i] are valid indices into the maze before trying to access those locations in the maze.
for printing path , you can create an additional matrix and store information in it.Same as in longest subsequence problem solved with dynamic programming.
OR
rather than creating some additional matrix,you can use the same matrix.To keep track of path,just save the state when you find an output cell.
while (i < 4)
{
if(!dfs(maze, x + x_dir[i], y + y_dir[i], x_dir, y_dir))
++i;
else
maze[x][y]=255;
}
then follow the cell with elements 255.
Hope this helps.
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
I want to use as loop like : Example
i putted in textbox 123 and 300 in my formula.
1/2*(300+123/300) = 150.205 >> answer
i want to loop this Example i got answer 150.205 next formula should be look like this
1/2*(150.205+123/150.205) = 75.512
the answer of this equation i want to put in next formula by loop.
i have written code but i don't know how to use it via loop
My code.
double value = (0.5 * (300 + 123 / 300));
=======================================
For End loop
When condition match like this
1/2*(11.091+123/11.091) = 11.091
Meaning Answer and input where i m putting 300 will be same i want to break loop
**Example** I want to do this without using square root function in c#
like simple if i want a root of 9 it will be 3 so it will be like this .
i choosen 1 Because 9 is one value so i choosen 1
1/2*(1+9/1) = 5.000
1/2*(5+9/5) = 3.400
1/2*(3.4+9/3.4) = 3.024
1/2*(3.024+9/3.024) = 3.000
1/2*(3+9/3) = 3.000
see you will get same value in one point always
The only tricky thing here is a comparison with tolerance, since because of round up errors you can well never meet
answer == value
condition. The implementation could be
double answer = 300.0;
double tolerance = 1e-10;
while (true) {
// based on previous answer we compute next one
double value = 0.5 * (answer + 123.0 / answer);
//TODO: you can print out steps here, if you want something like this
//Console.WriteLine(value);
// check convergence with tolerance
if (Math.Abs(answer - value) <= tolerance) {
answer = value;
break;
}
// next answer (value) becomes the previous one (answer)
answer = value;
}
// 11.0905365064094
Console.Write(answer);
The actual answer (prove it) is just a square root:
// 11.09053650640941716205160010261...
Console.Write(Math.Sqrt(123));
Real life implementation (if my boss wants me to implement it):
public static double NewtonEstimation(Func<double, double> function,
double tolerance = 1e-10,
double guess = 1.0) {
if (null == function)
throw new ArgumentNullException("function");
else if (tolerance < 0)
throw new ArgumentOutOfRangeException("tolerance", "tolerance must not be negative");
while (true) {
double value = function(guess);
if (Math.Abs(value - guess) <= tolerance)
return value;
guess = value;
}
}
...
// 11.0905365064094
Console.Write(NewtonEstimation(x => 0.5 * (x + 123 / x)));
I need to find the n-th term of this infinite series: 1,2,2,3,3,3,4,4,4,4...
Can you give me a constant time function for this task?
int i = 1;
while(true)
{
if(i = n)
//do things and exit the loop
i++;
}
I think this isn`t going to be a constant time function...
Edit
After reading more comments, it appears I misunderstood the question.
If you want to find the item at nth position an array in constant time, then the answer is trivial: x[n], because array access is constant time. However, if for some reason you were using some container where access time is not constant (e.g. linked list), or did not want to look up value in the array, you'd have to use the arithmetic series formulas to find the answer.
Arithmetic series tells us that the position n of the ith unique item would be
n = i * (i - 1) / 2
So we just need to solve for i. Using quadratic formula, and discarding the nonsensical negative option, we get:
i = Math.Floor( (1 + Math.Sqrt(1 + 8 * n)) / 2)
Original Response
I'm assuming you're looking for the position of the nth unique term, because otherwise the problem is trivial.
Sounds like the first occurrence of the nth unique term should follow arithmetic series. I.e. the position of nth unique term would be:
n * (n - 1) / 2
Given my understanding of the problem, this is more of a math problem than a programming one.
If the problem is:
Given an infinite series that consists of 1 copy of 1, 2 copies of 2, 3 copies of 3... n copies of n, what is the kth value in this series?
Now the first clue when approaching this problem is that there are 1 + 2 + 3... + n values before the first occurance of n + 1. Specifically there are (sum of the first n numbers) values before n+1, or (n)(n-1)/2.
Now set (n)(n-1)/2 = k. Multiply out and rationalize to n^2 - n - 2k = 0. Solve using quadratic equation, you get n = (1 + sqrt(1+8k))/2. The floor of this gives you how many full copies of n there are before, and happily, given zero based indexing, the floor gives you the value at the kth point in the array.
That means your final answer in c# is
return (int) Math.Floor((1 + Math.Sqrt(1 + 8 * k)) / 2);
Given non zero based indexing,
return (int) Math.Floor((1 + Math.Sqrt(-7 + 8 * k)) / 2);
public static long Foo(long index)
{
if (index < 0)
{
throw new IndexOutOfRangeException();
}
long nowNum = 0;
long nowIndex = 0;
do
{
nowIndex += nowNum;
nowNum++;
} while (nowIndex < index);
return nowNum;
}