Answer the question
In order to leave comments, you need to log in
The task is that I need to remove characters from the string by index from the array. The task with codewars (Last Survivor)?
All checks passed, but when the check goes with a huge string and a huge array, an error appears
System.IndexOutOfRangeException: Index was outside the bounds of the array. I must say right away that I know that this error appears when I try to access an index that is not in the array. But I can't figure out why this is happening in my case. PS In this task, arrays with numbers of length 1 less than strings are always given for verification!
public static string LastSurvivor(string letters, int[] coords)
{
for (int i = 0; i < coords.Length; i++)
{
if (coords[i] > letters.Length) i++;
letters = letters.Replace(letters[coords[i]].ToString(), "");
}
return letters;
}
Answer the question
In order to leave comments, you need to log in
You are doing the problem wrong.
A more correct option would be to create a StringBuilder and write into it all the letters that lie at indices that are not in the coords array.
You can understand why you go beyond the limits yourself - just try step by step to execute this function with the following parameters:
LastSurvivor ("123", new [] {3});
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question