C# logic (solution needed in coding) [closed] - c#

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)));

Related

Why do I keep getting an error with the return statement [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 8 months ago.
Improve this question
I keep getting an error with the return statement.
Write a C# program to get the absolute difference between n and 51. If n is greater than 51 return triple the absolute difference.
class Program
{
static void Main(string[] args)
{
Console.WriteLine(Calculations(5));
Console.ReadLine();
}
public static double Calculations(double n)
{
double diff;
if (n < 51)
{
diff = Math.Abs(51) - Math.Abs(n);
}
else if (n > 51)
{
diff = (Math.Abs(51) - Math.Abs(n)) * 3;
}
return diff;
}
}
Diff is not guaranteed to be defined since you are using an else if. If you change that to an else, all code paths will define diff and you shouldn't have an issue. This should be the same as changing the else if to n >= 51.
Right now there is a possible code path (n=51), where diff will not be initialized.
You need to initialize your return value of diff.
double diff = 0d;
Just add an initial value to diff and it will return no errors

Making a binary Calc in C# [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 1 year ago.
Improve this question
I am making a binary calc where you can enter a binary number and the program will output the dezimal number. The Script looks like this:
Binary Code Here
First I get the User input, then I reverse it because i will need to calc the numbers( 0 and 1s) backwards in the loop later on. Lets say I will input the Binary number 10 (2 in dezimal) in. First the loop will multiply 0 by 2 abd then multiply it by the power of 0. Then it will raise the "power multiplier" by 1. Now its going on again for 1 it will basicly do 1x2^1 again. At the end of the loop it always adds the calcutated summary to the var erg to output it later to the user. Somehow, as soon as i input something higher 1 it outputs the wrong calculated dezimal number. Is the variable type wrong or is the calculation wrong?
Just wanted to point out that .net can already do this conversion
int x = Convert.ToInt32(binaryString, 2); //base 2
When having a binary input you can obtain decimal result in one line with a help of Linq.
To convert binary, say, 111010 into decimal one can use loop with + and *:
111010 => ((((1 * 2 + 0) * 2 + 1) * 2 + 0) * 2 + 1) * 2 + 1
Code:
using System.Linq;
using System.Numerics;
...
BigInteger result = input.Aggregate(BigInteger.Zero, (s, a) => s * 2 + a - '0');
In case you prefer good old loop (no Linq solution):
BigInteger result = 0;
foreach(char c in input)
result = result * 2 + c - '0';
Fiddle

How to get out of the maze using recursion? [closed]

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.

Fibonacci numbers [closed]

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 9 years ago.
Improve this question
So I have this problem where I have to calculate the Fibonacci number of any given number from the user. I don't know how to do the actual calculations part, but everything else works. Here's my code. Can someone help me with the calculation part?
using System;
namespace Assignment
{
class MainClass
{
public static void Main (string[] args)
{
int sum = 0;
Console.WriteLine("Fibonacci Number: ");
String fib = Console.ReadLine ();
double result = Convert.ToDouble (fib);
for(int i = 0; i <= result; i++)
{
sum = i * i - 1;
}
Console.WriteLine ("!" + result + " = " + sum);
}
}
}
Extension on recursion approach - use anonymous recursion (which uses Fibonacci as example of recursive call):
Define recursive function: f(n+1) = f(n) + f(n-1);.
Grab definition of Y-Combinator from the article:
delegate Func<A,R> Recursive<A,R>(Recursive<A,R> r);
static Func<A, R> Y<A, R>(Func<Func<A, R>, Func<A, R>> f)
{
Recursive<A, R> rec = r => a => f(r(r))(a);
return rec(rec);
}
Now use Y-combinator to construct recursive function:
Func<int,int> fib = Y<int,int>(f => n => n > 1 ? f(n - 1) + f(n - 2) : n);
Ready to call:
var fibOfSmallNumber = fib(4);
Now for large values you'd need BigInteger
Func<BigInteger,BigInteger> fibForBigNumbers =
Y<BigInteger,BigInteger>(f => n => n > 1 ? f(n - 1) + f(n - 2) : n);
var fibOfBigNumber = fib(4);
Don't expect it to return value in short amount of time - default recursive implementation is very slow. Instead you should apply Memoization to remember previous values of the function (which also covered in the article).
Do you know the definition of the Fibonacci numbers? Please look them up; they have nothing to do with the polynomial x² - 1. The point of the problem is for you to translate the algorithm into C♯.
There are three general approaches you'll find:
Iteration by a for loop.
Recursion.
Direct formulas using exponentiation.
Try it all three ways. I suggest you look at the textbook by Graham, Knuth, and Patashnik, Concrete Mathematics. You'll learn some of the history too.
If what you want is the nth fibonacci number something like this should work:
const double goldenratio = 1.6180339887;
int n = 16;
int nthfib = Math.Round(Math.Pow(goldenratio, n - 1) / Math.Sqrt(5));
nthfib will equal the 16th fibonacci number, 610.
Since the fibonacci sequence gets very large rather quickly, you might need a limit set on n so that nthfib doesn't max out.

Find maximum sum leaf to root path in a Binary Tree [closed]

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];
}

Categories