How do i define starting position of listbox? - c#

I want to define the listbox rows to start at 1, not the default 0. How do i do it ?

You dont. You basically learn to work within the context of the environment you use. WPF defines table positions in general to start at 0.
Feel free to program your own WPF replacement.

If you are determined to do it, I would make a method
private int ListIndex(int index){
return index - 1;
}
And then use ListIndex anywhere you index into the list, but as others pointed out, you really should shift your mindset to deal with 0 based indexes, as they are a standard in most programming situations.

This is really an issue of why or why not you should begin indices (of any kind, for that matter) from 0. See this post about the very topic. There are, arguably, some good reasons for starting an index from 0.
There are also some legacy technical reasons. For example, in C, the array was actually a pointer to the first element of the array, and the form array[i] is equal to *(array + i), meaning that what the index really refers to is the offset from the first element of the array. Thus, a 0 offset references the first element, and 1 offset references the second element, and so on.
It's all about mathematical beauty.

In simple words, you can't do that buddy.

Related

Replacing an Array to Avoid Using 0 Based Index

I have written a small API to allow users to control a power supply. The PowerController object can switch electrical ports on or off:
PowerController.SwitchOn(1)
PowerController.SwitchOff(3)
The PowerController can toggle the power on four different ports by specifying an integer between 1 and 4. The user can also read back the status of all four ports using:
PowerController.GetPortStatus()
This function returns a Boolean array with a true/false value for each of the 4 ports in it. The users of my API do not like the fact that they must specify a 1 based index to turn ports on or off, but must use a 0 based index to check the status of a given port. What would be the best way of returning the port status so that the user can use the same 1 based index number that they use when turning a port on or off?
You could return a Dictionary<int, bool> where the Key is the 1-based index of the port and a Value is the status of the port. This way, the users can use 1-based indexing, like this:
Dictionary<int, bool> portsStatus = PowerController.GetPortStatus();
bool statusOfPort1 = portsStatus[1];
If I'm grasp your idea, when running this method
PowerController.GetPortStatus()
just return an array, where the index of the array is PORT and Value (0, 1) is a flag:1- ON, 0 - OFF
example:
return new int{-1, 0, 0, 0, 1} (only port 4 is active)
I would provide an alternative to PowerController.GetPortStatus(), say additional static function:
PowerController.IsPortOn(portNumber); // This number is 1-based
This way your users will have a way to access this data in 1-based manner and this will also leave already-written code intact, thus providing backward-compatibility.
You must be consistent with your users ; you can't ask them to use 0-based here and 1-based there.
Whichever you chose doesn't matter, because you should have a class and/or and enum for your different states.
Working with classes and enums is better than boolean and indexes, its more readable, and it's also much more fun.
Or, if you really wanna work with index, decide if it's 0 or 1 based. According to their choices, add/substract 1 to every index so it fits your system.
They want a 1-based index but you have an array of booleans (which is not super-good, I insist), you can let them use their 1-based index, and just substract 1 every time you use it, so it's a 0-based index under the hood. :)
Many solutions work, the last one is very very easy. But I suggest some deeper refactoring like I (and probably others) mentioned.

remove ILArray<> elements

