getting out of range exception in bool array(c#) -
getting out of range exception in bool array(c#) -
im trying utilize random number to pull 30 strings out of array of 58 strings , using bool array check , create sure same number not called twice. method , programme crashes index out of range error. here method.
static string[] newlist(string[] s) { string[] newlist = {}; bool[] issearched = new bool[s.length]; random callorder = new random(); (int = 0; < 31; i++) { int number = callorder.next(0, s.length); if (issearched[number] == false) { newlist[number] = s[number]; issearched[number] = true;//this crashes though ide says issearced has 58 elements , random number smaller that. } else i--; } homecoming newlist; }
im sure simple can't figure out why index of 8 outside range of array of 58.
your array newlist (what confusing name) has no space store anything. line
string[] newlist = {};
declares array without setting space store element, when seek utilize indexer on exception.
i suggest utilize different approach find 30 strings passed array. using list<string>
, go on add together list until have 30 elements in list
static string[] newlist(string[] s) { list<string> selectedelements = new list<string>(); bool[] issearched = new bool[s.length]; random callorder = new random(); while(selectedelements.count < 30)) { int number = callorder.next(0, s.length); if (!issearched[number]) { selectedelements.add(s[number]); issearched[number] = true; } } homecoming selectedelements.toarray(); }
if prefer utilize arrays method couple of fixing required code
static string[] newlist(string[] s) { string[] newlist = new string[30]; bool[] issearched = new bool[s.length]; random callorder = new random(); (int = 0; < 30; i++) { int number = callorder.next(0, s.length); if (issearched[number] == false) { newlist[i] = s[number]; issearched[number] = true; } else i--; } homecoming newlist; }
the newlist array declared have space store 30 elements the loops 30 times (not 31 current code) the newlist should utilize indexer value of variable i
c#
Comments
Post a Comment