IndexOutOfRangeException ? - c#

In this following code i am receiving and out of range exception.
private void btnRoll_Click(object sender, EventArgs e)
{
int success4 = 0;
int success6 = 0;
int success8 = 0;
int success10 = 0;
int success20 = 0;
int botch4 = 0;
int botch6 = 0;
int botch8 = 0;
int botch10 = 0;
int botch20 = 0;
if (cbnd4.SelectedIndex != 0)
{
int value = 4;
int arraySize = (int)cbnd4.SelectedIndex;
int[] refArray = randomNumber(value, arraySize);
foreach (int i in refArray)
{
if (cbGame.SelectedIndex == 1)
{
if (refArray[i] >= 2)
{
success4++;
}
if (refArray[i] == 1)
{
botch4++;
}
}
if (cbGame.SelectedIndex == 2)
{
if(refArray[i] >= 2)
{
success4++;
}
if (refArray[i] == 1)
{
botch4++;
}
}
}
}
/* if (cbmd4.SelectedIndex != 0)
{
}
*/
if (cbnd6.SelectedIndex != 0)
{
int value = 6;
int arrySize = (int)cbnd6.SelectedIndex;
int[] refArray = randomNumber(value, arrySize);
foreach (int i in refArray)
{
if (cbGame.SelectedIndex == 1)
{
if (refArray[i] >= 4)
{
success6++;
} if (refArray[i] == 1)
{
botch6++;
}
}
if (cbGame.SelectedIndex == 2)
{
if (refArray[i] >= 4)
{
success6++;
}
if (refArray[i] == 1)
{
botch6++;
}
}
}
}
if (cbnd8.SelectedIndex != 0)
{
int value = 8;
int arrySize = (int)cbnd8.SelectedIndex;
int[] refArray = randomNumber(value, arrySize);
foreach (int i in refArray)
{
if (cbGame.SelectedIndex == 1)
{
if (refArray[i] >= 5)
{
success4++;
}
if (refArray[i] == 1)
{
botch8++;
}
}
if (cbGame.SelectedIndex == 2)
{
if (refArray[i] >= 5)
{
success4++;
}
if (refArray[i] == 1)
{
botch8++;
}
}
}
}
if (cbnd10.SelectedIndex != 0)
{
int value = 10;
int arrySize = (int)cbnd10.SelectedIndex;
int[] refArray = randomNumber(value, arrySize);
foreach (int i in refArray)
{
if (cbGame.SelectedIndex == 1)
{
if (refArray[i] >= 7)
{
success10++;
}
if (refArray[i] == 1)
{
botch10++;
}
}
if (cbGame.SelectedIndex == 2)
{
if (refArray[i] >= 7)
{
success10++;
}
if (refArray[i] == 1)
{
botch10++;
}
}
}
}
if (cbnd20.SelectedIndex != 0)
{
int value = 20;
int arrySize = (int)cbnd20.SelectedIndex;
int[] refArray = randomNumber(value, arrySize);
foreach (int i in refArray)
{
if (cbGame.SelectedIndex == 1)
{
if (refArray[i] >= 16)
{
success20++;
}
if (refArray[i] == 1)
{
botch20++;
}
}
if (cbGame.SelectedIndex == 2)
{
if (refArray[i] >= 7)
{
success20++;
}
if (refArray[i] == 1)
{
botch20++;
}
}
}
}
lBotch_Result.Text = Convert.ToString(botch4 + botch6 + botch8 + botch10 + botch20);
lSuccess_Result.Text = Convert.ToString(success4 + success6 + success8 + success10 + success20);
MessageBox.Show("d4 successes: " +
success4.ToString() +
"\r\nd6 Successes: " +
success6.ToString() +
"\r\nd8 Successes: " +
success8.ToString() +
"\r\nd10 Successes: " +
success10.ToString() +
"\r\nd20 Successes: " +
success20.ToString() +
"\r\nd4 Botches: " +
botch4.ToString() +
"\r\nd6 Botches: " +
botch6.ToString() +
"\r\nd8 Botches: " +
botch8.ToString() +
"\r\nd10 Botches: " +
botch10.ToString() +
"\r\nd20 Botches: " +
botch20.ToString());
}
The Out of ranged exception occurs when if(refArray[i] >= 7) and the refArray.Length contains an odd int value.
here is the Exception Output:
System.IndexOutOfRangeException was
unhandled
Message="IndexOutOfRangeException"
StackTrace:
at Table_Top_Game_Dice.Form1.btnRoll_Click(Object
sender, EventArgs e)
at System.Windows.Forms.Control.OnClick(EventArgs
e)
at System.Windows.Forms.Button.OnClick(EventArgs
e)
at System.Windows.Forms.ButtonBase.WnProc(WM
wm, Int32 wParam, Int32 lParam)
at System.Windows.Forms.Control._InternalWnProc(WM
wm, Int32 wParam, Int32 lParam)
at Microsoft.AGL.Forms.EVL.EnterMainLoop(IntPtr
hwnMain)
at System.Windows.Forms.Application.Run(Form
fm)
at Table_Top_Game_Dice.Program.Main()
any advice here would be greatly appreciated. i have been pounding my head against the wall for 5 hours trying to fix this.
oh, the refArray gets it values from the following function: (if it helps)
private int[] randomNumber(int value, int arraySize)
{
int[] randArray = new int[arraySize];
maxValue = value;
Random rand = new Random();
for (int i = 0; i < arraySize; i++)
{
randArray[i] = rand.Next(minValue, maxValue);
}
return randArray;
}

