Declaring an array with incremental values - is there a shortcut? - c#

This question is probably pretty stupid, but I'm new to C# and I'm not sure if there are any shortcuts to do this. I have a dynamic array for which the range will always be 1-n, with n being variable. Is there anyway to declare an array and have it hold incremental values without looping?
Think along the lines of my array holding values 1-50. I'd like to declare an array as such (logically): double[] myArray = new double[] {1-50} or, more generically for my purposes double[] myArray = new double[] {1-n}. I don't know what made me think of this, I just thought I'd ask.
I am going to bind this array (or list) to a combo box in WPF. I guess setting a combo-box the same way would also work if there's a shortcut for that.
Sorry for the dumb question. =)

int n = 50;
var doubleArray = Enumerable.Range(1, n).Select(x => (double)x).ToArray();
That will generate a sequence of integers from 1 to n (in this case 50) and then cast each one to a double and create an array from those results.

You could use a List<T> which represents a dynamic array to which you could add elements.

System.Linq.Enumerable.Range can generate än enumeration of int. Cast the enumeration if you really want double.
System.Linq.Enumerable.Range(1,20).ToArray()
http://msdn.microsoft.com/en-us/library/system.linq.enumerable.range.aspx

Related

Can't do arithmetical operations on array values in c#

I'm writing a program for homework, but I have stumbled upon a very hard problem for me.
Now, I'm pretty new to C#, so please bear with me. This may be really easy and obvious.
On-topic:
C# doesn't allow me to perform arithmetical operations on multidimensional array values:
if(map[0,1] - map[0,0] == 10)
This statement doesn't return a value, but instead throws me an error:
Object reference not set to an instance of an object.
You need to first declare the array. Example:
var map = new int[2,2];
creates a two-dimensional array with four integer elements.
the error sounds like you didn't initiate the values of the array
also don't forget that you took [,] arrays
int[,] example = new int[,] { {11,5}, {1,10} };//initiate the array
if (example[0,0]-example[1,0] == 10)
{
}

String Array comparision and sorting

First off, i'd like to say that my programming knowledge is very basic and got a learn as you go style. So please bear with me if i sound stupid.
So i have a multi dimensional string array, a part of which is:
X Y
4,1 Adelaide
4,2 Interlagos
4,3 Sakhir
4,4 Hungaroring
4,5 Estoril
4,6 Barcelona
4,7 Silverstone
4,8 Mugello
4,9 Hockenheim
4,10 Monte Carlo
In the above table, X and Y are the 2 dimensions of the array.
Now i have another string array with elements from X dimension of the above array in unsorted fashion. For example,
4,6
5,15
3,7
10,12
etc...
Now what i want to do is write a code which looks into array #2 and assigns a corresponding element from dimension Y of the array #1.
For example, when the code encounters 4,6 in array #2, i want the code to assign the corresponding value which is Barcelona.
Just the basic snippet or algorithm is what i'm looking for. I'll do the rest myself.
Thanks in advance!
Sounds like table 1 should really be a Dictionary<string, string>, mapping "4,6" to "Barcelona". Then you can just do:
// However you want to populate your data
Dictionary<string, string> mapping = ...;
List<string> values = keys.Select(key => mapping[key]).ToList();
Note that this will throw an exception if any of the keys isn't mapped - if that's not what you want, please clarify the requirements.
It's not clear how you're getting this data, or whether your "multi-dimensional string array" is a string[,] or a string[][]. If you have to receive it as a string array, give us more details and we can explain how to convert that into the dictionary.
You should rather use a Dictionary for that. A dictionary is internally an array. If you hand over a key, value pair (to insert it) a so called hash function is applied to the key. This function returns an integer i. The value is than stored at array[i]. If you want to get a value from the Dictionary you hand over just the key. Internally the hash function is applied, i is computed and array[i] is returned. This sounds like very much overhead, but searching for the key is slow for large arrays (O(log n) if it is sorted by keys and O(n) if it is not sorted at all - if you know O notiation), where the hash function can be very fast in most applications. So even with large dictionaries accessing a value is fast. (There are some more tricks inside a dictionary, which handle the case that two keys result in the same integer i, but you don't have to care much about that, if you don't want to implement a dictionary yourself)
Dictionarys are also called maps or hashmaps in other languages.
Not sure if I'm interpreting your question correctly here...
Your array #2, are you saying you want to replace its elements(say "4,6") with "Barcelona"?If this is the case then:
Loop through array #2, for each element use String.split() to get the two numerical parts from it(ex. "4" and "6"). Then use Integer.parseInt() to convert them from String to ints(call them a,b) and use those ints as indexes to array #1 like array1[a][b] to get Y value.
I assume you really want to use an array because those numbers are small and bounded, otherwise use dictionary as suggest by other answers...
If you must receive your first set of data as a 2D array, here's how you can turn it into a dictionary:
Dictionary<string, string> dic = new Dictionary<string,string>();
for (int i = 0; i < firstArray.GetLength(0); i++)
{
dic.Add(firstArray[i, 0], firstArray[i, 1]);
}

