C# variable or array with number range (example. 1 - 100) - c#

I'm fairly new to C# and I'm doing a school project, i need to figure out how to get a variable or an array with numbers from 1 to 100 without entering every single number in an array for example int[] numbersArray {1,2,3,4,5,6,7,8,9,10...}; because that takes a long time and doesn't look very efficient.
I'm using C# Visual Studio Express 2010. It would mean alot to me if you could answer this for me. I'm gonna be using it in an if statement like so:
if(numbersArray.Contains(numbersInput))
{
Console.WriteLine("numbersInput was a number from 1 to 100")
}

You can use Enumerable.Range to create a range of numbers:
int[] arr = Enumerable.Range(1, 100).ToArray();

If you're assignment is just to print a message if the input is within a range you simply can do this:
if (numbersInput >= 1 && numbersInput <= 100)
Console.WriteLine("numbersInput was a number from 1 to 100");
But if you really need to create an array with numbers 1..100 you can use a for-loop:
var numbersArray = new int[100];
for (var i = 1; i <= 100; i++)
numbersArray[i - 1] = i;
Or simply use a little Linq:
var numbersArray = Enumerable.Range(1, 100).ToArray();

you could just use a for loop with the iterator of the loop as the counter:
int[] numbersArray = new int[100] // initialise array to 100 elements.
for (int i = 1; i <= 100; i++)
{
numbersArray[i - 1] = i; // note we are using 0-based indexing to access elements of the array
}

Other way...
int[] arr = new int[100];
for(int i = 0; i < arr.Length; ++i)
{
arr[i]=i+1;
}

Related

How to append arrays in c#

I would like to get the output of this to be [1,2,3,4,...,200]. Any suggestions for how to go about this?
var Laser_data = 0;
var i = 0;
var j = 1;
int[] LaserData_200 = new int[200];
for (i = 0; i < LaserData_200.Length; i++)
{
Laser_data += j;
LaserData_200[i] = Laser_data;
Console.WriteLine(" " + LaserData_200[i]);
}
Current output:
1
2
3
4
ect.
Your array initialization and element assignment can be simplified massively. Your array is just the numbers 1 through 200 (inclusive). Enumerable.Range can generate that for you, then save it as an array.
int[] myArray = Enumerable.Range(1, 200).ToArray();
To print it all, string.Join it using a comma as a seperator.
Console.WriteLine($"[{string.Join(',', myArray)}]");
// [1,2,3,4,5,6,7,8,9,10,11,12,13, .... 200]
I see the title has nothing to do with the posted code.
So I am answering the question in the title.
Say you have two arrays a and b and you want to create a third array that combines the two arrays, then you write code like
int[] c = Enumerable.Concat(a, b).ToArray();
or you have and array a and you want to keep adding values to it in loop. When arrays are fixed size (a.IsFixedSize = true always) so you can do this efficiently.
The best solution is to use List<T> instead of an array
List<int> a = new List<int>()
for(int i=0; i<200; i++)
{
a.Add( i+1 );
}
and if you want an array in the end, you just do
int[] c= a.ToArray();

Duplicated elements from x array add into y array

