Using specific array count - c#

My array max size is 20. If I were to enter data that would be less than 20,how do I get it where my program only counts the used arrays?
for (int i = 0; i < Score.Length; i++)
{
sum = sum + Score[i];
}
average = sum / Score.Length;
If I use this for loop above, it always divides by 20 for the average. I need it to only count the ones I entered, not 20. I would prefer solutions using arrays

If you insist in using arrays, then you must keep track of how many items you added to the array, like:
int[] Score = new int[20];
Random rdn = new Random();
int size=0;
for(int i=0;i<rdn.Next(0,20);i++)
{
Score[i] = rdn.Next();
size++;
}
int sum = 0;
for (int i = 0; i < size; i++)
{
sum = sum + Score[i];
}
double average = sum / size;
A better option is to use the List class that keep track for you of the number of items you add
List<int> Score = new List<int>();
Random rdn = new Random();
for(int i=0;i<rdn.Next(0,20);i++)
{
Score.Add(rdn.Next());
}
int sum = 0;
for (int i = 0; i < Score.Count; i++)
{
sum = sum + Score[i];
}
double average = sum / Score.Count;
And of course, as you didn't say the type of your data you could use other data types, like double, float, long, decimal for both solutions.

That is probably an overkill, but another approach would be to use a SparseVector class of the Math.Numerics package:
Sparse Vector uses two arrays which are usually much shorter than the vector. One array stores all values that are not zero, the other stores their indices.
PM > Install-Package MathNet.Numerics
var vector = SparseVector.Build.SparseOfArray(Score);
var sum = vector.Sum();
Sum() will only go through non-empty elements.

You need to keep track of the record that are != 0, so
int count = 0;
for(int i = 0; i < array.Length; i++)
{
if ( array[i] != 0 )
{
count++;
sum += array[i];
}
}
average = sum / count;
And beware of division by 0 ;)

Related

Copy odd numbers from array into another array

Im new to programming and struggling with this task:
In array X [20] random numbers from 1 to 30 are entered, in array Y enter only odd numbers from array X.
Print down Y.
int[] x = new int[20];
Random rnd = new Random();
int counter = 0;
int[] y;
for (int i = 0; i < x.Length; i++)
{
x[i] = rnd.Next(1, 30);
if (x[i] % 2 !=0 )
{
y = new int[counter];
counter++;
y[counter] = x[i];
}
}
foreach (int number in y)
{
Console.WriteLine(number);
}
Im having problems to fill Y array with odd numbers without defining length of Y, I tried with adding counter but getting some errors all the time,
If someone can help me with some suggestions that would be helpful, thank you!
This looks like homework, so I guess using a more appropriate collection such as a List<int> is out of the question, just as using Linq.
At y = new int[counter]; you're reinitializing the array. This happens each iteration, so your final array only holds the latest added value, and all values before that will be set to their default: 0.
You could've seen this by debugging your code by setting breakpoints, stepping through the code and inspecting your variables. You could then also have provided a more proper problem description than "getting some errors".
If you know the input is never larger than 20, you can initialize the output array to the same size and keep a counter of how many values you copied (the latter of which you already do).
Then when printing, only print the elements up till that count with a for loop instead of foreach.
So something like this:
int[] x = new int[20];
int[] y = new int[x.Length];
Random rnd = new Random();
int counter = 0;
for (int i = 0; i < x.Length; i++)
{
x[i] = rnd.Next(1, 30);
if (x[i] % 2 != 0)
{
y[counter] = x[i];
counter++;
}
}
for (int i = 0; i < counter; i++)
{
Console.WriteLine(y[i]);
}
Your problem is that you create a new y array for each odd number you find. You need to create the array only once and then fill it.
Since you don't know how many odd numbers there will be, I suggest to use a List<int> instead:
int[] x = new int[20];
Random rnd = new Random();
List<int> y = new List<int>(); // create the list before the loop
for (int i = 0; i < x.Length; i++)
{
x[i] = rnd.Next(1, 30);
if (x[i] % 2 !=0 )
y.Add(x[i]); // add odd number to list
}
foreach (int number in y)
{
Console.WriteLine(number);
}
See, In your case you are not aware about the number of odd numbers in that random array. so Array will not be a right choice here if you are following the current implementation. If you want the output as array, then Why not a simple LINQ with Where like this example:
First you collect all random numbers to your array as you are doing currently:
int[] randomIntegers = new int[20];
Random rnd = new Random();
for (int i = 0; i < randomIntegers.Length; i++)
{
randomIntegers[i] = rnd.Next(1, 30);
}
Now you have the all random numbers in x now perform the following operation:
int[] oddValues = randomIntegers.Where(a=> a % 2 !=0).ToArray();

