Tutorial :Ways in .NET to get an array of int from 0 to n



Question:

I'm searching the way(s) to fill an array with numbers from 0 to a random. For example, from 0 to 12 or 1999, etc.

Of course, there is a for-loop:

var arr = int[n];  for(int i = 0; i < n; i++)  {    arr[i] = i;  }  

And I can make this method been an extension for Array class. But is there some more interesting ways?


Solution:1

This already exists(returns IEnumerable, but that is easy enough to change if you need):

arr = Enumerable.Range(0, n);  


Solution:2

The most interesting way in my mind produces not an array, but an IEnumerable<int> that enumerates the same number - it has the benefit of O(1) setup time since it defers the actual loop's execution:

public IEnumerable<int> GetNumbers(int max) {      for (int i = 0; i < max; i++)          yield return i;  }  

This loop goes through all numbers from 0 to max-1, returning them one at a time - but it only goes through the loop when you actually need it.

You can also use this as GetNumbers(max).ToArray() to get a 'normal' array.


Solution:3

The best answer depends on why you need the array. The thing is, the value of any array element is equal to the index, so accessing any element is essentially a redundant operation. Why not use a class with an indexer, that just returnes the value of the index? It would be indistinguishable from a real array and would scale to any size, except it would take no memory and no time to set up. But I get the feeling it's not speed and compactness you are after. Maybe if you expand on the problem, then a better solution will be more obvious.


Note:If u also have question or solution just comment us below or mail us on toontricks1994@gmail.com
Previous
Next Post »