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.
Related
Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 1 year ago.
Improve this question
I need to substract given sum from array of elements. I.e. if given value is 15 and array starts with [10, 20,...] I need to substract 10 from the first elements (resulting with 0 for it) and the rest continue to subsequent elements - so second would be decreased by 5 (15 - 10), and the rest stay untouched.
int[] myNum = { 10, 20, 30, 40 };
if given value is 15 then I need to subtract value from the array. The new array will be
int[] myNum=[0,5,30,40]
I can easily create new array with all elements of the array decreased by the given number with basic for loop, but I don't know how to change that number based on how much I already substracted.
Your best bet is a for loop.
This will allow you to perform an action (I.E subtraction) on each 'element' of an array.
By using a return statement, you can return the new array that has had each element modified
EDIT As per #AlexeiLevenkov's comment, I have updated my answer to keep a count of the remaining subtraction.
Using this to test :
using System;
public class Program
{
public static void Main()
{
int[] array = new int[]{5,10,15,20,25,30,35};
array=SubtractArray(array,25);
Console.WriteLine("Output is:");
foreach(int v in array){
Console.WriteLine(v+", ");
}
}
public static int[] SubtractArray(int[] array , int subtraction){
for(int i=0; i< array.Length;i++){
if(subtraction>0){
int newValue=array[i]-subtraction;
if(newValue<1){
newValue=0;
subtraction=subtraction-array[i];
}
array[i]=newValue;
}
}
return array;
}
}
I don't know wath you said but I think it that :
The Arrays work 0,1,2,3,4,5,6
if I made a arrays like that
int[] _int = {10, 50, 30};
for go to the fist (10) and substract I need to do that
Sorry for my english I'm french
_int[0] -= 10;
becose it will select automatic the first (0)
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
I have an array of 8 compass points numbered from SW, clockwise though to S:
2 3 4
1 5
0 7 6
I want to calculate if the shortest route from one point to another would be clockwise (+1) or anticlockwise (-1). E.g. to go from 7 to 5 would be -1, to go from 7 to 0 would be + 1.
Simple problem I guess but I'm having a real brain freeze today.
The closest I've got is if abs(start - end) < 4, -1, 1 but that doesn't work if the start is 3.
There is a similar problem here, the accepted answer for which is to use modulo, but doesn't explain how. I've thrown various calculations around without success.
Instead of using abs, add 8 (the number of entries) and then take modulo 8, like this:
enum Direction {
None, Clockwise, Counterclockwise
}
public static Direction GetDirection(int a, int b) {
if (a == b) {
return Direction.None;
}
return (a-b+8)%8 > 4 ? Direction.Clockwise : Direction.Counterclockwise;
}
Adding 8 makes the difference non-negative; modulo-8 brings it into 0...7 range.
Note that when the number of steps is 4, it does not matter which way you go, so the program prefers counterclockwise. You can change it by using >= in place of >.
Try this
int start=3;
int end=6;
var temp = start-end;
temp= temp < 0 ? temp + 7 : temp;
var result = temp < 4 ? -1 : 1;
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)));
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];
}