I tried to find 2 or more same elements from array x and then that duplicate to add into new array Y
So if i have in x array number like: 2,5,7,2,8 I want to add numbers 2 into y array
int[] x = new int[20];
Random rnd = new Random();
int[] y = new int[20];
int counter = 0;
for (int i = 0; i < x.Length; i++)
{
x[i] = rnd.Next(1, 15);
for (int j=i+1; j< x.Length; j++)
{
if (x[i] == x[j])
{
y[counter] = x[i];
Console.WriteLine("Repeated numbers are " + y[counter]);
counter++;
}
else
{
Console.WriteLine("There is no repeated numbers, numbers that are in x are " + x[i]);
}
break;
}
}
But having problems with that, when it come to the if loop it doesn't want to proceed with executing if loop (even if condition is true)
If someone could give me some suggestion, that would be helpful, thank you
There are various logical errors in your use of for. You should work more on your logic, because while libraries can be learnt by rote, logical errors are more something that is inside you.
int[] x = new int[20];
Random rnd = new Random(5);
// You don't know the length of y!
// So you can't use arrays
List<int> y = new List<int>();
// First initialize
for (int i = 0; i < x.Length; i++)
{
x[i] = rnd.Next(1, 15);
}
// Then print the generated numbers, otherwise you won't know what numbers are there
Console.WriteLine("Numbers that are in x are: ");
for (int i = 0; i < x.Length; i++)
{
Console.WriteLine(x[i]);
}
// A blank line
Console.WriteLine();
// Then scan
for (int i = 0; i < x.Length; i++)
{
for (int j = i + 1; j < x.Length; j++)
{
if (x[i] == x[j])
{
y.Add(x[i]);
Console.WriteLine("Repeated numbers is " + x[i]);
}
}
}
// Success/failure in finding repeated numbers can be decided only at the end of the scan
if (y.Count == 0)
{
Console.WriteLine("There is no repeated numbers");
}
I've put some comments in the code (plus the changes)
And for debugging purpose, I suggest you use a fixed Random sequence. new Random(5) (or any other number) will return the same sequence every time you launch your program.
Note that if there are multiple repetitions of a number, like { 4, 4, 4 } then the y array will be { 4, 4 }
at first:
why do u use the 'break;' ?
second:
in the first for - loop u assign a random number to x[i]
but then in the nested second loop
u already ask x[j] to check for same values (but that doesn't exist yet)
there are so many ways to check if values are equal,
but i like your approach:
so what i would suggest:
make a for - loop and assign all the random numbers to int[] x
then think again how u can evaluate
x[0] = x[1] or x[2] or x[3] ...
Try to use Linq to find the duplicate in the Array
int[] x = new int[] { 2, 5, 7, 2, 8 };
int[] y;
var result = x.GroupBy(item => item)
.Select(grp => new { key = grp.Key, Count = grp.Count() });
y = result.Where(res => res.Count > 1).Select(res => res.key).ToArray();
int[] array = new int[5] {1,2,3,4,4};
List<int> duplitcateList = array.Where(x => array.Where(y => y == x).Count() > 1).Distinct().ToList();
or you can replace last line of above code with below.
List<int> duplitcateList = array.
GroupBy(x => x).Where(g => g.Count() > 1).Select(g => g.Key).ToList();
above code is using Linq.
suppose your first array (in question x) is array.
Linq will first check for all elements in to list which occur more then once, and select them distinctly and store it to duplicateList
if you need an array at the, you can simply convert this list to array by doing this,
int[] yArray = duplitcateList.ToArray();
Make use of linq in your code , as below
//first populate array x
var duplicates= xArray.GroupBy(x => x)
.Where(g => g.Count() > 1)
.Select(y => y.Key)
.ToArray();
linq query above make use of groupby and find duplicate i.e. element occuring more then one time in you array and then you select those element and return result
I think this will will be the most understandable solution without complicated extension methods:
int[] x = new int[20];
// there can be at most 10 duplicates in array of length of 20 :)
// you could use List<int> to easily add elements
int[] y = new int[10];
int counter = 0;
Random rnd = new Random();
// fill the array
for (int i = 0; i < x.Length; i++)
x[i] = rnd.Next(1, 15);
// iterate through distinct elements,
// otherwise, we would add multiple times duplicates
foreach (int i in x.Distinct())
// if the count of an elements is greater than one, then we have duplicate
if(x.Count(n => n == i) > 1)
{
y[counter] = i;
counter++;
}

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

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

Adding specific numbers from one sequence to another

I feel like this task should not be done this way...
My sequenceY length is not equal to number of steam numbers because you can't assign int[] length with int that have 0 as a starting value.
Therefore my sequenceY have a lot of 0 inside and I can't print the whole sequence. I even tried adding this after for loop:
sequenceY = new int[steamnumbercounter];
But it didn't work ... Why ?
My other question is how do programmers deal with sequences that have unknown length?
I managed to print only steam numbers but the task says print sequenceY not only part of it.
// 4. sequenceX[20] is made of random numbers from 1 to 30 ,
// sequenceY is made of steam numbers from sequenceX. Print sequneceY.
int[] nizx = new int[20];
int[] nizy = new int[20];
int n = 0;
int steamnumbercounter = 0;
Random rnd = new Random();
for (int i = 0; i < nizx.Length; i++)
{
nizx[i] = rnd.Next(1, 30);
if (nizx[i]%2==0)
{
nizy[n] = nizx[i];
n++;
steamnumbercounter++;
}
Console.Write("{0} , ", nizx[i]);
}
for (int i = 0; i < steamnumbercounter; i++)
{
Console.WriteLine("{0} , ",nizy[i]);
}
Partial code review along with an answer.
But it didn't work ... Why ?
That code didn't work because you're reassigning sequenceY to a completely new value.
My other question is how do programmers deal with sequences that have unknown length?
So, with that known we can do a few things here: create an array and use Array.Resize, use a List<T>, fill the initial array then swap it for one of the right size which is filled.
I'm going to assume a "steam" number is an even one.
Your naming is not good: nizx and nizy don't convey the meaning or line up with the problem.
I'm going to demonstrate the last option (since you stated that you don't know how to use many of the moderately complex parts of .NET in this class yet, which is fine): fill the initial array and swap it for a new one. This will run in O(n^2) time (sorta).
So, let's start with our source array.
int[] sequenceX = new int[20];
Next we'll define our destination array to be the same size as our source array. (This is the maximum number of values that could be stored in it, we'll shrink it later.)
int[] sequenceY = new int[sequenceX.Length];
Then we need a variable to hold how many numbers we found that meet our criteria:
int steamNumbers = 0;
And lastly, our Random.
Random random = new Random();
Then, we look through all our sequenceX as you did, but we'll update the logic a bit.
for (int i = 0; i < sequenceX.Length; i++)
{
sequenceX[i] = random.Next(1, 30);
if (sequenceX[i] % 2 == 0)
{
sequenceY[steamNumbers] = sequenceX[i];
steamNumbers++;
}
}
So our code looks almost the same as yours, but we have one more thing to do: since you only want sequenceY to contain steamNumbers we have to shrink it or something.
int[] tempSequenceY = sequenceY;
sequenceY = new int[steamNumbers];
for (int i = 0; i < steamNumbers; i++)
{
sequenceY[i] = tempSequenceY[i];
}
Now sequenceY only has your steam numbers in it.
Final code:
int[] sequenceX = new int[20];
int[] sequenceY = new int[sequenceX.Length];
int steamNumbers = 0;
Random random = new Random();
for (int i = 0; i < sequenceX.Length; i++)
{
sequenceX[i] = random.Next(1, 30);
if (sequenceX[i] % 2 == 0)
{
sequenceY[steamNumbers] = sequenceX[i];
steamNumbers++;
}
}
int[] tempSequenceY = sequenceY;
sequenceY = new int[steamNumbers];
for (int i = 0; i < steamNumbers; i++)
{
sequenceY[i] = tempSequenceY[i];
}
// Print your `sequenceY` here.
You could extract this to a method pretty easily as well:
public int[] GetSteamNumbers(int sequenceCount, int randomMinimum, int randomMaximum)
{
int[] sequenceX = new int[sequenceCount];
int[] sequenceY = new int[sequenceX.Length];
int steamNumbers = 0;
Random random = new Random();
for (int i = 0; i < sequenceX.Length; i++)
{
sequenceX[i] = random.Next(randomMinimum, randomMaximum);
if (sequenceX[i] % 2 == 0)
{
sequenceY[steamNumbers] = sequenceX[i];
steamNumbers++;
}
}
int[] tempSequenceY = sequenceY;
sequenceY = new int[steamNumbers];
for (int i = 0; i < steamNumbers; i++)
{
sequenceY[i] = tempSequenceY[i];
}
return sequenceY;
}
And then call it with:
int[] steamNumbers = GetSteamNumbers(20, 1, 30);
Of course, for the more advanced users (this doesn't help you, but it may help others) we can do something as follows using LINQ:
var random = new Random();
var sequenceY = Enumerable.Range(1, 20)
.Select(x => random.Next(1, 30))
.Where(x => x % 2 == 0)
.ToArray();
Which should have the same effect. (Just demonstrating that there are still things in C# to look forward to in the future.)
Disclaimer: I wrote this entire answer outside of the IDE and without actually compiling it, I make no guarantees to the accuracy of the code but the procedure itself should be fairly straight forward.
The thing with arrays in C# is that they are of fixed size.
You'll have to iterate through and re-create it or use a IEnumerable that has dynamic sizes, such as Lists.
Solution here would be to use a List that contains your integers and then you would use nizx.Add(rnd.Next(1, 30));
Elaborating on my comment above: You can create a 'fake' list by concatenating the values you need in a string, separated by commas. The string.Split(',') will give you the resulting array that you need.
Given a string of form "a,b,c,d" string.Split(',') will create the array ["a","b,"c","d"]. The code:
{
int[] nizx = new int[20];
string numberString = string.Empty;
int n = 0;
Random rnd = new Random();
for (int i = 0; i < nizx.Length; i++)
{
nizx[i] = rnd.Next(1, 30);
if (nizx[i] % 2 == 0)
{
numberString += nizx[i] + ",";
n++;
}
}
var numberArray = numberString.Split(',');
for (int i = 0; i < n; i++)
{
Console.WriteLine("{0} , ", numberArray[i]);
}
}

Categories

Resources