resize array in for loop in c# [duplicate] - c#

This question already has answers here:
change array size
(15 answers)
Closed 3 months ago.
I need to run this loop and add the values to the length array each time the loop iterates, so far each time i loop the temp array is cleared so the data is getting lost each iteration. I want to resize the array and add the user input to the length array each iteration.
int[] lengthArray = new int [1];
for (int i = 0; i < lengthArray.Length; i++)
{
lengthArray[i] = int.Parse(Console.ReadLine());
int[] temp = new int [lengthArray.Length + 1] ;
temp[i] = lengthArray[i];
lengthArray = temp;
}

You probably want to store your result in a List<int> instead of an array int[] .
Then you each time you want to add an element in the lengthArray you can just call the Add method.

Related

How to change a list based on another list [duplicate]

This question already has answers here:
How to sort a list so that the same changes would happen in another list?
(3 answers)
Closed 3 months ago.
I have a question:
For example I had a list with 132 and a second list 123
I would want my 132 list.sort but the 123 list to sort like 132:
was:
132
123
After
123
132
Not switch place but if the first element changes position in list 1 so should list 2, please help.
This answer involves writing (or editing an existing) sorting algorithm.
In the example below, I've illustrated a way in Javascript to enhance a simple Bubble Sort algorithm to include a second array to manipulate aswell.
I know the question is for C#, but the same concepts apply.
The arrays need to have the same length, otherwise you will get errors.
// Bubblesort algorithm stolen from https://www.geeksforgeeks.org/bubble-sort/
// edited to include a second array (arr2) that mirrors the sorting of the first array
function swap(arr, xp, yp)
{
var temp = arr[xp];
arr[xp] = arr[yp];
arr[yp] = temp;
}
function bubbleSort( arr, arr2, n)
{
var i, j;
for (i = 0; i < n-1; i++)
{
for (j = 0; j < n-i-1; j++)
{
if (arr[j] > arr[j+1])
{
swap(arr,j,j+1);
// swap the elements of the second array aswell
swap(arr2,j,j+1);
}
}
}
}
// just a function for printing
function printArray(arr, size)
{
var i;
for (i=0; i < size; i++)
document.write(arr[i]+ " ");
document.write("<br />");
}
// the two arrays
var array1 = [5, 1, 4, 2, 8];
var array2 = [2, 3, 4, 5, 6];
var n = 5;
document.write("UnSorted arrays: <br />");
printArray(array1, n);
printArray(array2, n);
bubbleSort(array1, array2, n);
document.write("Sorted arrays: <br />");
printArray(array1, n);
printArray(array2, n);
If you run the above snippet, you see that the '1' in the second position of the first array has moved to the first position.
The second array had a '3' in the second position, which is also swapped to the first position, like the first array did.
Long story short: The second array mirrors the sorting of the first array.

