How to Remove TopMost element From ArrayList in C# - c#

I have an Arraylist In Which I want to remove the single top element from Arraylist(i.e. POP in Stack),I have used .Remove() method, But it doesn't work,So How can i remove only single element from arraylist
For example-If arraytlist contains 96,97,98,99,100 When used .RemoveAt(0) Its going to remove the element 96,I want to remove the item 100 From arraylist ,So how can i remove this top item?

Try using RemoveAt:
ArrayList list = …
// remove the last item
list.RemoveAt(list.Count - 1);

You may try to use RemoveAt:
ArrayList ar = new ArrayList();
ar.Add("Delete");
ar.Add("The");
ar.Add("Top element");
ArrayList.RemoveAt(0);
Removes the element at the specified index of the ArrayList.
Also to quote the remarks:
In collections of contiguous elements, such as lists, the elements
that follow the removed element move up to occupy the vacated spot. If
the collection is indexed, the indexes of the elements that are moved
are also updated. This behavior does not apply to collections where
elements are conceptually grouped into buckets, such as a hash table.

int[] numbers = { 1, 3, 4, 9, 2, 4 };
int numToRemove = 1;
int numIdx = Array.IndexOf(numbers, numToRemove);
List<int> tmp = new List<int>(numbers);
tmp.RemoveAt(numIdx);
numbers = tmp.ToArray();

ArrayList myAL = new ArrayList();
....
myAL.RemoveAt(myAL.Count - 1);

Try this
First you find the array length using below code
int length = yourarray.Length;
next put this length in removeat
yourarray.RemoveAt(length - 1);

Related

How to remove an element of List<int[]> in C#

