Instead of removing the first occurrence of a duplicated value, as my code currently does, how can I get it to delete the second occurrence instead?
namespace deletenumber
{
class Program
{
public static void Main(String[] args)
{
Random r = new Random();
int[] a = new int[10];
for (int i = 0; i < 10; i++)
a[i] = r.Next(1, 100);
for (int i = 0; i < 10; i++)
Console.WriteLine(" a [" + i + "] = " + a[i]);
Console.WriteLine();
Console.ReadLine();
Console.WriteLine("What number do you want to delete?");
int item = Convert.ToInt32(Console.ReadLine());
Console.WriteLine();
int index = Array.IndexOf(a, item);
a = a.Where((b, c) => c != index).ToArray();
Console.WriteLine(String.Join(", ", a));
Console.ReadLine();
}
}
}
-
3You should always reveal when you are submitting homework as a task, you should show what you have tried, and how you are unit testing. You do none of this.Morten Bork– Morten Bork2020年08月17日 16:22:28 +00:00Commented Aug 17, 2020 at 16:22
-
3@MortenBork let's please be more patient against new users. This is why this post exist.Arsen Khachaturyan– Arsen Khachaturyan2020年08月17日 16:26:22 +00:00Commented Aug 17, 2020 at 16:26
-
@McCloud54 please check this about how to ask questions in SO.Arsen Khachaturyan– Arsen Khachaturyan2020年08月17日 16:39:20 +00:00Commented Aug 17, 2020 at 16:39
-
It is unknown what the real task is. You may be asked to actually remove the second instance of that number (not the third or however many more there might be), also you may be asked to do this using constant space, and also in the most efficient way. In that sense, the question leaves too much to the imagination.insane_developer– insane_developer2020年08月17日 16:43:32 +00:00Commented Aug 17, 2020 at 16:43
2 Answers 2
I'm not sure why exactly you might want to delete only the second occurrence because there should be no matter which one of the duplicates is removed, correct?
Anyway, there are several ways of achieving what you want. I will not directly write a solution here, but will propose the methods you can use in order to achieve what you want:
- Array.LastIndexOf
- Use the same
IndexOf
method again to find the second occurrence, by starting the search from the previous occurrence (myArray.IndexOf("string", last_indexof_index);
)
Generally, consider using a HashSet<T>
(official docs here) if you want to have a collection of unique elements.
You can also convert your existing collection to HashSet<int>
:
int[] a = new int[10];
var set = new HashSet<int>(a);
1 Comment
You could convert your array to a List and then just remove the index before casting it back to an array:
var list = new List<int>(a);
list.RemoveAt(index);
a = list.ToArray();