Create array of pointers from an array of double in C#

I'm trying to create an array of pointer references to a double array. For example;
double[] mylist = new double[100];
fixed (double* p = mylist) { }
Now as the MSDN documentation states, that is equivalent to p = &mylist[0] This is only taking the first value, is it possible to create an array of pointers to variables in another array? Or is the practice to use only one pointer?
Thanks for any help, in advance
Array elements are located in contiguous memory, so it's usually suffcient to have a pointer to the first element and do pointer arithmetic to get to the others.
When you have a typed pointer to a vector (or, more accurately, the first item in a vector), it works like in C/C++; all you need is the single pointer, and you can use it either as an individual item or as a zero-based array; you can still access p[3], except now instead of using array access metaphors, this is applying "3 * the-item-size as an offset relative to p". So:
p[3] = 1.0;
is fine. Note, of course, that if you go outside the array bounds accidentally, bad things will happen.

How to pass array in C#

I have a prototype:
int[] medianFileter(int[] data);
and an array
int[] intVal = new int[5];
How can I pass the intVal to the prototype in C#?
Um, you just call it (assuming you've got a real implementation to call):
int[] result = medianFileter(intVal);
Note that any changes made to the array within the method will show up in intVal: you're not passing each of the integers individually, but a reference to the whole array.
(There could be some trickiness here due to your use of the word "prototype" - it's not standard C# terminology, so I'm not exactly sure what you mean. If you could clarify the question, that would help.)
On a side note, method names in .NET are usually Pascal-cased, so this should probably be:
int[] result = ApplyMedianFilter(intVal);
It's either I don't see some obvious weirdness here, or it's just usual function invocation:
int[] medianFiltered = medialFileter(intVal);
This is what you would do,
medianFileter(intVal);
What's the problem with:
medianFileter(intVal);
?

Array of an unknown length in C#

I've just started learning C# and in the introduction to arrays they showed how to establish a variable as an array but is seems that one must specify the length of the array at assignment, so what if I don't know the length of the array?
Arrays must be assigned a length. To allow for any number of elements, use the List class.
For example:
List<int> myInts = new List<int>();
myInts.Add(5);
myInts.Add(10);
myInts.Add(11);
myInts.Count // = 3
Use List<> to build up an 'array' of unknown length.
Use List<>.ToArray() to return a real array, and not a List.
var list = new List<int>();
list.Add(1);
list.Add(2);
list.Add(3);
var array = list.ToArray();
A little background information:
As said, if you want to have a dynamic collection of things, use a List<T>. Internally, a List uses an array for storage too. That array has a fixed size just like any other array. Once an array is declared as having a size, it doesn't change. When you add an item to a List, it's added to the array. Initially, the List starts out with an array that I believe has a length of 16. When you try to add the 17th item to the List, what happens is that a new array is allocated, that's (I think) twice the size of the old one, so 32 items. Then the content of the old array is copied into the new array. So while a List may appear dynamic to the outside observer, internally it has to comply to the rules as well.
And as you might have guessed, the copying and allocation of the arrays isn't free so one should aim to have as few of those as possible and to do that you can specify (in the constructor of List) an initial size of the array, which in a perfect scenario is just big enough to hold everything you want. However, this is micro-optimization and it's unlikely it will ever matter to you, but it's always nice to know what you're actually doing.
You can create an array with the size set to a variable, i.e.
int size = 50;
string[] words = new string[size]; // contains 50 strings
However, that size can't change later on, if you decide you need 100 words. If you need the size to be really dynamic, you'll need to use a different sort of data structure. Try List.
Use an ArrayList if in .NET 1.x, or a List<yourtype> if in .NET 2.0 or 3.x.
Search for them in System.Collections and System.Collections.Generics.
You might also want to look into Dictionarys if your data is unique, This will give you two columns to work with.
User name , Total bill
it gives you a lot of built in tools to search and update just the value.
var yummy = new List<string>();
while(person.FeelsHappy()) {
yummy.Add(person.GetNewFavoriteFood());
}
Console.WriteLine("Sweet! I have a list of size {0}.", list.Count);
Console.WriteLine("I didn't even need to know how big to make it " +
"until I finished making it!");
try a generic list instead of array
In a nutshell, please use Collections and Generics.
It's a must for any C# developer, it's worth spending time to learn :)
As detailed above, the generic List<> is the best way of doing it.
If you're stuck in .NET 1.*, then you will have to use the ArrayList class instead. This does not have compile-time type checking and you also have to add casting - messy.
Successive versions have also implemented various variations - including thread safe variants.
If you really need to use an array instead of a list, then you can create an array whose size is calculated at run time like so...
e.g i want a two dimensional array of size n by n. n will be gotten at run time from the user
int n = 0;
bool isInteger = int.TryParse(Console.ReadLine(), out n);
var x = new int[n,n];

Categories

Resources