I'm kinda new to c# and I'm doing some projects on my own. In this project I need to find the values of the arithmetic a + (a + b) + (a + 2b) and so on. Then I need to add all the answers together. I have the first part done but I'm unsure how to add all the values I get from the loop.
class Program
{
static void Main(string[] args)
{
int a = 22;
int b = 8;
int answer;
Console.WriteLine(a);
for (int i = 1; i <= 43; i++)
{
answer = a + b * i;
Console.WriteLine(answer);
}
}
}
You need to accumulate the answer is some way. You can do that be defining another variable to hold the summation. If the loop is many iterations you may have to worry about overflow.
int total;
for (int i = 1; i <= 43; i++)
{
answer = a + b * i;
total += answer;
Console.WriteLine(answer);
}
Start with i=0
Use += operator for answer.
Consider Sum extension method from System.Linq
Using Linq you can use the Enumerable.Range() method to get a list of integers, then you can sum them.
var total = Enumerable.Range(1, 43).Sum();
Related
Given the following code:
public float[] weights;
public void Input(Neuron[] neurons)
{
float output = 0;
for (int i = 0; i < neurons.Length; i++)
output += neurons[i].input * weights[i];
}
Is it possible to perform all the calculations in a single execution? For example that would be 'neurons[0].input * weights[0].value + neurons[1].input * weights[1].value...'
Coming from this topic - How to sum up an array of integers in C#, there is a way for simpler caclulations, but the idea of my code is to iterate over the first array, multiply each element by the element in the same index in the second array and add that to a sum total.
Doing perf profiling, the line where the output is summed is very heavy on I/O and consumes 99% of my processing power. The stack should have enough memory for this, I am not worried about stack overflow, I just want to see it work faster for the moment (even if accuracy is sacrificed).
I think you are looking for AVX in C#
So you can actually calculate several values in one command.
Thats SIMD for CPU cores. Take a look at this
Here an example from the website:
public static int[] SIMDArrayAddition(int[] lhs, int[] rhs)
{
var simdLength = Vector<int>.Count;
var result = new int[lhs.Length];
var i = 0;
for (i = 0; i <= lhs.Length - simdLength; i += simdLength)
{
var va = new Vector<int>(lhs, i);
var vb = new Vector<int>(rhs, i);
(va + vb).CopyTo(result, i);
}
for (; i < lhs.Length; ++i)
{
result[i] = lhs[i] + rhs[i];
}
return result;
}
You can also combine it with the parallelism you already use.
Assume that I want to get sum of all squares from M to N. I googled a bit and found this formula:
(1^2 + 2^2 + 3^2 + ... + N^2) = (N * (N + 1) * (2N + 1)) / 6
so I write this code:
static void Main(string[] args)
{
const int from = 10;
const int to = 50000;
Console.WriteLine(SumSquares(from, to));
Console.WriteLine(SumSquares2(from, to));
}
static long SumSquares(int m, int n)
{
checked
{
long x = m - 1;
long y = n;
return (((y*(y + 1)*(2*y + 1)) - (x*(x + 1)*(2*x + 1)))/6);
}
}
static long SumSquares2(int m, int n)
{
long sum = 0;
for (int i = m; i <= n; ++i)
{
sum += i * i;
}
return sum;
}
it works fine until 40k, but when N becomes 50k it fails. Output for 50k:
41667916674715
25948336371355
Press any key to continue . . .
I think it's an overflow or something, so I added checked keyword and tried to change long to double, but I got the same result. How can it be explained? How to get correct result without loops?
Your second method is overflowing because you are using an int in the loop. Change it to a long as follows (and also add checked):
static long SumSquares2(int m, int n)
{
checked
{
long sum = 0;
for (long i = m; i <= n; ++i)
{
sum += i*i;
}
return sum;
}
}
What was going wrong is that i*i was being calculated internally as an int data type even though the result was being cast to a long data type (i.e. the variable sum), and so it overflowed.
While you are using long for the result, you are still using int for the operators. I would define M and N as long or even BigInteger, and the same for the result. If you do not, you are probably doing int arithmetic still, even though your result is of type long.
I tried your code, and got the results you got. But then I changed every int to long and got the two numbers to match, up to an N of 1600000.
Using BigInteger, I am up to 160000000 and still working ok (result for m=10 and n=160000000 is 13653333461333333359999715, both ways).
To use BigInteger, you will need to add a reference to the System.Numerics dll to your project, and you will need to have a statement at the top of your code including that library.
using System.Numerics;
namespace ConsoleFiddle
{
class Program
{
static void Main(string[] args)
{
BigInteger from = 10;
BigInteger to = 160000000;
Console.WriteLine(SumSquares(from, to));
Console.WriteLine(SumSquares2(from, to));
Console.ReadKey();
}
static BigInteger SumSquares(BigInteger m, BigInteger n)
{
checked
{
BigInteger x = m - 1;
BigInteger y = n;
return (((y * (y + 1) * (2 * y + 1)) - (x * (x + 1) * (2 * x + 1))) / 6);
}
}
static BigInteger SumSquares2(BigInteger m, BigInteger n)
{
checked
{
BigInteger sum = 0;
for (BigInteger i = m; i <= n; ++i)
{
sum += i * i;
}
return sum;
}
}
For an M of 4000000000000000000 (4 x 10^18), and an N of 4000000000100000000. This code still works and gives an immediate result with the first method (1600000016040000000400333333338333333350000000). With the second method it takes it a little while (100 million loop iterations) but gives the same result.
Most probably you are experiencing integer overflow, as the range of long is limited. Probably you have disabled exceptions for integer overflow, so no exception is thrown. The exceptions for integer overflow can be disabled and enabled in the project properties in Visual Studio, if I'm not mistaken.
I am trying to develop a console application in C# which uses a WAV-file for input. The application should do a couple of things all in order, as shown below. First of all, the complete code:
class Program
{
static List<double> points = new List<double>();
static double maxValue = 0;
static double minValue = 1;
static int num = 0;
static int num2 = 0;
static List<double> values = new List<double>();
private static object akima;
static void Main(string[] args)
{
string[] fileLines = File.ReadAllLines(args[0]);
int count = 0;
foreach (string fileLine in fileLines)
{
if (!fileLine.Contains(";"))
{
string processLine = fileLine.Trim();
processLine = Regex.Replace(processLine, #"\s+", " ");
if (Environment.OSVersion.Platform == PlatformID.Win32NT)
{
processLine = processLine.Replace(".", ",");
}
string[] dataParts = processLine.Split(Char.Parse(" "));
points.Add(double.Parse(dataParts[0]));
double value = Math.Pow(double.Parse(dataParts[1]), 2);
if (value > maxValue)
{
maxValue = value;
num = count;
}
values.Add(value);
}
count++;
}
for (int i = num; i < values.Count; i++)
{
if (values[i] < minValue)
{
minValue = values[i];
num2 = i;
}
}
Console.WriteLine(num + " " + num2);
int between = num2 - num;
points = points.GetRange(num, between);
values = values.GetRange(num, between);
List<double> defVal = new List<double>();
List<double> defValPoints = new List<double>();
alglib.spline1dinterpolant c;
alglib.spline1dbuildakima(points.ToArray(), values.ToArray(), out c);
double baseInt = alglib.spline1dintegrate(c, points[points.Count - 1]);
List<double> defETC = new List<double>();
for (int i = 0; i < points.Count; i += 10)
{
double toVal = points[i];
defETC.Add(10 * Math.Log10(values[i]));
defVal.Add(10 * Math.Log10((baseInt - alglib.spline1dintegrate(c, toVal)) / baseInt));
defValPoints.Add(points[i]);
}
WriteDoubleArrayToFile(defValPoints.ToArray(), defVal.ToArray(), "test.dat");
WriteDoubleArrayToFile(defValPoints.ToArray(), defETC.ToArray(), "etc.dat");
int end = 0;
for (int i = 0; i < points.Count; i++)
{
if (defVal[i] < -10)
{
end = i;
break;
}
}
//Console.WriteLine(num + " " + end);
int beginEDT = num;
int endEDT = num + end;
double timeBetween = (defValPoints[endEDT] - defValPoints[beginEDT]) * 6;
Console.WriteLine(timeBetween);
for (int i = 0; i < points.Count; i++)
{
}
Console.ReadLine();
}
static void WriteDoubleArrayToFile(double[] points, double[] values, string filename)
{
string[] defStr = new string[values.Length];
for (int i = 0; i < values.Length; i++)
{
defStr[i] = String.Format("{0,10}{1,25}", points[i], values[i]);
}
File.WriteAllLines(filename, defStr);
}
}
Extract the decimal/float/double value from the WAV-file
Create an array from extracted data
Create an Energy Time Curve that displays the decay of the noise/sound in a decibel-like way
Create an Decay Curve from the ETC created in step 3
Calculate things as Early Decay Time (EDT), T15/T20 and RT60 from this Decay Curve.
Display these Reverb Times in stdout.
At the moment I am sort of like half way through the process. I´ll explain what I did:
I used Sox to convert the audio file into a .dat file with numbers
I create an array using C# by simply splitting each line in the file above and putting the times in a TimesArray and the values at those points in a ValuesArray.
I am displaying a graph via GNUPlot, using the data processed with this function: 10 * Math.Log10(values[i]); (where i is an iterative integer in a for-loop iterating over all the items in the ValuesArray)
This is where I'm starting to get stuck. I mean, in this step I am using an Akima Spline function from Alglib to be able to integrate a line. I am doing that with a Schroeder integration (reversed), via this mathematical calculation: 10 * Math.Log10((baseInt - alglib.spline1dintegrate(c, toVal)) / baseInt); (where baseInt is a value calculated as a base integral for the complete curve, so I have a calculated bottom part of the reversed Schroeder integration. The c is a spline1dinterpolant made available when using the function alglib.spline1dbuildakima, which takes the timeArray as x values, valueArray as the y values, and c as an outwards spline1dinterpolant. toval is an x-value from the points array. The specific value is selected using a for-loop.) From these newly saved values I want to create an interpolated line and calculate the RT60 from that line, but I do not know how to do that.
Tried, did not really work out.
Same as above, I have no real values to show.
I'm quite stuck now, as I'm not sure if this is the right way to do it. If anyone can tell me how I can calculate the reverberation times in a fast and responsive way in C#, I'd be pleased to hear. The way of doing it might be completely different from what I have now, that's OK, just let me know!
Maybe you need to approach this differently:
start with the underlying maths. find out the mathematical formulas for these functions.
Use a simple mathematical function and calculate by hand (in excel or matlab) what the values should be (of all these things ETC, DC, EDC, T15, T20, RT60)
(A function such as a sine wave of just the minimum number of points you need )
then write a separate procedure to evaluate each of these in C# and verify your results for consistency with excel/matlab.
in C#, maybe store your data in a class that you pass around to each of the methods for its calculation.
your main function should end up something like this:
main(){
data = new Data();
//1, 2:
extract_data(data, filename);
//3:
energy_time_curve(data)
//...4, 5
//6:
display_results(data);
}
I need to define two methods for returning the sum and average of an int array. The method defining is as follow:-
public int Sum(params int[] customerssalary)
{
// I tried the following but it fails return customerssalary.sum();
}
Another question is, how can I return the average of these int values?
customerssalary.Average();
customerssalary.Sum();
This is the way you should be doing it, and I say this because you are clearly new to C# and should probably try to understand how some basic stuff works!
public int Sum(params int[] customerssalary)
{
int result = 0;
for(int i = 0; i < customerssalary.Length; i++)
{
result += customerssalary[i];
}
return result;
}
with this Sum function, you can use this to calculate the average too...
public decimal Average(params int[] customerssalary)
{
int sum = Sum(customerssalary);
decimal result = (decimal)sum / customerssalary.Length;
return result;
}
the reason for using a decimal type in the second function is because the division can easily return a non-integer result
Others have provided a Linq alternative which is what I would use myself anyway, but with Linq there is no point in having your own functions anyway. I have made the assumption that you have been asked to implement such functions as a task to demonstrate your understanding of C#, but I could be wrong.
Using ints.sum() has two problems:
The variable is called customerssalary, not ints
C# is case sensitive - the method is called Sum(), not sum().
Additionally, you'll need a using directive of
using System.Linq;
Once you've got the sum, you can just divide by the length of the array to get the average - you don't need to use Average() which will iterate over the array again.
int sum = customerssalary.Sum();
int average = sum / customerssalary.Length;
or as a double:
double average = ((double) sum) / customerssalary.Length;
Though the answers above all are different flavors of correct, I'd like to offer the following solution, which includes a null check:
decimal sum = (customerssalary == null) ? 0 : customerssalary.Sum();
decimal avg = (customerssalary == null) ? 0 : customerssalary.Average();
You have tried the wrong variable, ints is not the correct name of the argument.
public int Sum(params int[] customerssalary)
{
return customerssalary.Sum();
}
public double Avg(params int[] customerssalary)
{
return customerssalary.Average();
}
But do you think that these methods are really needed?
If you are using visual studio 2005 then
public void sumAverageElements(int[] arr)
{
int size =arr.Length;
int sum = 0;
int average = 0;
for (int i = 0; i < size; i++)
{
sum += arr[i];
}
average = sum / size; // sum divided by total elements in array
Console.WriteLine("The Sum Of Array Elements Is : " + sum);
Console.WriteLine("The Average Of Array Elements Is : " + average);
}
i refer so many results and modified my code its working
foreach (var rate in rateing)
{
sum += Convert.ToInt32(rate.Rate);
}
if(rateing.Count()!= 0)
{
float avg = (float)sum / (float)rateing.Count();
saloonusers.Rate = avg;
}
else
{
saloonusers.Rate = (float)0.0;
}
Having trouble with recursive methods in c#. When compiled it should just display the total sumUpToo of all number for the given int, i.e
- input 10
- output 55 (10 + 9 + 8 + 7 + 6 + 5 + 4 + 3 + 2 + 1 + 0)
Im not able to find any info anywhere so if someone has a link to a website that can teach me how to go through it, would be greatly appreciated.
class Program
{
static void Main(string[] args)
{
public static int sum(int x)
{
Console.WriteLine("num");
x = Console.ReadLine();
int sum = 0, i = 0;
for (i = 0; i <= x; i++)
{
sum = sum + i;
}
Console.WriteLine("{0}", sum);
}
public static int recursivesum(int x)
{
if (x <= 1)
Console.WriteLine("{0}", x);
else
(x + Recursivesum(x - 1));
}
edit * This is the adjustment seems to be working fine now, if im not mistaken. Thanks for all the help
class Program
{
static void Main(string[] args)
{
int x;
Console.Write("Please enter an integer value to sum up to: ");
x = Convert.ToInt32(Console.ReadLine());
Console.WriteLine("The sum of all numbers up to and including {0} is {1}",x, recursivesum(x));
}
public static int sum(int x)
{
int sum = 0, i = 0;
for (i = 0; i <= x; i++)
{
sum = sum + i;
}
return sum;
}
public static int recursivesum(int x)
{
if (x <= 1)
return x;
else
return x + recursivesum(x-1);
}
}
}
Beginners often have trouble with recursive functions. Follow this pattern strictly and you will be less likely to go wrong:
ReturnType RecursiveFunction(ArgumentType argument)
{
if (the argument is such that the problem can be trivially solved)
return the trivial solution;
// The problem could not be trivially solved.
// Break it down into one or more smaller problems.
ArgumentType smallerProblemArgument = whatever;
ReturnType smallerProblemSolution = RecursiveFunction(smallerProblemArgument);
// We have solved the smaller problem.
ReturnType bigProblemSolution = ...
// ... use the smaller problem solution to solve the bigger problem...
return bigProblemSolution;
}
So in your case:
public static int SumOfFirstNIntegers(int n)
{
if (n <= 0) // trivial case
return 0;
// We have a harder problem to solve. Make the problem simpler:
int smallerProblem = n-1;
int smallerSolution = SumOfFirstNIntegers(smallerProblem);
// We have solved the smaller problem. Use it to solve the big problem.
int bigSolution = smallerSolution + n;
return bigSolution;
}
A recursive function is a function that calls it self. You need a base case that will exit the function and a recursive case where the function calls itself with modified parameters. Your function should look something like this:
public static int recursivesum(int x)
{
if (x <= 1)
return x; // this is the base case
else
return x + recursivesum(x-1);
}
So to use this function, you simple call it like this:
recursivesum(10);
If you follow the logic of the function you will see this will return 10 + recursivesum(9). recursivesum(9) will return 9 + recursivesum(8). So now we have 10 + 9 + recursivesum(8).
This will carry on until we reach the point where we have 10+9+8+7+6+5+4+3+2+recursivesum(1). Now if you look at the function again, recursivesum(1) doesn't call itself again. Instead it just returns x. So now the function will unwind and you'll get the result you expect.
One final note on recursion. Recursion can be a wonderful elegant way to implement some algorithms, but it has it's dangers. This site isn't called stack overflow for nothing!