I am using C# and i am trying to find the the average of 5 values but i can only use 2 variables.
How can you input 5 integers into one variable and display the average of said integers
You can use List like this:
var list = new List<int>(){ 1, 2, 3, 4, 5 };
var average = list.Average();
using Average you'll get average of all values in list
Here you have all functions of Enumerable, you can for e.g. sum all values with Sum
Use a collection like a List<int> and the extension method Enumerable.Average:
List<int> numbers = new List<int>{ 10, 20, 30, 40, 50 };
double average = numbers.Average(); // 30.0
Use List.Add to add single integers:
numbers.Add(1);
numbers.Add(2);
numbers.Add(3);
// ...
Take the input values in a Integer list or array then use the following code
List<int> intlist=new List<int>();
intlist.Add(2);
intlist.Add(3);
..
..
var average= intlist.Average();
Using Average will computes the average of a sequence of all the integers in the list.
UPDATE: or if the case is to use integers only then you need to use the following code (Remember to validate the readline() entries)
public decimal Average()
{
int value = 0;
for(int i=0;i<5;i++)
{
value+=ConvertToInt32(Console.ReadLine());
}
return value/5;
}
What about using array? I think array is one variable in your case
int[] input = new int[5];
input[0] = 5;
input[1] = 40;
input[2] = 15;
input[3] = 50;
input[4] = 25;
int sum = 0;
foreach(int i in input)
{
sum = sum + i;
}
sum = sum / input.Length;
Console.WriteLine(sum.ToString());
#up Yeah that's better way!
You dont need arrays, or lists or anything remotely similar. Pseudo-code:
private int sum = 0;
private int count = 0;
while (user inputs valid number)
{
sum += userInput;
count++;
}
return sum / count;
Only two variables.
If you just want solution without List<int> then here it is
int[] arr=new int[5];
arr[0]=10;arr[1]=20;...arr[4]=50;
int sum=0;
foreach(int x in arr)
{
s+=x;
}
s=s/arr.Length;//s is average
If you want list
List<int> list = new List<int>(){ 1, 2, 3, 4, 5 };
var average = list.Average();
Related
I want to convert int array to int so i can add them.
Example
int[] x = {1, 2, 3};
sum=x[0] + x[1] + x[2];
I have a loop for getting an input from user but i have to add all the values of every inputted.
Use the .Sum LINQ method:
var x = new int[] { 1, 2, 3 };
var sum = x.Sum(); // gives 6
Further info
https://learn.microsoft.com/en-us/dotnet/csharp/programming-guide/concepts/linq/
https://www.csharp-examples.net/linq-sum/
You can do this in a number of ways.
first by making a loop yourself.
static int Sum(int[] array)
{
int sum = 0;
foreach (var item in array)
{
sum += item;
}
return sum;
}
static void Main()
{
int[] x = new int[] { 1, 2, 3 };
Console.Write(Sum(x).ToString());
}
second, using the Sum() method in the System.Linq library
using System.Linq;
////
int[] x = new int[] { 1, 2, 3 };
Console.Write(x.Sum());
thank you USEFUL for feedback if it worked for you
It is not really clear what the problem is. Your code seems fully functional, so it is difficult to know what you are really trying to achieve and what the underlying issue it.
But certainly a simple loop would work fine.
int sum = 0;
for(int loop=0; loop < x.Length; loop++)
{
sum += x[loop];
}
You can also do this via Linq (I see somebody else posted that example, so I won't repeat it).
I want to combine an integer array to a single integer value. So I have the following code that will combine the array to a single value.
int[] array = { 5, 6, 2, 4 };
int combine = 0;
for (int i = 0; i < array.Length; i++)
{
combine += array[i] * Convert.ToInt32(Math.Pow(10, array.Length-i-1));
}
this yield combine = 5624. Which is correct.
My issue is my array is not in the form of 0-9. So my array could be {51,62,23,44}
int[] array = { 51, 62, 23, 44 };
int combine = 0;
for (int i = 0; i < array.Length; i++)
{
combine += array[i] * Convert.ToInt32(Math.Pow(10, array.Length-i-1));
}
yielding combine as 574774, not 51622344. How would I correct this?
Do the following:
var number = int.Parse(string.Join("", array));
Explanation:
string.Join will take any enumeration of type T, call ToString() on each member and join them in a single string with the specified separator.
Once you have a string representing your number, you simply parse it to get the number itself.
Of course this is not safe and depending on your possible inputs, this could fail: {1, 4, -5, 4 }. Some error detection and int.TryParse is probably the best way to solve this, the example is simply to get the idea across.
Why not convert them to strings and then concatenate?
using System;
public class Program
{
public static void Main()
{
int[] intArray = { 5, 6, 2, 4 };
var result = string.Concat(intArray);
Console.WriteLine(result);
try {
int resultNumber = int.Parse(result);
}
catch(OverflowException) {
// this can occur if you exceed the maximum value of an int
long resultBigNumber = long.Parse(result);
}
}
}
Try using a StringBuilder, like this:
using System;
using System.Text;
public class Program {
public static void Main(string[] args) {
StringBuilder sb = new StringBuilder();
int[] array = new Int[] { 51, 62, 23, 44 };
int combine = 0;
foreach(int single in array) {
string oneNum = single.ToString();
sb.Append(oneNum);
}
string final = sb.ToString();
combine = Convert.ToInt32(final);
}
}
This will convert the numbers in the array into a string, which then gets converted into a number.
Linq and some simple math can help here (without strings or Math.Pow). I'm also going to seed it with numbers of widely varying magnitude (i.e., not all single digit numbers or all 2-digit numbers). First some preliminary code:
private readonly int[] PowersOf10 = new [] {10, 100, 1000, 10000, 100000};
private int DecimalShiftAccumulate(int numToShift, int numToAdd)
{
var nextPowerOf10 = PowersOf10.First(x => x > numToAdd);
return (numToShift * nextPowerOf10) + numToAdd;
}
You can include more numbers in the PowersOf10 array; I got tired of counting zeros.
Then declare your int array and calculate the result:
var intArray = new[] { 1051, 7, 923, 44 };
var arrayResult = intArray.Aggregate((a, b) => DecimalShiftAccumulate(a, b));
I get arrayesult = 1051792344 (i.e. (using & as concatenation) 1051 & 7 & 923 & 44)
In my C# program, I have an int array containing a set of integers and occasionally duplicates of those integers. I want to create an array that only contains the numbers that exist as duplicates in the initial array, but in itself contains no duplicates. Based on my newbie understanding of C# I thought that the following code would do the trick:
int a = 9;
int b = 6;
int c = 3;
int index = 0;
int[] mltpls = new int[a + b + c];
while (a > 0)
{
mltpls[index] = 2 * a;
a -= 1;
index += 1;
}
while(b > 0)
{
mltpls[index] = 3 * b;
b -= 1;
index += 1;
}
while(c > 0)
{
mltpls[index] = 5 * c;
c -= 1;
index += 1;
}
int[] mltpls_unique = mltpls.Distinct().ToArray();
int[] mltpls_dplcts = mltpls.Except(mltpls_unique).ToArray();
Console.WriteLine(mltpls_dplcts);
//EDIT
//By running the following code I can write out all numbers in "mltpls"
for (int i = 0; i < mltpls.Length; i++)
{
Console.Write(mltpls[i] + ", ");
}
/*If I try to run equivalent code for the "mltpls_dplcts" array nothing
only a blank line is displayed.*/
When I run this goal my the final result of my console application is a blank row. My interpretation of this is that the array mltpls_dplcts is empty or that I'm incorrectly going about printing the array.
How do get only the duplicate values from an array?
My interpretation of this is that the array mltpls_dplcts is empty or that I'm incorrectly going about printing the array.
Both interpretations are correct
Distinct will return every item that is at least once present in mltps. If you now apply Except you get nothing because all items that are in mltpls_unique are also present in mltps. The items in the array are compared by value, so for Except it does not matter whether a number occurs multiple times in the other array. If it is there once it will not return the number. So you get an empty array.
Furthermore you cannot simply shove an entire array into Console.WriteLine. Either use a loop or String.Join to print the content:
Console.WriteLine(String.Join(" ",mltpls_dplcts));
Solution: You can solve it using a good old loop approach ;)
int[] mltpls_unique = mltpls.Distinct().ToArray();
// The amount of duplicates is the difference between the original and the unique array
int[] mltpls_dplcts = new int[mltpls.Length-mltpls_unique.Length];
int dupCount = 0;
for (int i = 0; i < mltpls.Length; i++)
{
for (int j = i+1; j < mltpls.Length; j++)
{
if (mltpls[i] == mltpls[j])
{
mltpls_dplcts[dupCount] = mltpls[i];
dupCount++;
}
}
}
Output: 18 12 10 6 15
You cannot print the array directly. You need to loop and print one by one:
foreach (var element in mltpls_dplcts)
{
Console.WriteLine(element);
}
You can get array of distinct duplicates like this:
var duplicates = mltpls.GroupBy(o => o)
.Where(g => g.Count() > 1)
.Select(g => g.First()).ToArray();
To get new array that contains only the elements from the original one that are not in the second array you can use:
var newArr = mltpls.Except(duplicates).ToArray();
It is not proper way to find duplicates. You can determine the duplicates by using GroupBy and print them to console like this;
var mltpls_dplcts = mltpls.GroupBy(x => x).Where(x => x.Count() > 1).Select(x => x.Key).ToArray();
foreach (var duplicate in mltpls_dplcts)
{
Console.WriteLine(duplicate);
}
Also, If it isn't must to use Array for you, I suggest you to use List<int>.
Updated question from OP:
How do get only the duplicate values from an array?
var arr1 = new[] {1, 2, 4, 4, 5, 5, 5, 5, 6, 7, 1};
var duplicates = arr1.ToLookup(_ => _, _ => _).Where(_ => _.Count()>1).Select(_ => _.Key).ToArray();
// duplicates is now { 1, 4, 5 }
Original question from OP:
How do I delete all elements in an int array that exist in another int array in C#?
var arr1 = new[] {1, 2, 4, 5, 6, 7};
var arr2 = new[] {4, 5};
var hash = new HashSet<int>(arr1);
hash.ExceptWith(arr2);
var filteredArray = hash.ToArray();
// filteredArray is now { 1, 2, 6, 7 }
I have an array initialized as such:
int[] myArray = new int[] {9, 8, 7, 3, 4, 5, 6, 2, 1};
I then have a for() loop searching the array for the highest value each time using:
int maxValue = myArray.Max();
int maxIndex = myArray.ToList().IndexOf(maxValue);
It obviously keeps finding 9 as the highest value.
I want it to first set the previously indexed value to a randomized value below the current maxValue but above -1 and continue searching the array for the next maxValue and print it to console.
(If all values reach a value == 0 then the simulation stops) <- this part I know how to do.
Is this possible? If so, how?
I guess this might be what you want. Let me know how it works for you.
using System;
using System.Linq;
public class Program
{
private static Random random = new Random();
public static void Main()
{
int[] myArray = new int[] {9, 8, 7, 3, 4, 5, 6, 2, 1};
Simulate(myArray);
}
static void Simulate(int[] myArray)
{
int maxValue = myArray.Max();
Console.WriteLine(string.Join(" ",myArray));
var continueSimulation = true;
do{
int maxIndex = myArray.ToList().IndexOf(maxValue);
var randomValue = random.Next(0, maxValue);
myArray[maxIndex] = randomValue;
maxValue = myArray.Max();
if (maxValue == 0)
continueSimulation = false;
Console.WriteLine(string.Join(" ",myArray));
}while(continueSimulation);
}
}
You can check it out on this fiddle.
Hope this helps!
If you want to find the second max, you can mark the position of the first one and continue with your same approach. How can be done? 1- initialize an array of bool with the same length of the array where you want to find the max, then find the first max and mark that position in the second array with true, if you want the second max, make a loop through the array asking for the max and if that element is not marked in the second array of bool. Finally you will get the second max .
Another idea is taking the values in a list and once you find the max, remove the max from the list to continue with the same algorithm but with an array of less values
static int Max(int [] num)
{
int max = num[0];
for(int i = 0; i < num.Length; i ++)
{
if(num[i] > max)
max = num[i];
}
return max;
}
static int SecondMax(int[]a)
{
if(a.Length < 2) throw new Exception("....");
int count = 0;
int max = Max(a);
int[]b = new int[a.Length];
for(int i = 0; i < a.Length; i ++)
{
if(a[i] == max && count == 0)
{
b[i] = int.MinValue;
count ++;
}
else b[i] = a[i];
}
return Max(b);
}
Honestly, the question feels a bit unusual, so if you share why you're trying to do this, maybe someone could suggest a better approach. However, to answer your original question, you can just use .NET's random number generator.
int[] myArray = new int[] { 9, 8, 7, 3, 4, 5, 6, 2, 1 };
Random random = new Random();
for (int max = myArray.Max(); max > 0; max = myArray.Max())
{
int index = myArray.IndexOf(max);
DoSomething(max);
myArray[index] = random.Next(0, max);
}
From the MSDN doco on Random, the upper bound is exclusive, which means that it will generate a random number between 0 and max-1, unless max==0, in which case it will return 0.
I have a double[] array holding many numbers.
I have an algorithm that selects sections from within this array that fall under certain conditions (value greater than x, at least y values, etc.)
Now I want to calculate the average value of all these values in my section.
So, say my section is from index 20 to 40. Now I have 20 values. Is there an easy way to do this in C# or do I have to loop over my array and calculate the average by hand?
var values = new[] { 1, 2, 3, 4, 5, 6, 7, 8 };
var average = values.Skip(2).Take(5).Average();
Use Linq:
var myList = new double[] {1,2,3}
var avg = myList.Where(i => i > 1 && i < 2).Avg();
Note that if you have the numbers with index 20 to 40, you don't have 20 numbers, you have 21 numbers.
You can use the Range method to create an IEnumerable for the indexes, then you can use the Average method to get the average of the numbers:
double average = Enumerable.Range(20, 21).Select(i => numbers[i]).Average();
double avg = array
.Skip(startIndex)
.Take(endIndex - startIndex + 1)
.Average();
Use Enumerable.Average:
double[] values = new[] { 1.0, 2.0, 3.14, 2.71, 9.1 };
double average = values.Where(x => x > 2.0 && x < 4.0).Average();
Therefore, to use this with your selection methods you should consider having those methods return IEnumerable<double>. So, as an example:
public IEnumerable<double> GreaterThan(double[] values, double value) {
for(int i = 0; i < values.Length; i++) {
if(values[i] > value) {
yield return values[i];
}
}
Then:
// values is double[]
double average = GreaterThan(values, 2.0).Average();
You can even make the above an extension method so that it reads nicely:
double average = values.GreaterThan(2.0).Average();
I would encourage you to write your filtering methods to return IEnumerable<double>.
You can use the skip and take methods of linq to choose particular indexes:
var myData = new double[] { ..... };
var average = myList.Skip(20).Take(21).Average();