C#: finding the sum in a for loop

the question asks:
Write a program that reads from the screen two integer numbers min and max and outputs the sum of all squares of integers between min(including) and max(not including). If min is bigger than max, the program should output "min should be smaller than max!". Example:
>4
>9
190 (= 4² + 5² + 6² + 7² + 8²)
>14
>3
min should be smaller than max!
my code:
using System;
namespace ForLoops
{
class SumOfSquares
{
static void Main(string[] args)
{
int sum = 0;
int min = int.Parse(Console.ReadLine());
int max = int.Parse(Console.ReadLine());
for (int i = min; i < max; i = i++)
{
sum = i * i;
}
Console.WriteLine(sum);
}
}
}
I keep getting 68 when i should get 190.
So the answer is you make it to For Loop statement so you can have the 2 examples. Answers at the same time.
int min = int.Parse(Console.ReadLine());
int max = int.Parse(Console.ReadLine());
if(min > max)
{
Console.WriteLine("min should be smaller than max!");
}
else
{
int sum = 0;
for(int i = min; i < max; i++)
{
sum = sum + i*i;
}
Console.WriteLine(sum);
}
There are two flaws in your code:
The post-increment operator i++ increments i, but returns the previous value. So by i = i++ you never increase i because you always reassign the value as it was before the increment. This leads to an infinite loop.
You didn't sum up the products, but only assigned individual productes with sum = i * i;. You need to add them with sum += i*i;.
So your final loop could look like that:
int sum = 0;
for (int i = min; i < max; i++)
sum += i * i;
Linq is altertative to get rid of explicit loops (and let .net do the work for you):
using System.Linq;
...
int min = 4;
int max = 9;
int sum = Enumerable
.Range(min, max - min) // from min to max (not included)
.Sum(x => x * x); // sum up squares

Generating an array of numbers based off the smallest numbers in other arrays?

How do I go about making an array of numbers based off of the lowest values generated in other arrays? I have made an array that generates numbers between -1000 and 1000 and calculates the the lowest number from that; my problem comes after that I believe. I cant figure out how to add the lowest value to the "lowestNumbers" array.
static void Main(string[] args)
{
//ints and arrays used in the program.
int min = -1000;
int max = 1000;
int currentMinimum = 1000;
int[] numbers = new int[10];
int[] lowestNumbers = new int[numbers.Length];
Random rndm = new Random();
//Using a loop to create random numbers within numbers array between -1000 and 1000.
for (int i = 0; i < lowestNumbers.Length; i++)
{
if (i < lowestNumbers.Length)
{
for (int index = 0; index < numbers.Length; index++)
{
if (index < numbers.Length)
{
numbers[index] = rndm.Next(min, max);
}
}
for (int index = 0; index < numbers.Length; index++)
{
if (numbers[index] < currentMinimum)
currentMinimum = numbers[index];
}
}
lowestNumbers[i] = currentMinimum;
}
foreach (int value in lowestNumbers)
Console.WriteLine(value);
Console.WriteLine("//////////////////////////////////////////////////////////////////////////");
}
}
}
Use the power of Linq:
var numbers = Enumerable.Range(1, 100).Select(_ => rndm.Next(min, max)).ToArray();
var lowest = numbers.Min();
Based off the answer of #Laoujin, but slightly expanded a bit.
This will generate 1000 integers, from -1000 to 1000, and give you an array of the 100 lowest. I added 1 to max in the call to Random.Next(Int32, Int32) since maxValue is exclusive, otherwise the number 1000 would never show up in the resulting array.
var numbers = Enumerable.Range(1, 1000).Select(_ => rndm.Next(min, max+1)).ToArray();
var lowest = numbers.OrderBy(n => n).Take(100).ToArray();
As an extra note, if you are confused about the _ in the first line (many people are, the first time they see it used this way), that is just commonly used to denote an unused argument in a lambda expression. In this case, that variable contains the current number generated from Enumerable.Range() via the Select() call, but since it isn't being used, it is just named _. This isn't enforced by the language in any way, it is a common pattern that lots of programmers use.
That might contain duplicates though, so if you don't want them, you can pass the list though IEnumerable.Distinct() first, which returns only unique items:
var lowest = numbers.Distinct().OrderBy(n => n).Take(100).ToArray();
If you want the absolute lowest number from the first array, you can just do:
var lowestNumber = numbers.Min();

