I have this problem with generating Gauss Numbers. The problem is like this :
This is what i coded so far
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace SirurileLuiGauss
{
class Program
{
static int[] a = new int[100];
static int[] b = new int[100];
static List<int> list_a = new List<int>();
static List<int> list_b = new List<int>();
static int GaussA(int n)
{
if(n <= 0)
{
int a = 0;
list_a.Add(a);
return a;
}
else
{
int a = (GaussA(n - 1) + GaussB(n - 1))/2;
list_a.Add(a);
return a;
}
}
static int GaussB(int n)
{
if(n <= 0)
{
int b = 0;
list_b.Add(b);
return b;
}
else
{
int b = (int) Math.Sqrt(GaussA(n - 1) * GaussB(n - 1));
list_b.Add(b);
return b;
}
}
static void Main(string[] args)
{
int n = 5;
Console.WriteLine("GAUSS_111");
GaussA(n);
foreach (int element in list_a)
{
Console.WriteLine("GAUSS_A = "+element);
}
foreach (int element in list_b)
{
Console.WriteLine("GAUSS_B = " + element);
}
Console.WriteLine("\n\n");
// Clear the list
list_a = new List<int>();
list_b = new List<int>();
Console.WriteLine("GAUSS_222");
GaussB(n);
foreach (int element in list_a)
{
Console.WriteLine("GAUSS_A = " + element);
}
foreach (int element in list_b)
{
Console.WriteLine("GAUSS_B = " + element);
}
Console.Read();
}
}
}
And is totally wrong, gives me the output like 0 0 0 0 ...
What am i doing wrong?
Can i find this anywhere? Like a library or something?
I thing that the approach of this is by computing the integral and find out what is the peak/max_number of the array. Then try to iterate backwards to find all the numbers until we hit a > 0 and b > 0. The main problem is that you have to keep 2 arrays into memory, and that is hard ... Am i correct?
How do i compute that integral in C# ?
Why do you need epsilon for precision?
Thank you very much.
The problem starts as "let a0 = ... b0 = ..."; so you need a0 as well as b0
being input arguments. Another issue is that you don't need any array or list here
(imagine, that you're asked to find out a millionth itteration), dynamic programming
is a far better choice here:
// I let myselft return the result as Tupple<,>
public static Tuple<Double, Double> Gauss(Double a0, Double b0, int n) {
Double prior_a;
Double prior_b;
Double a = a0;
Double b = b0;
for (int i = 0; i < n; ++i) {
prior_a = a;
prior_b = b;
a = (prior_a + prior_b) / 2.0;
b = Math.Sqrt(prior_a * prior_b);
}
return new Tuple<Double, Double>(a, b);
}
Simple test: let a0 = 1; b0 = 5, so we have
Theory:
itt # a b
0 1 5
1 3 sqrt(5)
2 (3+sqrt(5))/2 sqrt(3*sqrt(5))
Actual:
Gauss(1, 5, 0); // returns (1, 5)
Gauss(1, 5, 1); // -/- (3, 2.23606797749979)
Gauss(1, 5, 2); // -/- (2.61803398874989, 2.59002006411135)
Gauss(1, 5, 3); // -/- (2.60402702643062, 2.60398935469938)
Gauss(1, 5, 10); // -/- (2.60400819053094, 2.60400819053094)
Gauss(1, 5, 100); // -/- (2.60400819053094, 2.60400819053094)
P.S. You can't compute (get, say, double value) an indefinite integral cause it equals F(x) + C where C is arbitrary constant; for definite integtral you may use Simpson algorithm
Related
I have a List<object> which can contain either an integer value or another List<object>.
What I need to do, is to sum the values in the array, depending on its depth(If depth is 0, multiply by 0, if 1 then by 1 ... etc.)
Example array: [5, 2, [7, -1], 3, [6, [-13, 8], 4]]
How it should be calculated: 5 + 2 + 2 * (7 - 1) + 3 + 2 * (6 + 3 * (-13 + 8) + 4) = 12
What I managed to get:
public class Program
{
public static List<object> TestCase1()
{
List<object> test = new List<object>(){
5,
2,
new List<object>(){
7, -1
},
3,
new List<object>(){
6,
new List<object>(){
-13, 8
},
4,
},
};
return test;
}
public static int ProductSum(List<object> array)
{
int depthCounter = 1;
int totalSum = 0;
int tempSum = 0;
for (int i = 0; i < array.Count; i++)
{
if (array[i] is IList<object>)
{
totalSum += tempSum * depthCounter;
tempSum = 0;
depthCounter++;
}
else
{
tempSum += (int)array[i];
}
}
return totalSum;
}
static void Main(string[] args)
{
Console.WriteLine("Result = " + ProductSum(TestCase1()));
}
}
The result from my code is
The problem that I have, is I don't see a way, that I could iterate through an array to calculate it ... Maybe there is a way to sort an array of objects in some way to simplify it?
The method should call itself ("recursive"), when it encounters a nested list. It should also take a depth parameter, keeping track of the depth. Every time you call the function recursively, you pass depth + 1 as the new depth. Whenever you count something, you multiply by depth.
public static int ProductSum(List<object> list) => ProductSum(list, 1);
public static int ProductSum(List<object> list, int depth)
{
var sum = 0;
foreach (var thing in list) {
if (thing is List<object> innerList) {
sum += ProductSum(innerList, depth + 1) * depth;
} else if (thing is int x) {
sum += x * depth;
}
}
return sum;
}
You should do it recusively:
public static int ProductSum(List<object> array, int depthCounter)
{
int totalSum = 0;
for (int i = 0; i < array.Count; i++)
{
if (array[i] is List<object>)
{
totalSum += ProductSum(array[i] as List<Object>, depthCounter + 1);
}
else
{
totalSum += (int)array[i] * depthCounter;
}
}
return totalSum;
}
You call it this way:
ProductSum(TestCase1(), 0);
But I don't get the number you calculated, though: If all depth 0 candidates are multiplied by 0, these are... 0! ;)
Maybe there are some rules for your application that I don't know, and that's the reason why the calculations differ, but in the code you see how recursions work.
I have a problem with displaying used numbers. I'm using KnapSack algorithm and I want to display all numbers that I used to get highest value. So there is my code:
static int max(int a, int b)
{
int c = (a > b) ? a : b;
Console.WriteLine(c);
return (a > b) ? a : b;
}
// Returns the maximum value that can
// be put in a knapsack of capacity W
int knapSack(int[] r, int[] wt, int n, int W)
{
if (W < 0)
return Int32.MinValue;
if (n < 0 || W == 0)
return 0;
int include = r[n] + knapSack(r, wt, n, W - wt[n]);
int exclude = knapSack(r, wt, n - 1, W);
int V = max(include, exclude);
return V;
}
Use:
int[] r = new int[] { 3, 4, 8, 5, 6 };
int[] wt = new int[] { 2, 2, 3, 4, 7 };
int W = 11;
int z = W;
int n1 = r.Length;
stopwatch.Start();
int keik = knapSack(r, wt, n1 - 1, W);
stopwatch.Stop();
answer of this is 28, but I need to display all r numbers that was included in this. I know that for this array used numbers are 8 8 8 and 4, so I need somehow to get these numbers and display to the console.
You could try the approach of letting the function return the list of used items.
You could either return the item values themselves, or the indices of the values, depending on your needs. I used the values in this example.
Here is an implementation:
static int knapSack(int[] r, int[] wt, int n, int W, out List<int> list)
{
if (W < 0) {
list = new List<int>();
return Int32.MinValue;
}
if (n < 0 || W == 0) {
list = new List<int>();
return 0;
}
int include = r[n] + knapSack(r, wt, n, W - wt[n], out List<int> includedList);
int exclude = knapSack(r, wt, n - 1, W, out List<int> excludedList);
if (include > exclude) {
includedList.Add(r[n]);
list = includedList;
return include;
} else {
list = excludedList;
return exclude;
}
}
Call like this:
int keik = knapSack(r, wt, n1 - 1, W, out List<int> list);
Console.WriteLine(string.Join(",", list));
Output:
4,8,8,8
How to Display Numbers in the Form(0 1 1 2 3 5 8 13)
Such that the number first 1 number is displayed then second is the number with addition of previous
=>
0 then 1 then 1+0 = 1then 1+1= 2 then 1+2=3 and so on?
using System;
namespace ConsoleApplication3
{
class Program
{
static void Main(string[] args)
{
for (int i = 0; i < 20; i++)
{
Console.Write(i) ;
}
Console.ReadKey();
}
}
}
Suggest some code please
Decompose your solution into Fibonacci sequence generator:
using System.Numerics;
using System.Linq;
public static IEnumerable<BigInteger> Fibonacci() {
BigInteger a = 0;
BigInteger b = 1;
yield return a;
yield return b;
while (true) {
BigInteger result = a + b;
a = b;
b = result;
yield return result;
}
}
And sequence representation:
Console.Write(String.Join(" ", Fibonacci().Take(20)));
This will do it. I wouldn't recommend handing this in to your teacher, though:
double Phi = (1.0 + Math.Sqrt(5.0)) / 2.0;
double D = 1.0 / Math.Sqrt(5.0);
Func<int, ulong> fib = i => (ulong) ((Math.Pow(Phi, i) - Math.Pow(1.0 - Phi, i))*D);
Console.WriteLine(string.Join(" ", Enumerable.Range(0, 21).Select(i => fib(i))));
(In seriousness, I just posted this to demonstrate that there is an analytic solution to fibonnaci, as well as the normal iterative one. This only works up to n == 71, though.)
I've recently started learning C# (having learnt other languages) and I'm trying to create a function that generates the fibonacci sequence to the 'nth' term using a while loop and then returns the value of the 'nth' term.
My current code is this:
void fibonacci(int n)
{
int[] terms = { 0, 1 };
int i = 2;
while (i<=n)
{
terms.Concat( terms[i-1] + terms[i-2] );
i += 1;
}
return terms[n];
}
My understanding of C# is very poor as visual studio is telling me that I can't use 'Concat' with int[] - I'm trying to append the array with the new values. Any help would be great.
Arrays in C# are fixed length.
If you want to use a variable length collection, use a strongly typed List<T> instead, which has an Add method:
int fibonacci(int n)
{
var terms = new List<int>{ 0, 1 };
int i = 2;
while (i<=n)
{
terms.Add( terms[i-1] + terms[i-2] );
i += 1;
}
return terms[n];
}
You can't append to an array. In .Net, arrays have constant size and you can't resize them after creation.
Instead, you should use List<int> and its Add() method.
You can for example use list and change your code to:
int fibonacci(int n)
{
List<int> terms = new List<int> { 0, 1 };
int i = 2;
while (i<=n)
{
terms.Add(terms[i-1] + terms[i-2]);
i += 1;
}
return terms[n];
}
You can't add items to an array as it has fixed length. Use List<int> instead of array
I'm surprised nobody mentioned fixing the array size.
Well, maybe I'm missing something, but you could do:
int[] FibonacciArray(int n)
{
int[] F = new int[n+1];
F[0] = 0;
F[1] = 1;
for (int i = 2; i <= n; ++i)
{
F[i] = F[i - 1] + F[i - 2];
}
return F;
}
It's in average 2.5x faster than the version using a list.
But as often there is no free-lunch: the drawback is that your memory consumption is not smoothed: you pay upfront for all the memory you'll need.
Don't append values to an array. arrays have static size and you can't resize them after creation.
use
List<int> and its Add() method instead of array.
here is your solution for fibonacci series.
int fibonacci(int n)
{
var terms = new List<int>{ 0, 1 };
int i = 2;
while (i<=n)
{
terms.Add( terms[i-1] + terms[i-2] );
i += 1;
}
return terms[n];
}
also can be done like this :
class FibonacciSeries
{
static void Main(string[] args)
{
Console.WriteLine("Enter a num till which you want fibonacci series : ");
int val = Convert.ToInt32(Console.ReadLine());
int num1, num2;
num1 = num2 = 1;
Console.WriteLine(num1);
if (val > num2)
{
while (num2 < val)
{
Console.WriteLine(num2);
num2 += num1;
num1 = num2 - num1;
}
}
Console.ReadLine();
}
}
in your array format here is the solution
public int[] FibonacciSeriesArray(int num)
{
int[] arr = new int[num+1];
arr[0] = 0;
arr[1] = 1;
for (int startnum = 2; startnum <= num; startnum++)
{
arr[startnum] = arr[startnum - 1] + arr[startnum - 2];
}
return arr;
}
I would do it as a recursion, and not as a loop.
private static int fibonacci(int fib)
{
if (fib == 2 || fib == 1)
{
return 1;
}
else
{
return fibonacci(fib - 1) + fibonacci(fib - 2);
}
}
Here's a much more efficient way of finding fibonnaci numbers.
public static IEnumerable<double> FibList(int n)
{
for (int i = 1; i <= n; i++)
{
yield return Math.Round(Fib(i));
}
}
public static double Fib(double n)
{
double golden = 1.61803398875;
return (n == 0 || n == 1) ? 1 : (Math.Pow(golden, n) - Math.Pow(-golden, -n))/Math.Sqrt(5);
}
I've got an homework assignment:
need to implement a function (RotateRight) that gets an array of INT and a number:
int[] res = RotateRight(new int[] { 1, 2, 3, 4, 5, 6 }, 2);
//so then res will be {5,6,1,2,3,4}
and return the array after rotating all of the items to the right according to the number that been given, In our case 2.
And I have to do this efficiently in terms of memory space.
my best idea is:
if the number that been given is x, to use a new int[] tmpArray in the size of x to copy all the last x items to it. then with a for loop to shift all the rest of the int to the right.
And in the end to copy the items in the tmpArray to the begining of the original array.
Thanks in advance for any advice or help
You can use the beauty of the Linq langage to return an IEnumerable without dealing with array size:
/// <summary>
/// Get c = a mod (b) with c in [0, b[ like the mathematical definition
/// </summary>
public static int MathMod(int a, int b)
{
int c = ((a % b) + b) % b;
return c;
}
public static IEnumerable<T> ShiftRight<T>(IList<T> values, int shift)
{
for (int index = 0; index < values.Count; index++)
{
yield return values[MathMod(index - shift, values.Count)];
}
}
Usage :
[TestMethod]
public void TestMethod1()
{
var res = ShiftRight(new [] { 1, 2, 3, 4, 5, 6 }, 2).ToArray();
Assert.IsTrue(res.SequenceEqual(new[] { 5, 6, 1, 2, 3, 4 }));
}
Most memory possible makes no sense, you probably mean as little memory as possible? If so you should swap each item in the array using XOR, i.e:
var a = 2096;
var b = 842390;
a ^= b;
b ^= a;
a ^= b;
would swap these numbers.
EDIT
Code to do the whole thing in place:
public static void RotateRight(int[] input, int right)
{
for (var i = 0; i < right; i += 1)
{
RotateRightOne(input);
}
}
public static void RotateRightOne(int[] input)
{
var last = input.Length - 1;
for (var i = 0; i < last; i += 1)
{
input[i] ^= input[last];
input[last] ^= input[i];
input[i] ^= input[last];
}
}
Usage:
var arr = new[] {1, 2, 3, 4, 5, 6};
RotateRight(arr, 2);
As Servy points out, this is only for integers
Don't know C#, but here are two C++ versions, both in place, the first (rotate) does the minimum possible number of element moves by exploiting the cyclic structure of the rotation permutation, the second (rotate_k) just does 2*n moves for an array of length n. In both versions it's used that rotate right by k is the same as rotate left by n - k % n, so they in fact do the equivalent left rotation.
#include <iostream>
#include <vector>
#include <algorithm>
void
rotate (size_t k, std::vector<int> &a) {
size_t n = a.size();
k = n - k % n;
size_t m = n;
size_t i = 0;
while (m > 0) {
int t = a[i];
size_t j = i;
while (i != (j + k) % n) {
a[j] = a[(j + k) % n];
j = (j + k) % n;
--m;
}
a[j] = t;
--m;
++i;
}
}
void
rotate_k (size_t k, std::vector<int> &a) {
size_t n = a.size();
k = n - k % n;
std::reverse (a.begin(), a.end());
std::reverse (a.begin(), a.begin() + n - k);
std::reverse (a.begin() + n - k, a.end());
}
int
main () {
std::vector<int> a = { 1, 2, 3, 4, 5, 6, 7, 8, 9};
rotate (12, a);
for (auto i : a)
std::cout << i << " ";
std::cout << std::endl;
}
You just need to figure out the final index for each element after rotating it k times rather than actually rotating it k times.
This worked for me:
for(int i=0;i<a.Length;i++){
rotated[(k+i)%(a.Length)]=a[i];
}
Here's a quick sample on rotating an array A right K steps:
var splitPoint=A.Length-(K%A.Length);
var result=new int[A.Length];
int idx=0;
for(var pos=0;pos<A.Length;pos++)
{
if(pos<A.Length-splitPoint)
{
result[pos]=A[splitPoint+pos];
}
else
{
result[pos]=A[idx];
idx++;
}
}
return result;
C# 8 now has Indices and Ranges
Rotate Right...
int[] r = t[1..].Concat(t[0..1]).ToArray();
Rotate Left...
int[] r = t[^1..^0].Concat(t[..^1]).ToArray();
in place of the "1" above, a variable can also be used: int[] r = t[amt..].Concat(t[0..amt]).ToArray();