Rearrange numbers content within a listbox - c#

i trying to shuffle the numbers currently contained within a listbox.
However getting an error with my index
I am able to do this with an array, although now I am trying to shuffle without the use of any containers or arrays, but having problems doing so.
this.index = 0;
int a = Convert.ToInt32(lstHoldValue.Items.Count);
lstHoldValue.Items.Clear();
for (int i = 0; i < a; i++)
{
int idx = rnd.Next(i, a);
//swap elements
int tmp = Convert.ToInt32(lstHoldValue.Items[i]);
(lstHoldValue.Items[i]) = Convert.ToInt32(lstHoldValue.Items[idx]);
(lstHoldValue.Items[idx]) = Convert.ToInt32(tmp);
lstHoldValue.Items.Add("\t" + Convert.ToInt32(lstHoldValue.Items[i]));//show array in a listbox
}

this.index = 0;//what is this for?
int a = listHoldValue.Count;//Count returns an integer by default
// lstHoldValue.Items.Clear(); //remove this line,it clears the items stored
for (int i = 0; i < a; i++)
{
int idx = rnd.Next(i, a);
//swap elements
int tmp = Convert.ToInt32(lstHoldValue.Items[i]);
lstHoldVAlue.Items.Insert(i,lstHoldValue.Items[idx]);
(lstHoldValue.Items[i]) = Convert.ToInt32(lstHoldValue.Items[idx]);
(lstHoldValue.Items.Insert(idx,temp);
lstHoldValue.Items.Add("\t" + Convert.ToInt32(lstHoldValue.Items[i]));//this line is redundant because you have already added item[i] at index [idx]
}

Related

How can i write which element corresponds to which score in 2 different arrays?

I have got 25 elements in my txt file. My code calculates their scores according to answer key. Then i would like to sort them without using sort.Array etc. I made it and a assigned them another array which is name is result. Now i would like to write the elements number according to order of result array
. For example the element 101' score 78. The element 105' s score is 25.
The result array sort them: 78-25
i would like to sort them : 101-105
my code is:
//arranging results according to their values
int temp = 0;
int[] elm = new int[result.Length];
for (int i = 0; i <= result.Length-1 ; i++)
{
for (int j = i+1 ; j < result.Length; j++)
{
if (result[i] < result[j])
{
temp = result[i];
result[i] = result[j];
result[j] = temp;
}
elm[j] = Convert.ToInt16(row[i,0]);
}
;
}

Trying to find Frequency of elements in array

I am trying to count how many times a number appears in an array 1 (a1) and then trying to print out that number by storing it in array 2 (a2) just once and then try to print array 2. But first using for loop and a function, I will check that if a number already exist in array 2 then move to next index in array 1, unfortunateley this code is not working; can someone please help me in trying to fix it, I don't need some complex solutions like dictionaries or lists athe moment, although it might be helpful too. thanks, I am not an expert in programming and I try to practise it in my free time, so please help me.
I just want this code to be fixed for my understanding and knowledge
class Program
{
static void Main(string[] args)
{
int i, j;
int[] a1 = new int[10];
int[] a2 = new int[10];
int[] a3 = new int[10];
//takes an input
for (i = 0; i < a1.Length; i++)
{
a1[i] = Convert.ToInt32(Console.ReadLine());
}
for (i = 0; i < a1.Length; i++)
{
Cn(a1, a2); //calls in function
i++; //increments is if true
int count = 0;
for (j = 0; j < a1.Length; j++)
{
//if a number matches with a number in second array
if (a1[i] == a1[j])
{
//do count ++
count++;
// store that number into second array
a2[i] = a1[i];
}
}
//store the number of counts in third array
a3[i] = count;
}
for (i = 0; i < a2.Length; i++)
{
if (a2[i] != 0)
{
Console.WriteLine(a2[i]);
}
}
Console.ReadLine();
}
//function to check if element at current index of array 1 exists in array 2 if yes than break
public static void Cn (int[] aa1, int [] aa2)
{
int k, j;
for ( k = 0; k < aa1.Length; k++)
{
for (j = 0; j < aa2.Length; j++)
{
if (aa1[k] == aa2[j])
break;
}
}
}
}
You probably want to do a group by count:
int[] a1 = new int[10];
var rnd = new Random();
//takes an input
for (int i = 0; i < a1.Length; i++)
{
a1[i] = Convert.ToInt32(rnd.Next(0, 11)); // or Console.ReadLine()
}
var grouped = a1
.GroupBy(x => x)
.Select(g => new
{
Item = g.Key,
Count = g.Count()
}).ToList(); // ToList() is optional, materializes the IEnumerable
foreach (var item in grouped)
{
Console.WriteLine($"number: {item.Item}, count: {item.Count}");
}
This uses a Hash algorithm internally.
You can solve this without a Hash or Dictionary but it wouldn't be very efficient because you need to do lots of linear searches through the arrays.
The advantage of a Hash algorithm is that your lookups or groupings are much faster than if you loop over a complete array to find / increment an item.

How do i select an array range where array index is greater than a certain value C#

I am trying to select 15 events with each iteration of i.
In the first loop of i, I want to add validbatch[0 to 15].
Next loop validbatch[15 to 30] and so on.
How do I filter or select a subarray from valid batch where the index > i*15?
for (j = counter; j < i * 15; j++)
{
crm x = new crm();
x.EmailAddress = EMAILaddress[j];
Properties prop = new Properties();
prop.new_insideroptout = optin[j];
validBatch[j] = new SampleEventBody() { Id = Int64.Parse(ID[j]), Publication = subscriptionname[j], CrmProperties = x, Properties = prop };
counter++;
}
sendTasks.Add(client.SendEventBatchAsync(validBatch.Where<EventBody>(validbatch => validBatch[j] > validbatch[i * 15 - 1])
You could use the following generic method to split an array.
public static IEnumerable<IEnumerable<T>> SplitArray<T>(this T[] array, int size)
{
for (var i = 0; i < (float)array.Length / size; i++)
{
yield return array.Skip(i * size).Take(size);
}
}
And then you can call it like
var splitedArray = array.SplitArray(2);
I hope you are looking for this.

How do you retrieve inputted text from a textbox array?

I am creating a calculator where the user enters a number into a textbox specifing how many inputs (textboxes) the user wants to have (Code not shown). I have used a textbox array to create these textboxes. The problem comes when I want to get the text from these textboxes to perform the calculations, the code I have written so far for this is shown below:
int n;
TextBox[] textBoxes;
Label[] labels;
double[] values;
public void GetValue()
{
n = Convert.ToInt16(txtInputFields.Text);
values = new double[n];
textBoxes = new TextBox[n];
for (int i = 0; i < n; i++)
{
}
}
I am unsure what to put in the for loop for this; I have tried the following:
values[n] = Convert.toDouble(textBoxes[n].Text);
but it gives me the error: Index was outside the bounds of the array.
I am new to C# and programming in general so any help would be much appreciated.
Thanks.
EDIT: Code to create textboxes is shown here:
public void InstantiateTextFields()
{
n = Convert.ToInt16(txtInputFields.Text);
int posLeft = 100;
textBoxes = new TextBox[n];
labels = new Label[n];
// Creates number of inputs and labels as specified in txtInputFields (n).
for (int i = 0; i < n; i++)
{
textBoxes[i] = new TextBox();
textBoxes[i].Top = 100 + (i * 30);
textBoxes[i].Left = posLeft;
textBoxes[i].Name = "txtInput" + (i + 1);
labels[i] = new Label();
labels[i].Top = 100 + (i * 30);
labels[i].Left = posLeft - 50;
labels[i].Text = "Input " + (i + 1);
labels[i].Name = "lblInput" + (i + 1);
}
for (int i = 0; i < n; i++)
{
this.Controls.Add(textBoxes[i]);
this.Controls.Add(labels[i]);
}
}
Your code in the GetValue method recreates the array of textboxes and doing so destroys the orginal content (the textboxes dynamically created InstantiateTextFields).
In this way your loop fails with Object Reference not set.
You just need to use the global variable without reinitiaizing it
public void GetValue()
{
n = Convert.ToInt16(txtInputFields.Text);
values = new double[n];
// textBoxes = new TextBox[n];
for (int i = 0; i < n; i++)
{
values[i] = Convert.ToDouble(textBoxes[i].Text);
}
}
There is something to be said about reading the input text and converting it to double without checks. If your user types something that cannot be converted to a double your code will crash on the Convert.ToDouble line. Use instead
double temp;
for (int i = 0; i < n; i++)
{
if(double.TryParse(textBoxes[i].Text, out temp)
values[i] = temp;
else
{
// Not a double value....
// A message to your user ?
// fill the array with 0 ?
// Your choice....
}
}
values[n] = Convert.toDouble(textBoxes[n].Text); gives you error because n is outside of the array. You allocate an array with the size of n which is zero indexed aka the last element is at position n-1.
for (int i = 0; i < n; i++)
{
values[i] = Convert.toDouble(textBoxes[i].Text);
}

Initializing two dimensional array of objects

I have a 2-dimensional array of objects, which I initialize using the traditional loop:
PairDS[,] tempPb1 = new PairDS[LoopCounterMaxValue+1, LoopCounterMaxValue+1];
for (int i = 0; i <= LoopCounterMaxValue; i++)
for (int j = 0; j <= LoopCounterMaxValue; j++)
tempPb1[i, j] = new PairDS();
Is there any better way to do this using Enumerable or something?
I thought Initialize could do it, but it only works with value types.
int N = 10;
PairDS[,] temp = new PairDS[N + 1, N + 1];
temp.Initialize();
What I recommend you do is use a jagged array.
class PairDS { public PairDS(int row, int col) { } }
static void Main(string[] args)
{
int N = 10;
PairDS[][] temp = Enumerable.Range(0, N + 1).Select(
(row) => Enumerable.Range(0, N + 1).Select(
(col) => new PairDS(row, col)).ToArray()).ToArray();
}
I don't believe you can represent a multi-dimensional array as an Enumerable or List, directly because it (the CLR) has no way of knowing how you intend to index the array.
If you did work it out row by row, it'd actually be worse (ie slower) then simply looping through the array as you're doing and initializing each cell.
There's no way to directly initialize a 2D array with the Enumerable types and as some users have pointed out there's nothing directly wrong with what you're doing. If you're just looking to simplify the loop though this might be what you're looking for;
const int length = LoopCounterMaxValue + 1;
PairDS[,] tempPb1 = new PairDS[length, lenth];
for (var i = 0; i < length * length; i++) {
var column = i % length;
var row = (i - column) / length;
tempPb1[row, column] = new PairDS();
}

Categories

Resources