You are obviously trying to access an array element beyond the end of the array.
The randomNumber()method generates an array of random numbers where the size of the array and the maximum value are independent. Therefore it might return { 1, 7, 13 } if called with arraySize 3 and value 20.
Then you iterate over the array using foreach (int i in refArray). In consequence there will be three iterations with i set to 1, then 7, and finally 13.
So if you access the array using refArray[i] you try to access the array elements and indexes 1, 7, and 13 and therefore get an IndexOutOfRangeException in the second iteration because you try to access the element at index 7 while the array contains only 3 elements.
Did you intend for (int i = 0; i < refArray.Length; i++) instead of the foreach loop?

Isn't this piece of code able to produce an int that is equal to the size of the array and subsequently cause an outofrange exception when reading that item from the array by i.
int[] refArray = randomNumber(value, arraySize);
foreach (int i in refArray)
{
if (cbGame.SelectedIndex == 1)
{
if (refArray[i] >= 2)
{
success4++;
}
if (refArray[i] == 1)
{
botch4++;
}
}

I didn't found the error, but you are repeating a lot of code. Try to encapsulate all these code inside of each "if (cbndXX.SelectedIndex != YY) inside a function.
Something like this:
private void RefactorizedFunction(ComboBox cmb, ComboBox cbGame, ref int success, ref int botch, int value, int maxsuxcess)
{
var arraySize = (int)cmb.SelectedIndex;
int[] refArray = randomNumber(value, arraySize);
foreach (int i in refArray) //WARNING HERE...
{
if (cbGame.SelectedIndex == 1)
{
if (refArray[i] >= maxsuxcess)
{
success++;
}
if (refArray[i] == 1)
{
botch++;
}
}
if (cbGame.SelectedIndex != 2) continue;
if (refArray[i] >= maxsuxcess)
{
success++;
}
if (refArray[i] == 1)
{
botch++;
}
}
}
It is not tested, and it will not solve your problem, but I'm sure your code will be easier to debug. There is other ways to improve your code, like using a dictionary or arrays instead of all these successXX and botchXX vars but... step by step.

Related

Index was outside the bounds of the array of type string

I am creating a patience clock game and I have trouble with the cards index array that is of type string.
foreach (string deck in decks)
{
string[] cards = deck.Split(' ');
int exposedCards = 0;
string lastExposedCard = "";
for (int i = 12; i >= 0; i--)
{
if (i + exposedCards >= 12)
{
if (i < cards.Length)
{
lastExposedCard = cards[i];
break;
}
}
int targetIndex = (i + exposedCards) % cards.Length;
if (targetIndex >= 0 && targetIndex < cards.Length)
{
if (cards[i][0] == cards[targetIndex][0] ||
cards[i][1] == cards[targetIndex][1])
{
exposedCards++;
}
}
I am trying to get an output

Find inconsistent and consecutive objects from List in C#

I'm having trouble with getting a consecutive and nonconsecutive number from list. I'm sure it's pretty simple, but i can't get it.
If consecutiveNum=2, then if result from before last and last is equal, i need to throw an exception.
If nonConsecutiveNum=4, then if from 10 pieces there are 4 with same result, i need to throw an exception.
I'm trying with nested loops and couple checks, but i didn't succeeded at all. Same is for both cases, i tried a couple solutions with System.LINQ, but again i don't get the result i need.
Thanks in advance to all of you!
int consecutiveNum = 2;
int nonConsecutiveNum = 4;
int counter = 1;
var sensInfo = new ResultInfo()
{
Product = CurrentLot.Info.Product,
Result = code
};
if (consecutiveNum > 0)
{
for (int i = ListSensors.Count + 1; i >= 0; i--)
{
if (sensInfo.Result == ListSensors[i].Result)
{
counter++;
if (counter >= consecutiveNum)
{
throw new Exception("Consecutive num");
}
}
}
}
if (nonConsecutiveNum > 0)
{
for (int i = 0; i < ListSensors.Count; i++)
{
for (int j = i + 2; j < ListSensors.Count - 2; j++)
{
if (ListSensors[i].Result == ListSensors[i+1].Result)
continue;
if (ListSensors[i].Result == ListSensors[j].Result)
{
counter++;
if (counter >= nonConsecutiveNum)
{
throw new Exception("NonConsecutive num");
}
}
}
}
}
// consecutiveNum
for (int i = ListSensors.Count - 1; i >= 0; i--)
{
if (sensInfo.Result == ListSensors[i].Result)
{
counter++;
if (counter >= consecutiveNum)
{
throw new Exception("Consecutive num");
}
}
else
{
counter = 1;
}
}
// nonConsecutiveNum
IDictionary<int, int> resultCountDictionary = new Dictionary<int,int>();
foreach (var listSensor in ListSensors)
{
if (resultCountDictionary.ContainsKey(listSensor.Result))
{
resultCountDictionary[listSensor.Result] = resultCountDictionary[listSensor.Result] + 1;
if (resultCountDictionary[listSensor.Result] >= nonConsecutiveNum)
{
throw new Exception();
}
}
else
{
resultCountDictionary.Add(listSensor.Result, 1);
}
}
Consecutive:
Using MoreLinq's Window function:
ListSensors.Window(consecutiveNum).Any(x => x.Distinct().Count() == 1);
Nonconsecutive:
ListSensors.Any(x => ListSensors.Count(s => s == x) >= nonConsecutiveNum);

Why Is This Code Running Longer Character Combinations Than Necessary?

I'm a math student with little to no experience programming, but I wrote this to act like a brute force algorithm. It seems to run fine except that it runs all the password combinations out to 3 characters for passwords as short as 2. Also I'm sure there's a way to refactor the for and if statements as well. Any help would be appreciated, thanks.
I've already been testing to see if some of the if statements aren't executing, and it looks like the statements with "console.writeln(Is this executing)" aren't executing but I'm not really sure.
public Form1()
{
InitializeComponent();
}
static char[] Match ={'0','1','2','3','4','5','6','7','8','9','a','b','c','d','e','f','g','h','i','j' ,'k','l','m','n','o','p',
'q','r','s','t','u','v','w','x','y','z','A','B','C','D','E','F','G','H','I','J','C','L','M','N','O','P',
'Q','R','S','T','U','V','X','Y','Z','!','?',' ','*','-','+'};
private string[] tempPass;
private void button1_Click(object sender, EventArgs e)
{
string tempPass1 = "lm";
string result = String.Empty;
int passLength = 1;
int maxLength = 17;
tempPass = new string[passLength];
for (int i = 0; i < Match.Length; i++)
{
if (tempPass1 != result)
{
tempPass[0] = Match[i].ToString();
result = String.Concat(tempPass);
if (passLength > 1)
{
for (int j = 0; j < Match.Length; j++)
{
if (tempPass1 != result)
{
tempPass[1] = Match[j].ToString();
result = String.Concat(tempPass);
if (passLength > 2)
{
for (int k = 0; k < Match.Length; k++)
{
if (tempPass1 != result)
{
tempPass[2] = Match[k].ToString();
result = String.Concat(tempPass);
if (tempPass[0] == "+" && tempPass[1] == "+" && tempPass[2] == "+" && tempPass1 != result)
{
Console.WriteLine("This will execute?");
passLength++;
tempPass = new string[passLength];
k = 0;
j = 0;
i = 0;
}
else if (result == tempPass1)
{
Console.WriteLine("Broken");
Console.WriteLine("This is big gay: " + result);
break;
}
}
}
}
if (tempPass[0] == "+" && tempPass[1] == "+" && tempPass1 != result)
{
Console.WriteLine("Did this execute?");
passLength++;
tempPass = new string[passLength];
j = 0;
i = 0;
}
else if (result == tempPass1)
{
Console.WriteLine("Broken");
Console.WriteLine("This is bigger gay: " + result);
break;
}
}
}
}
//tempPass[1] = "World!";
//Console.WriteLine(result);
if (tempPass[tempPass.Length - 1] == "+" && tempPass1 != result)
{
passLength++;
tempPass = new string[passLength];
Console.WriteLine(tempPass.Length + " " + result + " " + "Success");
Console.WriteLine(i);
i = 0; /**update
j = 0;
k = 0;
l = 0;
m = 0;*/
}
else if (result == tempPass1)
{
Console.WriteLine("Broken");
Console.WriteLine("This is biggest gay: " + result);
}
}
}
}
Play with this; modified from my answer here. It'll show you all the 2 and 3 length combinations. Clicking the button will start/stop the generation process. You need a button, label, and a timer:
public partial class Form1 : Form
{
private Revision rev;
public Form1()
{
InitializeComponent();
rev = new Revision("0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ!? *-+", "00");
label1.Text = rev.CurrentRevision;
}
private void button1_Click(object sender, EventArgs e)
{
timer1.Enabled = !timer1.Enabled;
}
private void timer1_Tick(object sender, EventArgs e)
{
rev.NextRevision();
if (rev.CurrentRevision.Length == 4)
{
timer1.Stop();
MessageBox.Show("Sequence Complete");
// make it start back at the beginning?
rev = new Revision("0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ!? *-+", "00");
label1.Text = rev.CurrentRevision;
}
else
{
label1.Text = rev.CurrentRevision;
}
}
}
public class Revision
{
private string chars;
private char[] values;
private System.Text.StringBuilder curRevision;
public Revision()
{
this.DefaultRevision();
}
public Revision(string validChars)
{
if (validChars.Length > 0)
{
chars = validChars;
values = validChars.ToCharArray();
curRevision = new System.Text.StringBuilder(values[0]);
}
else
{
this.DefaultRevision();
}
}
public Revision(string validChars, string startingRevision)
: this(validChars)
{
curRevision = new System.Text.StringBuilder(startingRevision.ToUpper());
int i = 0;
for (i = 0; i <= curRevision.Length - 1; i++)
{
if (Array.IndexOf(values, curRevision[i]) == -1)
{
curRevision = new System.Text.StringBuilder(values[0]);
break;
}
}
}
private void DefaultRevision()
{
chars = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
values = chars.ToCharArray();
curRevision = new System.Text.StringBuilder(values[0]);
}
public string ValidChars
{
get { return chars; }
}
public string CurrentRevision
{
get { return curRevision.ToString(); }
}
public string NextRevision(int numRevisions = 1)
{
bool forward = (numRevisions > 0);
numRevisions = Math.Abs(numRevisions);
int i = 0;
for (i = 1; i <= numRevisions; i++)
{
if (forward)
{
this.Increment();
}
else
{
this.Decrement();
}
}
return this.CurrentRevision;
}
private void Increment()
{
char curChar = curRevision[curRevision.Length - 1];
int index = Array.IndexOf(values, curChar);
if (index < (chars.Length - 1))
{
index = index + 1;
curRevision[curRevision.Length - 1] = values[index];
}
else
{
curRevision[curRevision.Length - 1] = values[0];
int i = 0;
int startPosition = curRevision.Length - 2;
for (i = startPosition; i >= 0; i += -1)
{
curChar = curRevision[i];
index = Array.IndexOf(values, curChar);
if (index < (values.Length - 1))
{
index = index + 1;
curRevision[i] = values[index];
return;
}
else
{
curRevision[i] = values[0];
}
}
curRevision.Insert(0, values[0]);
}
}
private void Decrement()
{
char curChar = curRevision[curRevision.Length - 1];
int index = Array.IndexOf(values, curChar);
if (index > 0)
{
index = index - 1;
curRevision[curRevision.Length - 1] = values[index];
}
else
{
curRevision[curRevision.Length - 1] = values[values.Length - 1];
int i = 0;
int startPosition = curRevision.Length - 2;
for (i = startPosition; i >= 0; i += -1)
{
curChar = curRevision[i];
index = Array.IndexOf(values, curChar);
if (index > 0)
{
index = index - 1;
curRevision[i] = values[index];
return;
}
else
{
curRevision[i] = values[values.Length - 1];
}
}
curRevision.Remove(0, 1);
if (curRevision.Length == 0)
{
curRevision.Insert(0, values[0]);
}
}
}
}

Knuth Morris Pratt algorithm implementation

I'm trying to implement KMP algorithm. Part "if (W[i] == S[m + i])" returns index out of range exception and I can't get it to work.
I was following example on Wikipedia: https://en.wikipedia.org/wiki/Knuth%E2%80%93Morris%E2%80%93Pratt_algorithm
static int[] KMPTable(string W)
{
int[] T = new int[W.Length];
int pos = 2;
int cnd = 0;
T[0] = -1;
T[1] = 0;
while (pos < W.Length)
{
if (W[pos - 1] == W[cnd])
{
T[pos] = cnd + 1;
cnd = cnd + 1;
pos = pos + 1;
}
else
if (cnd > 0)
{
cnd = T[cnd];
}
else
{
T[pos] = 0;
pos = pos + 1;
}
}
return T;
}
static int[] KMPSearch(string S, string W)
{
int m = 0;
int i = 0;
int[] kmpNext = KMPTable(S);
List<int> result = new List<int>();
while (m + i < S.Length)
{
if (W[i] == S[m + i])
{
if (i == W.Length - 1)
{
result.Add(m);
}
i = i + 1;
}
else
{
m = m + i - kmpNext[i];
if (kmpNext[i] > -1)
i = kmpNext[i];
else
i = 0;
}
}
return result.ToArray();
}
When m + i < S.Length, then it might be W[i] that is out of its index. Try checking with a step-by-step debug.

Logic behind the Array.Reverse() method

what is the native logic work behind public static void Reverse(Array array, int index, int length);
You can use .NET Reflector for that:
[ReliabilityContract(Consistency.MayCorruptInstance, Cer.MayFail)]
public static void Reverse(Array array, int index, int length)
{
if (array == null)
{
throw new ArgumentNullException("array");
}
if ((index < array.GetLowerBound(0)) || (length < 0))
{
throw new ArgumentOutOfRangeException((index < 0) ? "index" : "length", Environment.GetResourceString("ArgumentOutOfRange_NeedNonNegNum"));
}
if ((array.Length - (index - array.GetLowerBound(0))) < length)
{
throw new ArgumentException(Environment.GetResourceString("Argument_InvalidOffLen"));
}
if (array.Rank != 1)
{
throw new RankException(Environment.GetResourceString("Rank_MultiDimNotSupported"));
}
if (!TrySZReverse(array, index, length))
{
int num = index;
int num2 = (index + length) - 1;
object[] objArray = array as object[];
if (objArray == null)
{
while (num < num2)
{
object obj3 = array.GetValue(num);
array.SetValue(array.GetValue(num2), num);
array.SetValue(obj3, num2);
num++;
num2--;
}
}
else
{
while (num < num2)
{
object obj2 = objArray[num];
objArray[num] = objArray[num2];
objArray[num2] = obj2;
num++;
num2--;
}
}
}
}
TrySZReverse is a native method that can sometimes do the same thing only faster.
Loop from the starting point, index, to the middle of the range, index + length/2, swapping each array[i] with array[index + length - i - 1].
Some details about the native method "TrySZReverse"
from the related codes from coreclr([1][2]), TrySZReverse handles the array of primitive types, and the reverse algorithm is the same as Array.Reverse :
codes quotation
static void Reverse(KIND array[], UINT32 index, UINT32 count) {
LIMITED_METHOD_CONTRACT;
_ASSERTE(array != NULL);
if (count == 0) {
return;
}
UINT32 i = index;
UINT32 j = index + count - 1;
while(i < j) {
KIND temp = array[i];
array[i] = array[j];
array[j] = temp;
i++;
j--;
}
}
and the prefix "SZ" seems stands for "single-dimension zero-terminated".

Categories