I'm trying to program a Sudoku solver in C# in which I'm using a List of an integer array with all the positions of empty fields, because I need them in my algorithm.
In the progress of solving the Sudoku I need to remove those positions which got filled with a number. But somehow my list with empty positions does not get smaller, when I use the Remove-method.
I will explain my problem with a simplified example:
List<int[]> test1 = new List<int[]>();
test1.Add(new int[] { 0, 0 });
test1.Add(new int[] { 1, 7 });
test1.Remove(new int[] { 1, 7 });
The first line generates the list with my one dimensional integer array (which always consists of two values - one for the column and one for the row-number). The empty positions get added in a method, but in this example I just added them in these two lines.
Later on in my algorithm, I want to remove elements by using the Remove-function similarly to the Add-function. It throws no errors, even while compiling. However, it's not removing anything.
I tried using the RemoveAll-method, although I don't really understand, how it works and therefore didn't find a correct solution for my problem.
By trying out a List of integers (not an integer array) the Remove-method works perfectly, but in the case of an array it doesn't seem to work this way.
Even creating a seperat variable rem
int[] rem = new int[] { 1, 7 };
test1.Remove(rem);
does not work.
I'm a beginner so I don't really know if a List of arrays is the best solution in my case.
bool IntArrayPredicate(int[] element)
{
return element.SequenceEqual(new int[] { 2, 3 });
}
List<int[]> listOfIntArray = new List<int[]>();
listOfIntArray.Add(new int[] { 0, 0 });
listOfIntArray.Add(new int[] { 1, 7 });
listOfIntArray.Add(new int[] { 2, 3 });
listOfIntArray.RemoveAll(element => element.SequenceEqual(new int[] { 1, 7 })); //It Works!. Using lambda expresion. Remove by Comparing sequences that match equals.
int[] toRemove = listOfIntArray[0];
listOfIntArray.Remove(toRemove); //It works!. Remove element by exact reference.
listOfIntArray.Remove(new int[] { 2, 3 }); // Not working / References are different.
listOfIntArray.RemoveAll(IntArrayPredicate); // It works!. Same as using lambda but using method reference.
Console.WriteLine($"{nameof(listOfIntArray)} has {listOfIntArray.Count()} elements"); // Yup. 0 elements.
The reason you're not able to remove items from your list using the Remove method is that you're storing reference types in the List, but creating new references when trying to remove an item. Because reference types by default use a reference comparison (not a comparison of their fields) to determine equality, you won't be able to remove items in that way.
One way to resolve this is to create a reference to each object in the List<int[]> outside of the list creation itself. This way, you can use the existing reference as an argument to the Remove method, and, because it's referring to the same object that was added to the list, it will match and be removed:
// Here we have 'item1' and 'item2' that refer to the location of different int[]
int[] item1 = new int[] { 0, 0 };
int[] item2 = new int[] { 1, 7 };
// And now we use those references to add the int[] items to our list
List<int[]> test1 = new List<int[]>();
test1.Add(item1);
test1.Add(item2);
// Finally, we can remove an item using the same reference that we used to add it
test1.Remove(item2);
This is very clunky, however, since we now need to maintain an individual reference for every item in our list as well as the list itself.
Another way to resolve this would be to search for the item we want to remove using our own equality algorithm (rather than relying on the default equality that Remove uses). We can use FirstOrDefault to search for the first item that has a length of 2 and whose values match those that we want. It will return a reference to the item if it's found, or null if it's not found. We can use IndexOf to get the index of the item (or -1 if it's not found), and then pass that index to the RemoveAt method to remove it:
List<int[]> test1 = new List<int[]>();
test1.Add(new int[] { 0, 0 });
test1.Add(new int[] { 1, 7 });
int indexToRemove = test1.IndexOf(test1.FirstOrDefault(item =>
item.Length == 2 && item[0] == 1 && item[1] == 7));
if (indexToRemove >= 0) test1.RemoveAt(indexToRemove);
As you can see, what you're trying to do isn't super easy. As a suggestion to help you think about the problem in a different way, you might consider using a 2-dimensional array to store the sudoku grid. Normally we store the row in the first dimesion and the column in the second dimension:
int[,] grid = new int[9, 9];
You could potentially create a few of these, one to represent the puzzle solution, one to represent the puzzle shown to the user's (with just their guesses), maybe even one to store user's "notes" (if you allow them to tag a cell with possible values before committing to a guess), though that would likely need to be a string[,] or an int[,][].
Then the typical way to loop through the grid would be something like:
for (int row = 0; row < 9; row++)
{
for (int col = 0; col < 9; col++)
{
// Do something with the cell at 'row' 'col' here
// Set a value for this cell
grid[row, col] = row + col;
// Report the value of a cell
Console.WriteLine($"The value at row {row} and column {col} is {grid[row, col]}");
}
}

Subset pattern implementation

I am trying to write an implementation on C# of Subsets pattern read here 14 Patterns to Ace Any Coding Interview Question:
It looks obvious but confuses me. My research says me it should be implemented via Jagged Arrays (not Multidimensional Arrays). I started:
int[] input = { 1, 5, 3 };
int[][] set = new int[4][];
// ...
Could someone help with 2, 3 and 4 steps?
The instructions provided seem to lend themselves more to a c++ style than a C# style. I believe there are better ways than manually building arrays to get a list of subsets in C#. That said, here's how I would go about implementing the instructions as they are written.
To avoid having to repeatedly grow the array of subsets, we should calculate its length before we allocate it.
Assuming n elements in the input, we can determine the number of possible subsets by adding:
All subsets with 0 elements (the empty set)
All subsets with 1 element
All subsets with 2 elements
...
All subsets with n-1 elements
All subsets with n elements (the set itself)
Mathematically, this is the summation of the binomial coefficient. We take the sum from 0 to n of n choose k which evaluates to 2^n.
The jagged array should then contain 2^n arrays whose length will vary from 0 to n.
var input = new int[] { 1, 3, 5 };
var numberOfSubsets = (int)Math.Pow(2, input.Length);
var subsets = new int[numberOfSubsets][];
As the instructions in your article state, we start by adding the empty set to our list of subsets.
int nextEmptyIndex = 0;
subsets[nextEmptyIndex++] = new int[0];
Then, for each element in our input, we record the end of the existing subsets (so we don't end up in an infinite loop chasing the new subsets we will be adding) and add the new subset(s).
foreach (int element in input)
{
int stopIndex = nextEmptyIndex - 1;
// Build a new subset by adding the new element
// to the end of each existing subset.
for (int i = 0; i <= stopIndex; i++)
{
int newSubsetLength = subsets[i].Length + 1;
int newSubsetIndex = nextEmptyIndex++;
// Allocate the new subset array.
subsets[newSubsetIndex] = new int[newSubsetLength];
// Copy the elements from the existing subset.
Array.Copy(subsets[i], subsets[newSubsetIndex], subsets[i].Length);
// Add the new element at the end of the new subset.
subsets[newSubsetIndex][newSubsetLength - 1] = element;
}
}
With some logging at the end, we can see our result:
for (int i = 0; i < subsets.Length; i++)
{
Console.WriteLine($"subsets[{ i }] = { string.Join(", ", subsets[i]) }");
}
subsets[0] =
subsets[1] = 1
subsets[2] = 3
subsets[3] = 1, 3
subsets[4] = 5
subsets[5] = 1, 5
subsets[6] = 3, 5
subsets[7] = 1, 3, 5
Try it out!
What I find easiest is translating the problem from a word problem into a more logical one.
Start with an empty set : [[]]
So the trick here is that this word problem tells you to create an empty set but immediately shows you a set that contains an element.
If we break this down into arrays instead(because I personally find it more intuitive) we can translate it to:
Start with an array of arrays, who's first element is an empty array. (instead of null)
So basically
int[][] result = new int[]{ new int[0] };
Now we have somewhere to start from, we can start to translate the other parts of the word problem.
Add the First Number (1) to all existing subsets to create subsets: [[],[1]]
Add the Second Number (5) to all existing subsets ...
Add the Third Number (3) to all existing subsets ...
There's a lot of information here. Let's translate different parts
Add the 1st Number ...
Add the 2nd Number ...
Add the nth Number ...
The repetition of these instructions and the fact that each number 1, 5, 3 matches our starting set of {1, 5, 3} tells us we should use a loop of some kind to build our result.
for(int i = 0; i < set.Length; i++)
{
int number = set[i];
// add subsets some how
}
Add the number to all existing subsets to create subsets: [[],[1]
A couple things here stand out. Notice they used the word Add but provide you an example where the number wasn't added to one of the existing subsets [[]] turned into [[],[1]]. Why is one of them still empty if we added 1 to all of them?
The reason for this is because when we create the new subsets and all their variations, we want to keep the old ones. So we do add the 1 to [](the first element) but we make a copy of [] first. That way when we add 1 to that copy, we still have the original [] and now a brand new [1] then we can combine them to create [[],[1]].
Using these clues we can decipher that Add the number to all existing subsets, actually means make copies of all existing subsets, add the number to each of the copies, then add those copies at the end of the result array.
int[][] result = new int[]{ new int[0] };
int[] copy = result[0];
copy.Append(1); // pseudo code
result.Append(copy); // pseudo code
// result: [[],[1]]
Let's put each of those pieces together and put together the final solution, hopefully!
Here's an example that I threw together that works(at least according to your example data).
object[] set = { 1, 5, 3 };
// [null]
object[][] result = Array.Empty<object[]>();
// add a [] to the [null] creating [[]]
Append(ref result, Array.Empty<object>());
// create a method so we can add things to the end of an array
void Append<T>(ref T[] array, T SubArrayToAdd)
{
int size = array.Length;
Array.Resize(ref array, size + 1);
array[size] = SubArrayToAdd;
}
// create a method that goes through all the existing subsets and copies them, adds the item, and adds those copies to the result array
void AddSubsets(object item)
{
// store the length of the result because if we don't we will infinitely expand(because we resize the array)
int currentLength = result.Length;
for (int i = 0; i < currentLength; i++)
{
// copy the array so we don't change the original
object[] previousItemArray = result[i]; // []
// add the item to it
Append(ref previousItemArray, item); // [1]
// add that copy to the results
Append(ref result, previousItemArray); // [[]] -> [[],[1]]
}
}
// Loop over the set and add the subsets to the result
for (int i = 0; i < set.Length; i++)
{
object item = set[i];
AddSubsets(item);
}

Count of matching elements in a list and array

I have a list and an array. I want to find out the number/count of elements in the array that match those in the list
List<int> list = new List<int>{ 1, 2, 3, 4 };
int[] array = new int[] { 1, 2 };
Since the two matching elements are 1 and 2, I am expecting a result of count 2.
Can someone please point me in the right direction?
You can use a little Linq with the Count extension method:
var count = array.Count(list.Contains);
Or if you know that there are no duplicate values in the the array, you can use the Intersect method:
var count = array.Intersect(list).Count();
You can use:
int matches = list.Intersect(array).Count();
Note that this will only work if the list and array only contain unique values.

How to get items in a specific range (3 - 7) from list?

What would be the most efficient way to select all the items in a specific range from a list and put it in a new one?
List<DataClass> xmlList = new List<DataClass>();
This is my List, and I would like to put all the DataClass items between the range (3 - 7) in a new List.
What would be the most efficient way? A foreach loop that that count++ everytime untill he reaches the items between a the range and add those items to the new list?
The method you are seeking is GetRange:
List<int> i = new List<int>();
List<int> sublist = i.GetRange(3, 4);
var filesToDelete = files.ToList().GetRange(2, files.Length - 2);
From the summary:
// Summary:
// Creates a shallow copy of a range of elements in the source System.Collections.Generic.List<T>.
// Parameters:
// index:
// The zero-based System.Collections.Generic.List<T> index at which the range
// starts.
// count:
// The number of elements in the range.
If for any reason you don't like to use the GetRange method, you could also write the following using LINQ.
List<int> list = ...
var subList = list.Skip(2).Take(5).ToList();
List implements a CopyTo method that lets you specify the start and number of elements to copy. I'd suggest using that.
See: http://msdn.microsoft.com/en-us/library/3eb2b9x8.aspx
in c# 8 you can use Range and Index instead of Linq take and skip for List
notice: before using you should convert the list to array
Sample array:
string[] CountryList = { "USA", "France", "Japan", "Korea", "Germany", "China", "Armenia"};
var countryArray = CountryList.ToArray();
To get this result (element 1,2,3) ==> France Japan Korea
1: Get a range of array or list:
var newArr = countryArray[1..3]
2: Define Range object
Range range = 1..3;
var newArr = countryArray[range])
3: Use Index Object
Index startIndex = 1;
Index endIndex = 3;
var newArr = countryArray[startIndex..endIndex]

Removing strings from array C#

Is there a function to remove the last cell from array?
it's a string array like: {"a","b","c",""}.
The length of an array is immutable, but you can create a new array without the empty "" strings:
string[] newArray = myArray.Where(str => str != "").ToArray();
Erm... just resize it
Array.Resize(ref theArray, theArray.Length -1);
From the docs
public static void Resize(ref T[] array, int newSize)
If it's an array of strings, you can do something like:
string[] results = theArray.Where(s => !string.IsNullOrWhitespace(s)).ToArray();
If you are just going to iterate the results, there's no need to convert back into an array, and you can leave off the .ToArray() at the end.
Edit:
If you just want to remove the last cell, and not empty entries (as suggested by your edited version), you can do this using Array.Copy more efficiently than using the LINQ statement above:
string[] results = new string[theArray.Length - 1];
Array.Copy( theArray, results, results.Length );
An array is a fixed-size collection object. That makes it woefully inadequate for what you want to do. The best you could do is create another one with one less element. That's expensive.
Fix the real problem, this should be a List<string>, now it's simple.
var newArraySize = oldArray.Length - 1;
var newArray = new string[newArraySize];
Array.Copy(oldArray, newArray, newArraySize);
Create new array equal to existing array size -1
aNewArray = aOldArray
Ofcourse you could just null the last element in your array, but that would result in problems later. Otherwise, use a nice flexible list.
If you always want to get rid of the last element,
int[] a = new[] {1, 2, 3, 4, 5};
int[] b = new int[a.Length - 1];
Array.Copy(a, b, a.Length - 1);

Categories

Resources