Getting Error 'System.IndexOutOfRangeException' - c#

public float[] HitungFitness()
{
float[] fitness = new float[populasi];
for (var individu = 0; individu < populasi; individu++)
{
fitness[individu] = CekConstraint(individu);
}
string[] sort = new string[populasi];
for (int i = 0; i < populasi; i++)
{
sort[i] = string.Format("\nIndividu {0} :Fitness {1}",(i + 1), fitness[i]);
}
bool swapped = true;
while (swapped)
{
swapped = false;
for (int i = 0; i < populasi-1 ; i++)
{
string[] strI = sort[i].Split('.');
float fitI = float.Parse(string.Format("0.{0}", strI[1]));
string[] strJ = sort[i + 1].Split('.');
float fitJ = float.Parse(string.Format("0.{0}", strJ[1]));
if (fitI < fitJ)
{
string sTmp = sort[i];
sort[i] = sort[i + 1];
sort[i + 1] = sTmp;
swapped = true;
}
}
}
return fitness;
}
variable populasi assign = 12
A function CekConstraint is giving a return value between '0.***' to '1'
I have a problem with:
float fitI = float.Parse(string.Format("0.{0}", strI[1]));
or
float fitJ = float.Parse(string.Format("0.{0}", strI[1]));
When the strI or strJ just giving one value of array like strJ[1] or stri[1] then I'm getting the Index was outside bounds of the array. I recognize the error but how do I fix this?
Please help me.

string[] strI = sort[i].Split('.');
float fitI = float.Parse(string.Format("0.{0}", strI[1]));
sort[i] string doesn't have . in it. Because of that when you call Split('.') you produce only array with 1 item. Because of that on strI[1] you receive and exception, there is no second elements in strI array.

Error is because it is not getting value in strI[1] or strJ[1]. It may have happened because of a "." is not found in sort[i]. Hence we can see put a condition based on strI and strJ array Length.
Change your inner for loop as
for (int i = 0; i < populasi-1 ; i++)
{
float fitI = 0.0;
float fitJ = 0.0;
string[] strI = sort[i].Split('.');
if(strI.Length > 1)
fitI = float.Parse(string.Format("0.{0}", strI[1]));
string[] strJ = sort[i + 1].Split('.');
if(strJ.Length > 1)
fitJ = float.Parse(string.Format("0.{0}", strJ[1]));
if (fitI < fitJ)
{
string sTmp = sort[i];
sort[i] = sort[i + 1];
sort[i + 1] = sTmp;
swapped = true;
}
}

Why so many loops, use a list or dictinary in place or array and use foreach loop to avoid the out-of-range exception.
float[] fitness = new float[populasi];
//create a list for this
string[] sort = new string[populasi];
//another list
and do foreach looping

Related

Creating Dynamic String and Array references in for loop