Creating 1000 arrays and sorting them using the bubble and selection sort (C#) [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 4 years ago.
Improve this question
I am new to programming. C# is my first programming language.
I have an assignment where I have to create and test out a bubble sort algorithm and a selection sort algorithm using arrays. I think I understand those now.
The next part of the assignment I am having some trouble on.
I have to write a program that will ask the user for a number (n) and create 1000 arrays of n size.
So if the user enters 5 for the number, my program has to create and sort 1000 arrays that are of length 5.
I have to use the bubble sort and the selection sort methods I created.
After I do that, I have to initiate a variable called running_time to 0. I have to create a for loop that iterates 1000 times and in the body of the loop i have to create an array of n random integers.
Then I have to get the time and set this to the start time. My professor said to notice that the sort is started after each array is built, so I should time the sort process only.
Then I have to get the time and set it to end time. I have to subtract the start time from end time and add the result to the total time.
Once the program has run, note
1. the number of items sorted
2. the average running time for each array (total time/1000)
Then I have to repeat the process using 500, 2500, and 5000 as the size of the array.
This is my code for creating one array with n number of spaces and filled with random integers.
//Asks the user for number
Console.WriteLine("Enter a number: ");
n = Convert.ToInt32(Console.ReadLine());
//Creates an array of the length of the user entered number
int[] randArray = new int[n];
//Brings in the random class so we can use it.
Random r = new Random();
Console.WriteLine("This is the array: ");
//For loop that will put in a random number for each spot in the array.
for (int i = 0; i < randArray.Length; i++) {
randArray[i] = r.Next(n);
Console.Write(randArray[i] + " ");
}
Console.WriteLine();
THIS IS MY CODE FOR THE BUBBLE SORT ALGORITHM:
//Now performing bubble sort algorithm:
for (int j = 0; j <= randArray.Length - 2; j++) {
for (int x = 0; x <= randArray.Length - 2; x++) {
if (randArray[x] > randArray[x + 1]) {
temp = randArray[x + 1];
randArray[x + 1] = randArray[x];
randArray[x] = temp;
}
}
}
//For each loop that will print out the sorted array
foreach (int array in randArray) {
Console.Write(array + " ");
}
Console.WriteLine();
THIS IS MY CODE FOR THE SELECTION SORT ALGORITHM:
//Now performing selection sort algorithm
for (int a = 0; a < randArray1.Length - 1; a++) {
minkey = a;
for (int b = a + 1; b < randArray1.Length; b++) {
if (randArray1[b] < randArray1[minkey]) {
minkey = b;
}
}
tempSS = randArray1[minkey];
randArray1[minkey] = randArray1[a];
randArray1[a] = tempSS;
}
//For loop that will print the array after it is sorted.
Console.WriteLine("This is the array after the selection sort algorithm.");
for (int c = 0; c < randArray1.Length; c++) {
Console.Write(randArray1[c] + " ");
}
Console.WriteLine();
This is very overwhelming as I am new to this and I am still learning this language.
Can someone guide me on the beginning on how to create 1000 different arrays filled with random numbers and then the rest. I would appreciate it greatly. Thank you.
So you have a several questions that has overwhelmed you.
Let's look at each one
Take user input
Console.WriteLine("Enter a length");
while (!int.TryParse(Console.ReadLine(), out var length))
Console.WriteLine("omg! you had one job");
Calling a method with an out argument
Starting with C# 7.0, you can declare the out variable in the argument
list of the method call, rather than in a separate variable
declaration. This produces more compact, readable code, and also
prevents you from inadvertently assigning a value to the variable
before the method call. The following example is like the previous
example, except that it defines the number variable in the call to the
Int32.TryParse method.
Fill Array
private static Random _rand = new Random();
const string chars = "ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
...
public static string RandomString(int length)
{
var result = Enumerable.Range(0, length)
.Select(s => chars[_rand.Next(length)])
.ToArray();
return new string(result);
}
Create array of random chars
var arr = Enumerable.Range(0, size)
.Select(i => RandomString(length)).ToArray();
How to time something
var sw = Stopwatch.StartNew();
// something to time
var milliseconds = sw.ElapsedMilliseconds
Now map it all together, I'll leave these details up to you
Additional Resources
Enumerable.Range(Int32, Int32) Method
Generates a sequence of integral numbers within a specified range.
Enumerable.Select Method
Projects each element of a sequence into a new form.
Stopwatch Class
Provides a set of methods and properties that you can use to
accurately measure elapsed time.
Random Class
Represents a pseudo-random number generator, which is a device that
produces a sequence of numbers that meet certain statistical
requirements for randomness.

C# - Field values of an array picking up values of a loop [duplicate]

This question already has answers here:
How to get first N elements of a list in C#?
(7 answers)
How do I clone a range of array elements to a new array?
(26 answers)
Closed 5 years ago.
I'm training C# on a simple card game. I have methods that shuffle and deals the cards. I have a random deck that is well generated.
Is it possible to set an array for the player1 cards, picking up the first ten values of the array.
Here is a part of my code :
currentCard = 0;
public Card DealCard()
{
if (currentCard < deck.Length)
return deck[currentCard++];
else
return null;
}
I want to pick up for example ten first values of
deck[currentCard++]
Any suggestions will be appreciated, thanks for your help !
You mean you want to pull the first 10 enties into another array? Something like;
var player1Cards = deck.Take(10);
or
List<int> player1Cards = new List<int>();
for (int i = 0; i < 10; i++){
player1Cards.Add(deck[i]);
}

Resizing array to lose empty values

I have made a loop that loops for every month from a current age through year x, say 80.
I have an array yearCalculation years and every yearCalculation contains among other things an array of monthCalculation. (Just in case anyone wants to throw a comment about Lists, I am currently using arrays and want to see if there is an easy solution.)
This looks as following:
yearCalculations[] years = years.InstantiateArray(//Number of years, [80 minus age]//);
monthCalculations[] months = months.InstantiateArray(//Number of months in a year, [this should be 12]//);
After the instantiation I loop through all the periods and fill them with all sorts of calculations. (However, after age x is being reached, all calculations will result in zero):
for (int i = 0; i < yearCalculations.Length; i++) {
for (int j = 0; j < yearCalculations[i].monthCalculations.Length; j++) {
Double age = calculateAge(birthDate, dateAtTimeX);
if(age < ageX){
//Do all sorts of calculations.
}else{
//Break out of the loops
}
}
}
As you can understand at age X (80), the calculations will be complete, but the last yearcalculation will contain some results, without calculations being made. Lets say this is from month 7 and on. What is the easiest way to resize this array, removing all the months without calculations (So index 6 and on)?
Just for the sake of completeness, here is the instantiateArray function;
public static T[] InstantiateArray<T>(this T[] t, Int64 periods) where T : new()
{
t = new T[periods];
for (int i = 0; i < t.Length; i++){
t[i] = new T();
}
return t;
}
To remove blank values from the array you could use LINQ
var arr = years.Where(x => !string.IsNullOrEmpty(x)).ToArray();//or what ever you need
You can't resize an array.
To quote MSDN:
The number of dimensions and the length of each dimension are established when the array instance is created. These values can't be changed during the lifetime of the instance.
What methods like Array.Resize actually do is allocate a new array and copy the elements over. It's important to understand that. You're not resizing the array, but reallocating it.
So long as you're using arrays, in the end the answer is going to boil down to "allocate a new array, then copy what you want to keep over to it".
The Array.Resize method should do the trick with the new total length. You know the total new length to be the total old length - (12 - month as an int in year)

Filling an array of int at declaration [duplicate]

This question already has answers here:
Direct array initialization with a constant value
(6 answers)
Fastest way to fill an array with a single value [duplicate]
(3 answers)
Closed 8 years ago.
I'd like to declare an array of int rows with a variable size (X) and init all values to 1. For the moment I use this :
int[] rows = new int[X];
for (int i = 0; i < rows.Length; i++)
{
rows[i] = 1;
}
Is there any faster/shorter way to do it with some sort of fill(1) or int[] rows = new int[X] {1}; ?
LINQ:
int[] rows = Enumerable.Repeat(element:1, count: X).ToArray();// named parameter - X
// doesn't tell anything

Categories

Resources