Using ILNumerics, I am trying to take the first n number of columns of an ILArray<> in the most efficient way possible.
using(ILScope.Enter(inframe)
{
ILArray<complex> frame = ILMath.check(inframe);
int[] dims = frame.Size.ToIntArray(); //frame is a 2d ILArray
frame.SetRange(complex.Zero, dims[0] -1 , (dims[1] * 2 - 1)); //doubles the size of the array with zeros.
//TODO- various computations.
frame.SetRange(null, dims[0], dims[1] - 1); //EXCEPTION: why doesn't this work?
}
In this example I am trying to take only the first half of the frame, but I am unable to size it back to the original dimensions. I have tried various permutations based on http://ilnumerics.net/ArrayAlter.html but have been unsuccessful.
The documentation for shrinking of ILNumerics arrays says:
The range definition must address the full dimension - for all dimensions except the one, which is to be removed.
You want to remove the last half from the 2nd dimension. So you must define full ranges for all other dimensions involved. Here, since frame is a matrix, there are only 2 dimensions. Hence, the first must get fully addressed.
It should work easier by using the C# indexer. The following example assumes your code in a class derived from ILMath. Otherwise, add ILMath. before all the full, r, and end functions / properties:
A[full, r(end / 2, end)] = null;
Watch out for ‘off by one’ errors and addressing with ‘end’. You may want to use end / 2 + 1 instead ?
Since you want the most efficient way, performance seems to be important to you. In this case, you should try to prevent from expanding and shrinking arrays! It is better to work with two arrays of different sizes: a large one and the original one. Copy the data accordingly. Expanding and shrinking does copy the data anyway, so this is not a disadvantage. Furthermore, frame.Size.ToIntArray() is not needed here. Simply use frame.S[0]and frame.S[1] for the length of the dimensions 0 and 1.

c# how do i make my list 1 based rather than 0 based

I have a list and i have added my winform textboxes to it as shown below, but the list is 0 based, as the count starts from 0, how do i make it 1 based?
List<TextBox> textBoxList = new List<TextBox>();
textBoxList.Add(textBox1);
textBoxList.Add(textBox2);
textBoxList.Add(textBox3);
textBoxList.Add(textBox4);
textBoxList.Add(textBox5);
textBoxList.Add(textBox6);
textBoxList.Add(textBox7);
textBoxList.Add(textBox8);
textBoxList.Add(textBox9);
textBoxList.Add(textBox10);
textBoxList.Add(textBox11);
textBoxList.Add(textBox12);
I have an index which can be any number from 1 to 12, illd like to use this index to find the right textbox so index 6 will be textbox 6 .. rather than textbox 5
You cannot make .NET's list one-based, but you can either (1) adjust your index down by one every time you read, or (2) insert a useless entry at position 0 and ignore it after that (not recommended).
You can inherit from list, and build your own data structure that adjusts indexes on the way in and out, but that would require a lot more effort, not to mention the amount of confusion among the readers, so I would strongly caution against doing that.
Things don't do this way - list/array access is inherently zero-index based, and a custom implementation to attempt to defy this would be confusing (I personally think naming a class to be descriptive of its nature, if this were its nature, would be harder than doing the logic for a specific case elsewhere).
What's the use case? Usually you can get by with incrementing an index value to represent a 'current', or 'count' value that would make sense to users, or maybe adjusting input from a user perspective to what is needed, but what is your specific case?
If what you want to do, based on your update, is get a control by index you can either start your index from 0 or adjust the input as mentioned (by decreasing it according to the offset you need in the array) - this is just as easy, if not easier, and straightforward enough for anyone to understand, as any other method.
Maybe in your case it will be better to use Dictionary? So, your code will transform to:
Dictionary<int, TextBox> textBoxes =
new Dictionary<int, TextBox>();
textBoxes.Add(1, textBox1);
But anyway it's a strange requirement.
You can define your own list class which extends the built in class and insert the first element in the construct function.
One rather awkward way to solve your problem of making the collection index 1-based is to use the Array class. You can then create an array instance with arbitrary lower bound. In your case it would look like this:
var textBoxList = Array.CreateInstance(typeof(TextBox), new[] {12}, new[] {1});
Defining the elements in this array is somewhat more cumbersome:
...
textBoxList.SetValue(textBox5, 5);
...
And similarly, accessing the elements is also rather explicit:
var tb9ref = (TextBox)textBoxList.GetValue(9);
heres what i did and it seems to work :D, simple enough i guess.. still learning ..
var tb = textBoxList;
int newDef = def - 1;
tb[newDef].Text = "occupied";

Retrieving the highest number in an array recursively in C#?

How can I retrieve the highest number in an array recursively in C#?
Right now you're probably thinking that we're mean for not giving you the answer -- and I admit that I have the answer written down and part of me wants to give it to you, even.
Programming is all about finding the solutions to problems yourself. When you're hired as a programmer, you may have other people to lean on, but they've all got their own problems, and you'll need to be able to pull your own weight.
Recursion (in an oversimplifed answer) means to call the same operation over and over until the result is produced. That means you need in every recursive operation, you need to know (at least) two things:
What you're looking for
What you've found so far
The 'What you're looking for' is the termination condition. Once you find that, all work can stop and you can go home.
The 'what you've found so far' is how you know what've you've checked so you don't retread old ground.
So what do you need to know in order to find the highest value in an array recursively?
The contents of the Array.
The highest number you've found so far.
Have you already looked at this part of the Array? (Why look through it again?)
That would produce a method signature that looks like:
public int GetHighestNumber(int[] array, int highestNumberFound, int lastIndexChecked);
Once you're inside the array, you've got to do the following:
Iterate through the array
Stop when you find a value that is higher than the highestNumberFound
Call GetHighestNumber again with the new highestNumberFound and lastIndexChecked updated.
When there are no more 'higher' numbers, then return the highest number found.
I realize it sounds trite, but learning this stuff on your own will make you a better programmer.
If you want to be a professional programmer, you have got to learn this stuff on your own.
If you don't want to be a professional programmer, then drop the course and do something you love.
Here's just a hint (taking int[] as an example):
public int FindMax(int[] array, int indexSoFar, int maxSoFar)
Think about:
The start conditions
The termination conditions
How you move through the array recursively
Reason of EDIT: Didnt want to spoil the answere.
Greetings.

How can I sort an array of strings?

I have a list of input words separated by comma. I want to sort these words by alphabetical and length. How can I do this without using the built-in sorting functions?
Good question!! Sorting is probably the most important concept to learn as an up-and-coming computer scientist.
There are actually lots of different algorithms for sorting a list.
When you break all of those algorithms down, the most fundamental operation is the comparison of two items in the list, defining their "natural order".
For example, in order to sort a list of integers, I'd need a function that tells me, given any two integers X and Y whether X is less than, equal to, or greater than Y.
For your strings, you'll need the same thing: a function that tells you which of the strings has the "lesser" or "greater" value, or whether they're equal.
Traditionally, these "comparator" functions look something like this:
int CompareStrings(String a, String b) {
if (a < b)
return -1;
else if (a > b)
return 1;
else
return 0;
}
I've left out some of the details (like, how do you compute whether a is less than or greater than b? clue: iterate through the characters), but that's the basic skeleton of any comparison function. It returns a value less than zero if the first element is smaller and a value greater than zero if the first element is greater, returning zero if the elements have equal value.
But what does that have to do with sorting?
A sort routing will call that function for pairs of elements in your list, using the result of the function to figure out how to rearrange the items into a sorted list. The comparison function defines the "natural order", and the "sorting algorithm" defines the logic for calling and responding to the results of the comparison function.
Each algorithm is like a big-picture strategy for guaranteeing that ANY input will be correctly sorted. Here are a few of the algorithms that you'll probably want to know about:
Bubble Sort:
Iterate through the list, calling the comparison function for all adjacent pairs of elements. Whenever you get a result greater than zero (meaning that the first element is larger than the second one), swap the two values. Then move on to the next pair. When you get to the end of the list, if you didn't have to swap ANY pairs, then congratulations, the list is sorted! If you DID have to perform any swaps, go back to the beginning and start over. Repeat this process until there are no more swaps.
NOTE: this is usually not a very efficient way to sort a list, because in the worst cases, it might require you to scan the whole list as many as N times, for a list with N elements.
Merge Sort:
This is one of the most popular divide-and-conquer algorithms for sorting a list. The basic idea is that, if you have two already-sorted lists, it's easy to merge them. Just start from the beginning of each list and remove the first element of whichever list has the smallest starting value. Repeat this process until you've consumed all the items from both lists, and then you're done!
1 4 8 10
2 5 7 9
------------ becomes ------------>
1 2 4 5 7 8 9 10
But what if you don't have two sorted lists? What if you have just one list, and its elements are in random order?
That's the clever thing about merge sort. You can break any single list into smaller pieces, each of which is either an unsorted list, a sorted list, or a single element (which, if you thing about it, is actually a sorted list, with length = 1).
So the first step in a merge sort algorithm is to divide your overall list into smaller and smaller sub lists, At the tiniest levels (where each list only has one or two elements), they're very easy to sort. And once sorted, it's easy to merge any two adjacent sorted lists into a larger sorted list containing all the elements of the two sub lists.
NOTE: This algorithm is much better than the bubble sort method, described above, in terms of its worst-case-scenario efficiency. I won't go into a detailed explanation (which involves some fairly trivial math, but would take some time to explain), but the quick reason for the increased efficiency is that this algorithm breaks its problem into ideal-sized chunks and then merges the results of those chunks. The bubble sort algorithm tackles the whole thing at once, so it doesn't get the benefit of "divide-and-conquer".
Those are just two algorithms for sorting a list, but there are a lot of other interesting techniques, each with its own advantages and disadvantages: Quick Sort, Radix Sort, Selection Sort, Heap Sort, Shell Sort, and Bucket Sort.
The internet is overflowing with interesting information about sorting. Here's a good place to start:
http://en.wikipedia.org/wiki/Sorting_algorithms
Create a console application and paste this into the Program.cs as the body of the class.
public static void Main(string[] args)
{
string [] strList = "a,b,c,d,e,f,a,a,b".Split(new [] { ',' }, StringSplitOptions.RemoveEmptyEntries);
foreach(string s in strList.Sort())
Console.WriteLine(s);
}
public static string [] Sort(this string [] strList)
{
return strList.OrderBy(i => i).ToArray();
}
Notice that I do use a built in method, OrderBy. As other answers point out there are many different sort algorithms you could implement there and I think my code snippet does everything for you except the actual sort algorithm.
Some C# specific sorting tutorials
There is an entire area of study built around sorting algorithms. You may want to choose a simple one and implement it.
Though it won't be the most performant, it shouldn't take you too long to implement a bubble sort.
If you don't want to use build-in-functions, you have to create one by your self. I would recommend Bubble sort or some similar algorithm. Bubble sort is not an effective algoritm, but it get the works done, and is easy to understand.
You will find much good reading on wikipedia.
I would recommend doing a wiki for quicksort.
Still not sure why you don't want to use the built in sort?
Bubble sort damages the brain.
Insertion sort is at least as simple to understand and code, and is actually useful in practice (for very small data sets, and nearly-sorted data). It works like this:
Suppose that the first n items are already in order (you can start with n = 1, since obviously one thing on its own is "in the correct order").
Take the (n+1)th item in your array. Call this the "pivot". Starting with the nth item and working down:
- if it is bigger than the pivot, move it one space to the right (to create a "gap" to the left of it).
- otherwise, leave it in place, put the "pivot" one space to the right of it (that is, in the "gap" if you moved anything, or where it started if you moved nothing), and stop.
Now the first n+1 items in the array are in order, because the pivot is to the right of everything smaller than it, and to the left of everything bigger than it. Since you started with n items in order, that's progress.
Repeat, with n increasing by 1 at each step, until you've processed the whole list.
This corresponds to one way that you might physically put a series of folders into a filing cabinet in order: put one in; then put another one into its correct position by pushing everything that belongs after it over by one space to make room; repeat until finished. Nobody ever sorts physical objects by bubble sort, so it's a mystery to me why it's considered "simple".
All that's left now is that you need to be able to work out, given two strings, whether the first is greater than the second. I'm not quite sure what you mean by "alphabetical and length" : alphabetical order is done by comparing one character at a time from each string. If there not the same, that's your order. If they are the same, look at the next one, unless you're out of characters in one of the strings, in which case that's the one that's "smaller".
Use NSort
I ran across the NSort library a couple of years ago in the book Windows Developer Power Tools. The NSort library implements a number of sorting algorithms. The main advantage to using something like NSort over writing your own sorting is that is is already tested and optimized.
Posting link to fast string sort code in C#:
http://www.codeproject.com/KB/cs/fast_string_sort.aspx
Another point:
The suggested comparator above is not recommended for non-English languages:
int CompareStrings(String a, String b) {
if (a < b) return -1;
else if (a > b)
return 1; else
return 0; }
Checkout this link for non-English language sort:
http://msdn.microsoft.com/en-us/goglobal/bb688122
And as mentioned, use nsort for really gigantic arrays that don't fit in memory.

Categories

Resources