I need to create dynamic references to both strings and string Arrays within a for loop.
Is the following correct? In particular where I am trying to create a dynamic string reference string sRef = "svert"+num; and later a dynamic Array reference string arrayRef = "s_array"+num;
Any feedback welcome.
Vector3[] meshVerts = foo;
for(int num=0; num < meshVerts.Length;num++){
string sRef = "svert"+num;
sRef =meshVerts[num].ToString( format: "F4");
sRef= sRef.Substring(1, 3);
string arrayRef = "s_array"+num;
string[] arrayRef = sRef.Split(',');
}
'''
I have prepared a sample and test code for your question. I hope you find it interesting.
//fill vector3 array
Vector3[] meshVerts = new Vector3[3];
for (int i = 0; i < meshVerts.Length; i++)
{
meshVerts[i] = new Vector3(i, i + 1, i + 2);
}
//fill string array
string[] arrayRef = new string[meshVerts.Length];
for (int num = 0; num < meshVerts.Length; num++)
{
arrayRef[num] = string.Format("s_array{0}: {1}", num, meshVerts[num]);
}
//show vector3 array and string array
for (int i = 0; i < meshVerts.Length; i++)
{
Console.WriteLine(string.Format("Vector3 Array Row{0}: X={1} ,Y={2} ,Z={3}", i, meshVerts[i].X, meshVerts[i].Y, meshVerts[i].Z));
string[] newArray = arrayRef[i].Split(',');
string firstCell = newArray[0].Split(':')[1].Replace("<", "");
Console.WriteLine(string.Format("{0} Row{1}: X={2} ,Y={3} ,Z={4}", newArray[0].Split(':')[0], i, firstCell, newArray[1], newArray[2].Replace(">", "")));
}

Substring causing index and length error

I have a section in my code that I run to check to see if the item is an spanish item or english item. I am using this logic from an old vb.net application.
public int Spanish_Item()
{
int i = 0;
object j = 0;
int k = 0;
string ss = null;
string sp_item = null;
sp_item = TxtItem.Text.Trim();
k = 0;
for (i = 1; i <= 15; i++)
{
ss = sp_item.Substring(i, 2);
if (ss == "XX")
{
k = 1;
i = 16;
}
}
return k;
}
The following code loops around
then I get this error message :
ex.Message "Index and length must refer to a location within the
string.\r\nParameter name: length" string
please help!!!
You always go from 1 to 15 - if the (trimmed) text of TxtItem.Text is shorter then 15 chars you'll get the exception.
You should use the length-2 of sp_item as upper bound to avoid the error.
Also, instead of setting i = 16 you should use break to stop the for loop.
However, I think your algorithm could also be written like this instead of the for loop:
if (sp_item.IndexOf("XX")>=1) {
k=1;
}
In c# the first position is at index 0 not 1 like vb
public int Spanish_Item()
{
int i = 0;
object j = 0;
int k = 0;
string ss = null;
string sp_item = null;
sp_item = TxtItem.Text.Trim();
k = 0;
for (i = 0; i < sp_item.len-2; i++)
{
ss = sp_item.Substring(i, 2);
if (ss == "XX")
{
k = 1;
i = 15;
}
}
return k;
}
you can use
if (sp_item.IndexOf("XX")>=0) {
k=1;
}

Cosine similarity calculation issue

I am having issues in calculation of cosine similarity between 2 strings.
I calculate the binary vector format of each string using a function. It gives out binary vectors which are in the form of, say, (1,1,1,1,1,0,0,0,0).
public static Tuple<int[],int[]> sentence_to_vector(String[] word_array1, String[] word_array2)
{
String[] unique_word_array1 = word_array1.Distinct().ToArray();
String[] unique_word_array2 = word_array2.Distinct().ToArray();
String[] list_all_words = unique_word_array1.Concat(unique_word_array2).ToArray();
String[] list_all_words_unique = list_all_words.Distinct().ToArray();
int count_all_unique_words = list_all_words_unique.Length;
int[] sentence1_vector = new int[count_all_unique_words];
int[] sentence2_vector = new int[count_all_unique_words];
for (int i = 0; i < count_all_unique_words; i++)
{
if (Array.IndexOf(unique_word_array1, list_all_words_unique[i]) >= 0)
{
sentence1_vector[i] = 1;
}
else
{
sentence1_vector[i] = 0;
}
}
for (int i = 0; i < count_all_unique_words; i++)
{
if (Array.IndexOf(word_array2, list_all_words_unique[i]) >= 0)
{
sentence2_vector[i] = 1;
}
else
{
sentence2_vector[i] = 0;
}
}
return Tuple.Create(sentence1_vector, sentence2_vector);;
}
After I calculate the vector representation, I go for cosine similarity calculation.
The code is attached herewith:
public static float get_cosine_similarity(int[] sentence1_vector, int[] sentence2_vector)
{
int vector_length = sentence1_vector.Length;
int i = 0;
float numerator = 0, denominator = 0;
int temp1 = 0, temp2 = 0;
double square_root1 = 0, square_root2 = 0;
for (i = 0; i < vector_length; i++)
{
numerator += sentence1_vector[i] * sentence2_vector[i];
temp1 += sentence1_vector[i] * sentence1_vector[i];
temp2 += sentence2_vector[i] * sentence2_vector[i];
}
//TextWriter tw = new StreamWriter("E://testpdf/date2.txt");
square_root1 = Math.Sqrt(temp1);
square_root2 = Math.Sqrt(temp2);
denominator = (float)(square_root1 * square_root2);
if (denominator != 0){
return (float)(numerator / denominator);
//return (float)(numerator);
}
else{
return 0;
}
}
I checked out a site where in I can specify 2 strings and find the cosine similarity between them. The site is attached herewith:
http://cs.uef.fi/~zhao/Link/Similarity_strings.html
function implementationCosin(){
var string1 = document.DPAform.str1.value;
var s1 = stringBlankCheck(string1);
var string2 = document.DPAform.str2.value;
var s2 = stringBlankCheck(string2);
if (s1.length < 1) {
alert("Please input the string1.");
return;
}
if (s2.length < 1) {
alert("Please input the string2.");
return;
}
document.DPAform.displayArea2.value = "";
var sDT = new Date();
// var begin = new Date().getTime();
var cosin_similarity_value = consinSimilarity(s1, s2);
document.DPAform.displayArea2.value += 'Cosin_Similarity(' + s1 + ',' + s2 + ')=' + cosin_similarity_value + '%\n';
var eDT = new Date();
var timediff = sDT.dateDiff("ms", eDT);
// var timediff = (new Date().getTime() - begin);
document.DPAform.displayArea2.value += "The total escaped time is: " + timediff + " (ms).\n";
}
Even if 2 sentences are 0% similar, my codes says that there is some amount of similarity between them.

Converting double to int array

I'm trying to XOR each letter from my TextBox with each value from my array.
The problem is, that when I convert double to int array, my int array result stores only one value.
If I run my code I get first letter XORed, but if I input more then one, I get message :
System.IndexOutOfRangeException: Index was outside the bounds of the array.
I have tried myself to create an int array like: int[] result = new int[] {1,2,3,4,5,6,7}; and I didn't have any problems with XORing up to 7 letters..
private void iTalk_Button_12_Click(object sender, EventArgs e)
{
ambiance_RichTextBox1.Text = XorText(ambiance_RichTextBox1.Text);
}
private string XorText(string text)
{
string newText = "";
double r = 3.9;
double[] first_value = new double[text.Length];
double[] to_int_array = new double[text.Length];
for (int i = 0; i < text.Length; i++)
{
double get_first = r * i * (1 - i);
int index = (int)(i * text.Length);
first_value[index] = get_first;
}
for (int i = 0; i < text.Length; i++)
{
int xnbb = 0;
if (first_value[i] > Math.Exp(Math.Log(2) * (-i)))
{
double get_first = first_value[i] - Math.Exp(Math.Log(2) * (-i));
xnbb = 1;
}
double array_of_values = xnbb + 1 * Math.Round(Math.Exp(Math.Log(2) * (24 - i)));
int index = (int)(i * text.Length);
to_int_array[index] = array_of_values;
int[] result = new int[] { Convert.ToInt32(to_int_array[i]) };
int charValue = Convert.ToInt32(text[i]);
charValue ^= result[i]%320;
newText += char.ConvertFromUtf32(charValue);
}
return newText;
}
double[] first_value = new double[text.Length];
...
for (int i = 0; i < text.Length; i++)
{
double get_first = r * i * (1 - i);
int index = (int)(i * text.Length);
first_value[index] = get_first;
}
When the text length is 2, first_value index may run from 0..1. i will loop from 0 to 1. the calculated index becomes 1 x 2 = 2, and that is beyond the index range.
When passing a string with 2 characters to XorText, the System.IndexOutOfRangeException is thrown in this Line:
first_value[index] = get_first;
because the index is 2 when the loop body is executed the second time:
int index = (int)(i * text.Length);
You really should consider learning how to use a debugger. It will make programming easier.

adding initialized array(index 5 onwards is null) to chart control using for loop

I've initialized a 2 dimensional array and starting from index 5 onwards contain null value. I'm trying to add the array values to my Chart Control. When I try displaying the values to Console.WriteLine, there's no exception occurred however when I add to my chart series, the exception is "Index was outside the bounds of the array." Anyone can help me? is it because chart control has limited bars?
try
{
//females age range
string[,] gAge = new string[10, 2];
gAge[0, 0] = "F.13-17";
gAge[0, 1] = yf.f1317.ToString();
gAge[1, 0] = "F.18-24";
gAge[1, 1] = yf.f1824.ToString();
gAge[2, 0] = "M.25-34";
gAge[2, 1] = yf.m2534.ToString();
gAge[3, 0] = "M.13-17";
gAge[3, 1] = yf.m1317.ToString();
gAge[4, 0] = "M.18-24";
gAge[4, 1] = yf.m1824.ToString();
for (int i = 0; i < gAge.Length; i++)
{
if (gAge[i, 0] == null)
{
break;
}
else
{
Console.WriteLine(gAge[i, 0].ToString());
string[] seriesArray = { gAge[i, 0].ToString() };
Series series = this.chart1.Series.Add(seriesArray[i]);
}
}
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
}
The problem is that you are getting the length of your entire array, in this casegAge.Length is equal to 20 which is the total number of indices in your Array. It is exceeding the bounds of your first array dimension. Try using gAge.GetLength(0) instead.
try
{
chart1.Series.Clear();
chart1.Titles.Clear();
chart1.Visible = true;
//CODES HERE TO GET THE SELECTED PAGE FROM DROP DOWN LIST
var fb = new FacebookClient(myToken.Default.token);
var query = string.Format("SELECT metric, value FROM insights WHERE object_id=132414626916208 AND metric='page_fans_gender_age' AND period = period('lifetime') AND end_time = end_time_date('2013-01-18')");
dynamic parameters = new ExpandoObject();
parameters.q = query;
var data = fb.Get<genderAgeDataII>("fql", parameters);
genderAge yf = (genderAge)data.data[0].value;
//females age range
string[,] gAge = new string[10, 2];
gAge[0, 0] = "F.13-17";
gAge[0, 1] = yf.f1317.ToString();
gAge[1, 0] = "F.18-24";
gAge[1, 1] = yf.f1824.ToString();
gAge[2, 0] = "M.25-34";
gAge[2, 1] = yf.m2534.ToString();
gAge[3, 0] = "M.13-17";
gAge[3, 1] = yf.m1317.ToString();
gAge[4, 0] = "M.18-24";
gAge[4, 1] = yf.m1824.ToString();
for (int i = 0; i < gAge.GetLength(0); i++)
{
if (gAge[i, 0] == null)
{
break;
}
else
{
string[] seriesArray = { gAge[i,0] };
// Add series.
for (int w = 0; w < seriesArray.Length; w++)
{
// Add series.
Series series = this.chart1.Series.Add(seriesArray[w]);
int[] pointsArray = new int[seriesArray.Length];
pointsArray[w] = Convert.ToInt32(gAge[i, 1]);
series.Points.Add(pointsArray[w]);
}
Console.WriteLine(gAge[i, 0].ToString());
}
}

Categories

Resources