using System; using System.Collections.Generic; namespace Function_JosephusSurvivor { class Program { static void Main(string[] args) { //Debug purposes Console.WriteLine(JosSurvivor(7, 3)); Console.ReadKey(); } //Actual function: public static int JosSurvivor(int n, int k) { // n = amount of people(array size) // k = every k'th index will be yeeted List<int> list = new List<int>(); int iCounter = 1; //always count till the size of the list int iWatcher = 1; //always count till the size of k for (int i = 1; i <= n; i++) { list.Add(i); } do { if (iWatcher+1 == k) { list.RemoveAt(iCounter); iWatcher = 0; } iWatcher++; iCounter++; if (iCounter == list.Count) // -1 because index { iCounter = 0; } else if (iCounter > list.Count) { iCounter = 1; //if one is jumped due to deleteting } } while (list.Count != 1); return list[0]; //winner } } } My question is:
how could you make this more efficient? What could I do better?
I'm trying to submit this as my solution on a practicing page. Unfortunately, it always times out. Therefore I need to make this more efficient I believe.
Thanks in advance :)!
Also feel free to add fitting Tags :)!
Arrays overLists, because of double capacity allocation. Or it might be even better to useIEnumerables 2) Try to usestructs instead ofclasses for short-living small data objects. 3) Try to avoid to allocate space more than 85000 bytes for a single object, because they will be allocated on the LargeObjectHeap. 4) Try to use allocation optimised structures likeSpan,Memory,ArrayPool,StringBuilder, etc. \$\endgroup\$