Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Deleting Last Item from Array of String

I'm working on a simple blackjack game project. Firstly I create the array of cards:

string[] deck = { "2", "3", "4", "5", "6", "7", "8", "9", "10", "J", "Q", "K", "A", }; 

than I multiply it 4 and given deckNumber:

newDeck = Enumerable.Repeat(deck, deckNumber*4).SelectMany(x => x).ToArray(); 

when I want to delete last card from array I apply this:

newDeck = newDeck.Where(w => w != newDeck.Last()).ToArray(); 

so the problem is that code doesn't removes last item from array, acts like there are multiple arrays and removes all last elements from them. For example with one deck:

cards: 2 3 4 5 6 7 8 9 10 J Q K A 2 3 4 5 6 7 8 9 10 J Q K A 2 3 4 5 6 7 8 9 10 J Q K A 2 3 4 5 6 7 8 9 10 J Q K A  

when I apply my remove command it become:

cards: 2 3 4 5 6 7 8 9 10 J Q K 2 3 4 5 6 7 8 9 10 J Q K 2 3 4 5 6 7 8 9 10 J Q K 2 3 4 5 6 7 8 9 10 J Q K  

it removes all the A's from array. But I want to remove only the last item from whole array. Whats the problem how can I solve this?

like image 989
JayGatsby Avatar asked Nov 15 '14 13:11

JayGatsby


People also ask

How can you remove the last item in an array?

JavaScript Array pop() The pop() method removes (pops) the last element of an array. The pop() method changes the original array. The pop() method returns the removed element.

How do you insert and remove the last element of an array?

The array_pop() function, which is used to remove the last element from an array, returns the removed element.

How do I remove the last element?

To remove last array element in JavaScript, use the pop() method. JavaScript array pop() method removes the last element from an array and returns that element.

How do you remove the last two elements of an array?

Use the splice() method to remove the last 2 elements from an array, e.g. arr. splice(arr. length - 2, 2) . The splice method will delete the 2 last elements from the array and return a new array containing the deleted elements.


2 Answers

To remove just the last element use this:

newDeck = newDeck.Take(newDeck.Count() - 1).ToArray(); 

Your solution removes all Elements that are equal to the last element. For a string, this means, it removes all elements equal to A

like image 136
Flat Eric Avatar answered Oct 13 '22 14:10

Flat Eric


You can use Array class to resize:

Array.Resize(ref result, result.Length - 1); 
like image 26
Ahmet Arslan Avatar answered Oct 13 '22 16:10

Ahmet Arslan