Reputation: 56
So let's say I have a base int[] tab
array with 100 elements. I want to perform Erastotenes' Sieve using tmp array storing not compatibile elements. Since I don't know exactly how many elements will land in this array, I declare it as new int[100]
. But is there any way to shrink that array after performing population task? Like for example, I end up with 46 numbers instead of 100, so I'd like to shrink that array's size accordingly, based on the number of said elements. I'd like to avoid manual resize, I'd rather do it programatically.
Sample code:
int[] tab = new int[100];
int[] tmp = new int[100];
for(int i = 0; i < tab.Length; i++) {
tab[i] = i;
}
EDIT. One idea that came to my mind is to perform while
loop strictly counting amount of elements in tmp array which could help me determine its final size.
EDIT 2. Working solution:
int[] tab = new int[100];
List<int> tmp = new List<int>();
List<int> se = new List<int>();
for(int i = 0; i < tab.Length; i++)
{
tab[i] = i + 2;
}
se.Add(tab[0]);
se.Add(tab[1]);
for (int i = 2; i < tab.Length; i++)
{
if (tab[i] % 2 == 0 || tab[i] % 3 == 0)
{
if (tmp.IndexOf(tab[i]) == -1)
{
tmp.Add(tab[i]);
}
}
}
int k = 3;
int value;
while(k < tab.Length)
{
if(tmp.IndexOf(tab[k]) == -1) {
value = tab[k];
for (int i = k; i < tab.Length; i++)
{
if(tmp.IndexOf(tab[i]) == -1)
{
if(tab[i] % value == 0 && tab[i] != value)
{
tmp.Add(tab[i]);
}
else
{
if(se.IndexOf(tab[i]) == -1)
{
se.Add(tab[i]);
}
}
}
}
}
k++;
}
Console.WriteLine("Zawartość tablicy początkowej:");
for(int i = 0; i < tab.Length; i++)
{
Console.Write(tab[i] + " ");
}
Console.WriteLine();
Console.WriteLine();
Console.WriteLine("Elementy wykluczone:");
foreach(int t in tmp)
{
Console.Write(t + " ");
}
Console.WriteLine();
Console.WriteLine();
Console.WriteLine("Sito Erastotenesa:");
foreach (int s in se)
{
Console.Write(s + " ");
}
Console.WriteLine();
Console.WriteLine();
Upvotes: 0
Views: 143
Reputation: 138
public static void Resize<T> (ref T[]? array, int newSize);
This method allocates a new array with the specified size, copies elements from the old array to the new one, and then replace the old array with the new one. the array must be a one-dimensional array. Changes the number of elements of a one-dimensional array to the specified new size.
You can read the full article here
Upvotes: 0
Reputation: 32780
No, you can't shrink an array (or grow, for that matter). You can create a new array with the correct size and copy the data to the new one, but an array, once created, can not change size.
The easiest way to achieve this is using List<T>
which is nothing more than a thin wrapper over an array that hides away all the plumbing of how and when the underlying array needs to grow and copying data from the "depleted" to the newer array.
Once you've populated the list, if you need an array then simply call ToArray()
.
Upvotes: 1