Is there a way to square the items on a listbox then the output would go to the other listbox
for example I added an item on the listbox using loop
int items;
items=2;
do
{
listbox1.items.add(items);
items=items+2;
} while(items<20);
If you want to add 4, 16, 36, ... 324 items, you can achieve it with the code:
for (int i = 2; i < 20; i += 2)
listbox1.Items.Add(i * i);
Based on the image you posted in a comment to Abdelhamid's answer it looks like you are trying to populate the items in the second list box as the squared version of their counterparts in the first list
foreach(var item in listBox1.Items)
{
//Since you don't specify their type I presume they need parsing..
int num;
int.TryParse(item.ToString(), out num);
listBox2.Items.Add(num * num);
}
If you were trying to do it at the same time as populating the first..
int items = 2;
do
{
listbox1.Items.Add(items);
listbox2.Items.Add(items * items);
items += 2;
} while(items<20);
How about
int items =2;
int items_sq;
do
{
listBox1.Items.Add(items);
items_sq=Math.Pow(items,2); //squares the items variable
listBox2.Items.Add(items_sq);
items += 2;
} while(items<20);
Use the ListBox for display and for user interaction only and do the logic operations independently from the listbox.
// Initialize
List<int> input = new List<int>();
for (int i = 2; i < 20; i += 2) {
input.Add(i);
}
// Calculate
List<int> result = new List<int>();
for (int i = 0; i < input.Count; i++) {
int value = input[i];
result.Add(value * value);
}
// Display
listbox1.Items.AddRange(input);
listbox2.Items.AddRange(result);
The GUI (Graphical User Interface) logic should always be kept separate from the so called Business Logic (in this case the calculation of squares). The List<int>s represent the data in the business logic (they are called the Model). They are typed and need no casting or transformation and do not depend on some controls. If you want to convert your example into a web page, the business logic part will remain exactly the same, where as the display part will be completely different.
int items;
items=2;
do
{
listbox1.items.add(items);
items = Math.Pow(items, 2)
} while(items<20);
Try this...
int items;
items=2;
do
{
listbox1.items.add(items);
listbox2.items.add(items*items);
items=items+2;
} while(items<20);
Related
I have a textbox to write the position of an array and a textbox to write the value of that position. Every time I want to add a value and a position I click the button btnStoreValue
I created a function (CompareTwoNumbers) for another exercise that compares two numbers and returns the biggest
Using that function and avoiding the use of comparison characters like > and < I'm supposed to get the biggest value of the array
public partial class Form1 : ExerciseArray
{
int[] numbers = new int[10];
private int CompareTwoNumbers(int i, int j)
{
if (i < j)
{
return j;
}
return i;
}
private void btnBiggestValue_Click(object sender, EventArgs e)
{
//int n=1;
int counter = 0;
int highestPosition = CompareTwoNumbers(0, 1);
for(int i=0; i<10; i++){
//int j = CompareTwoNumbers(numbers[i], numbers[i+1])
//n = CompareTwoNumbers(numbers[n], numbers[i+1]
counter = CompareTwoNumbers(highestPosition, i);
}
txtBiggestValuePosition.Text= n.ToString();
txtBiggestValue.Text=numbers[n].ToString();
}
I've tried multiple things, using multiple variables, I tried to write it on paper to try to understand things better and I'm stuck. I don't know how is it possible to find that value using the function I created on the previous exercise (assuming the function I created is correct)
So, the core part of your question is that you want to know how to find the biggest number in an array using your helper function CompareTwoNumbers and then figure out what the value and position of the biggest number is.
Based on my understanding above, you have the framework almost set up correctly.
First off, CompareTwoNumbers should be updated to return a bool. Doing this will let you conditionally update your variables holding the biggest number value and position.
private int CompareTwoNumbers(int i, int j)
{
if (i < j)
{
return true;
}
return false;
}
To know what the largest value in an (unsorted) array is, you will need to iterate through every value. While doing so, you need to keep track of the value and position of the biggest value, only updating it when a bigger value is found.
private void btnBiggestValue_Click(object sender, EventArgs e)
{
// Store the bigget number's index and value
// We start with the first index and corresponding
// value to give us a starting point.
int biggestNumberIndex = 0;
int biggestNumber = numbers[0];
// Iterate through the array of numbers to find
// the biggest number and its index
for(int i=0; i<10; i++)
{
// If the current number is larger than the
// currently stored biggest number...
if(CompareTwoNumbers(biggestNumber, numbers[i])
{
// ...then update the value and index with
// the new biggest number.
biggestNumber = number[i];
biggestNumberIndex = i;
}
}
// Finally, update the text fields with
// the correct biggest value and biggest
// value position.
txtBiggestValuePosition.Text= biggestNumberIndex.ToString();
txtBiggestValue.Text=numbers[biggestNumberIndex].ToString();
}
This uses a Tuple to give you both the max index and max value from the same method:
public (int, int) FindMaxValue(int[] items)
{
int maxValue = items[0];
int maxIndex = 0;
for(int i=1;i<items.Length;i++)
{
if (items[i] > maxValue)
{
maxValue = items[i];
maxIndex = i;
}
}
return (maxIndex, maxValue);
}
So I am trying to figure out why filling sudoku board in order of how I generate fields is many times faster then filling it which shuffled order, and I can't come to any reasonable conclusions.
Speed of filling and checking should be about the same no matter if fields are shuffled or not, only noticeable difference is the fact that filling boxes in a shuffled order causes the main loop to easily go for 60.000.000+ iterations not sure how many on average as I am not patient enough to check. And filling them in order of how they were generated gets finished in usually < 1.000 iterations rarely going over it and basically never going over 5.000.
I do understand that code doesn't follow C# standards too strictly but it's a project I am supposed to make and it's not my main language there are probably some possible optimizations but it's not what I am interested in all i want to know why shuffling the order of fill the boxes causes the process to take this much longer.
Edit: forgot to attach order of creating/filling boxes order of filling/creating boxes:
Edit2: more concise rephrased question:
The question is why generating an valid fully filled sudoku board in order from image creates a lot less invalid boards from which there is required backtracking, as compared to generating a board in a random order of choosing fields?
example of random order
Here is the code used for the project https://github.com/Piterm21/sudoku
And here are all the parts used in generation.
filledBox class:
public class filledBox
{
public int textBoxIndex;
public int value;
public int nextIndexToTry;
public int[] values;
public int lineIndex;
public int columnIndex;
public int groupIndex;
}
Here is a main loop:
filledBox[] boxes = this.shuffleBoxesCreateCheckingLists();
long iter = 0;
int nextIndexToFill = 0;
while (nextIndexToFill != 81) {
for (; boxes[nextIndexToFill].nextIndexToTry < 9; boxes[nextIndexToFill].nextIndexToTry++) {
// check if is valid
if (!createsError(boxes[nextIndexToFill])) {
boxes[nextIndexToFill].value = boxes[nextIndexToFill].values[boxes[nextIndexToFill].nextIndexToTry];
nextIndexToFill++;
break;
}
if (boxes[nextIndexToFill].nextIndexToTry == 8) {
boxes[nextIndexToFill].nextIndexToTry = 0;
boxes[nextIndexToFill].value = 0;
nextIndexToFill--;
boxes[nextIndexToFill].nextIndexToTry++;
while (boxes[nextIndexToFill].nextIndexToTry == 9) {
boxes[nextIndexToFill].nextIndexToTry = 0;
boxes[nextIndexToFill].value = 0;
nextIndexToFill--;
boxes[nextIndexToFill].nextIndexToTry++;
}
break;
}
}
iter++;
}
System.Diagnostics.Debug.WriteLine(iter);
Generation of boxes with setting of lists used for checking for errors:
List<filledBox>[] generationLines;
List<filledBox>[] generationColumns;
List<filledBox>[] generationGroups;
public filledBox[] shuffleBoxesCreateCheckingLists()
{
filledBox[] boxes = new filledBox[81];
for (int i = 0; i < 81; i++) {
boxes[i] = new filledBox();
boxes[i].values = new int[9]{ 1, 2, 3, 4, 5, 6, 7, 8, 9 };
boxes[i].values = shuffle(boxes[i].values, true);
}
generationLines = new List<filledBox>[9];
generationColumns = new List<filledBox>[9];
generationGroups = new List<filledBox>[9];
for (int i = 0; i < 9; i++) {
generationLines[i] = new List<filledBox>();
generationColumns[i] = new List<filledBox>();
generationGroups[i] = new List<filledBox>();
}
int boxIndex = 0;
for (int y = 0; y < 3; y++) {
for (int x = 0; x < 3; x++) {
for (int innerY = 0; innerY < 3; innerY++) {
for (int innerX = 0; innerX < 3; innerX++) {
int subPanelIndex = x + y * 3;
int lineIndex = innerY + y * 3;
int columnIndex = innerX + x * 3;
boxes[boxIndex].textBoxIndex = boxIndex;
boxes[boxIndex].groupIndex = subPanelIndex;
boxes[boxIndex].columnIndex = columnIndex;
boxes[boxIndex].lineIndex = lineIndex;
boxes[boxIndex].nextIndexToTry = 0;
boxes[boxIndex].value = 0;
generationLines[lineIndex].Add(boxes[boxIndex]);
generationColumns[columnIndex].Add(boxes[boxIndex]);
generationGroups[subPanelIndex].Add(boxes[boxIndex]);
boxIndex++;
}
}
}
}
#if !fast
boxes = shuffle(boxes);
#endif
return boxes;
}
Shuffling code:
public T[] shuffle<T> (T[] array)
{
int i = array.Length;
while (i > 1) {
i--;
int j = rnd.Next(0, i - 1);
T temp = array[i];
array[i] = array[j];
array[j] = temp;
}
return array;
}
And code responsible for checking for errors:
public bool hasError (List<filledBox> list, filledBox box)
{
bool result = false;
foreach (filledBox filledBoxToCheck in list) {
if (filledBoxToCheck.value == box.values[box.nextIndexToTry]) {
if (box.lineIndex != filledBoxToCheck.lineIndex ||
box.columnIndex != filledBoxToCheck.columnIndex) {
result = true;
break;
}
}
}
return result;
}
public bool createsError (filledBox box)
{
bool result = false;
if (hasError(generationGroups[box.groupIndex], box)) {
result = true;
} else if (hasError(generationLines[box.lineIndex], box)) {
result = true;
} else if (hasError(generationColumns[box.columnIndex], box)) {
result = true;
}
return result;
}
The reason the shuffled order of visiting boxes is worse is that, for the first few boxes, you've increased the odds of filling them in independently. I'm calling a 3x3 region a box. You could visit each little square randomly, but I'll confine my analysis to fillng in one 3x3 box at a time. It should illustrate the problem.
Lets assume, whether you used the in-order or random method, you filled in the top left box first.
VISITING BOXES IN ORDER:
Now consider filling in the box next to it, that is, the top middle box. Just look at filling in the top row of that box, there are 6x5x4 = 120 ways to fill it in.
VISITING BOXES RANDOMLY:
Now consider instead choosing any box to fill in next. If you happen to choose a box that is not in the top row or left column, filling it in is unaffected by the way the first box was filled. The top row of that box can be filled in 9x8x7 = 504 ways.
Taking this further, if you fill in the boxes sequentially, say, across the top, the third box (the top right one), begins with only 3x2x1 = 6 ways to fill in the top row of it. Whereas, if you select the next box randomly, you might, at worst, select a box that is not in the same row or column of either of the first 2 boxes, which means that the top row of that box has yet again 9x8x7 = 504 ways of being filled in.
If you tried randomly selecting the order for each little square to be filled in, the first few might all be in different rows and columns. At worst, none of the first 9 squares will align meaning there will be 9^9 = 387,420,489 options. But filling them in across the top row, the choices are guaranteed to be 9! = 362,880.
This illustrates one of the strategies for how to approach backtracking. Ideally, you first solve parts of the problem that most tightly constrain the rest of the problem. For some problems sequential is better, and for some random is better.
I have a 16 element int array and 16 textboxes (textBox1, textBox2 ....) that look like 4x4 matrix. Is there any way to put textboxes values to every array element not using code like this:
array[1] = (int)textBox1.Text;
array[2] = (int)textBox2.Text;
One possibility would be to store the references to the TextBox instances in an array.
TextBox[] Boxes;
And then use a 'for' loop to populate the values.
for (int i = 0; i < 16; i++)
{
array[i] = (int)Boxes[i].Text;
}
You could use a function to get the text box's text as an integer using it's "index" from the form's control collection:
int GetBoxText(int index)
{
return Convert.ToInt32(this.Controls["textBox" + i.ToString()].Text);
}
Note that this has no error checking of any kind. You could add some if you wanted to. All this does is get the text of the control named textBox + whatever i is from the form's control collection and convert it to an integer.
IMHO the best way to design is by the way it's meant to be. In particular, rectangular/multidimensional arrays may be useful in this scenario:
public partial class Form1 : Form {
TextBox[,] textBoxes;
int[,] values;
public Form1() {
InitializeComponent();
textBoxes = new TextBox[4, 4];
values = new int[textBoxes.GetLength(0), textBoxes.GetLength(1)];
for(int r = 0; r < textBoxes.GetLength(0); r++) {
for(int c = 0; c < textBoxes.GetLength(1); c++) {
values[r, c] = int.Parse(textBoxes[r, c].Text);
}
}
}
}
I want to save the result of zarb function which repeats for 1000 times in a list with size 1000. Then I must to increase the index of the list for every calculation to avoid to save the next calculation at the same index of previous one. How can I do that?
var results = new List<float>(1000);
for (int z = 0; z < 1000; z++)
{
results.Add(zarb(sc,z));
//increase the index of resukts
}
foreach (var resultwithindex in results.Select((r, index) => new { result = r, Index = index }).OrderByDescending(r => r.result).Take(20))
{
MessageBox.Show(string.Format("{0}: {1}", resultwithindex.Index, resultwithindex.result));
}
Zarb function
public float zarb(int userid, int itemid)
{
float[] u_f = a[userid];
float[] i_f = b[itemid];
for (int i = 0; i < u_f.Length; i++)
{
result += u_f[i] * i_f[i];
}
return result;
}
No you don't. The Add method (surprisingly) adds an item into the list. It doesn't replace anything. You should read MSDN documentation for List<T>. Also, don't be afraid of trying and seeing the results before asking—you'll save time.
Maybe I don't understand the question, but you do not need index for list. The add method will deal with the it.
int i = 0;
int x = 10;
List<int> group = new List<int>();
while (i < x)
{
RichTextBoxShowTafel.AppendText(Convert.ToString(group[i]));
i++;
}
Why does this not work? I want to display the first 10 numbers of the List called: "group".
edit:
I actually want to create variables and print it in a row...
You never put anything in the group variable. You only instantiated an empty list.
And you'd be better off doing this:
foreach (int item in group)
{
RichTextBoxShowTafel.AppendText(item.ToString());
}
Because group is empty? As it has no elements, you can't access group[0], which is what you do in the first iteration
This is because group is empty!
When your loop first executes then i = 0 then you try Convert.ToString(groups[i]) which will always fail as there is no index of 0 in group
You should add elements in the list before you try to get them. The is the reason you got ArgumentOutOfRangeException. You can avoid the exception by adding element first.
int i = 0;
int x = 10;
List<int> group = new List<int>();
while (i < x)
{
group.Add(i);
RichTextBoxShowTafel.AppendText(Convert.ToString(group[i]));
i++;
}
If you are expecting group to be populated with numbers, you will have to do that yourself. Declaring and initializing it List<int> group = new List<int>(); only creates it. There is nothing inside. If you want to try putting variables in you can do something like this:
for(int j = 0; j < 10; j++)
{
group.Add(j);
}