Almost Ordered not sorting the exact amount of values i give it

this is a really easy question but i cant figure out a way around it. Apparently the almost ordered has a bug that it might randomize a little bit more than you ask it. the code is rather simple:
public void Section1Task1AlmostOrdered(int arraySize, int percentage)
{
int[] testArray = new int[arraySize];
Console.WriteLine("Ordered List: ");
for (int i = 1; i <= testArray.Length; i++)
{
testArray[i-1] = i;
Console.Write(i + "\t");
}
Console.WriteLine("Almost Ordered List: ");
testArray = shuffler.AlmostOrdered(arraySize, percentage);
for (int i = 0; i < testArray.Length; i++)
{
Console.Write(testArray[i] + "\t");
}
}
The shuffler is this part of the code:
public int[] AlmostOrdered(int n, double p)
{
if (p > 100)
{
throw new InvalidOperationException("Cannot shuffle more than 100% of the numbers");
}
int shuffled = 0;
//Create and Populate an array
int[] array = new int[n];
for(int i = 1; i <= n; i++)
{
array[i-1] = i;
}
//Calculate numbers to shuffle
int numsOutOfPlace = (int) Math.Ceiling(n * (p / 100));
int firstRandomIndex = 0;
int secondRandomIndex = 0;
do
{
firstRandomIndex = this.random.Next(n-1);
// to make sure that the two numbers are not the same
do
{
secondRandomIndex = this.random.Next(n - 1);
} while (firstRandomIndex == secondRandomIndex);
int temp = array[firstRandomIndex];
array[firstRandomIndex] = array[secondRandomIndex];
array[secondRandomIndex] = temp;
shuffled++;
}
while (shuffled < numsOutOfPlace);
return array;
}
When i enter values 10 for array size and 40 for percentage to be shuffled, it is shuffling 5 numbers instead of 4. Is there a way to perfect this method to make it more accurate?
Likely the problem is with the calculation:
int numsOutOfPlace = (int)Math.Ceiling(n * (p / 100));
So if p=40 and n=10, then in theory you should get 4. But you're dealing with floating point numbers. So if (p/100) returns 0.400000000001, then the result will be 4.000000001, and Math.Ceiling will round that up to 5.
You might want to replace Math.Ceiling with Math.Round and see how that works out.

How to find the smallest value in an array without using C# Math function?

I am using C# and I am doing some questions for revision. I am trying to find the smallest value in a randomly generated array (which I coded). My teacher requires us to find the smallest value in that array without using the .Min function, because this is an algorithm module. Code below shows what I have coded to create the array. Have no idea how to proceed from here. Thank you guys.
int[] myRandom = new int[10];
int min = 0;
int max = 19;
Random randNum = new Random();
for (int i = 0; i < 10; i++)
{
myRandom[i] = randNum.Next(min, max);
}
for (int i = 0; i < 10; i++)
{
Console.WriteLine(myRandom[i]);
}
The easy way is using Min() linq extension method:
var min = myRandom.Min();
Console.WriteLine(min);
But if you need to do it manually you can do this:
//int min = int.MaxValue; //This variable stores current min value during each iteration.
int min = myRandom[0]; //If first value of myRandom is the minimum then ok, you already have it, if not it will be replaced in iterations
for (int i = 0; i < myRandom.Length; i++)
if (myRandom[i] < min) //Compare each value of the array with the current min value
min = myRandom[i];
Console.WriteLine(min);
Here is the best solution. You find the min value and generate the array at the same time, like this:
int minValue = int.MaxValue;
for (int i = 0; i < 10; i++)
{
myRandom[i] = randNum.Next(min, max);
if (myRandom[i] < minValue)
{
minValue = myRandom[i];
}
}
Console.WriteLine(minValue);
By doing this, you don't have to loop the array the second time to find the min value.

Categories

Resources