c# Leaner way of initializing int array - c#

Having the following code is there a leaner way of initializing the array from 1 to the number especified by a variable?
int nums=5;
int[] array= new int[nums];
for(int i=0;i<num;i++)
{
array[i] = i;
}
Maybe with linq or some array.function?

int[] array = Enumerable.Range(0, nums).ToArray();

Use Enumerable.Range() method instead of. Don't forget to add System.Linq namespace. But this could spend little bit high memory. You can use like;
int[] array = Enumerable.Range(0, nums).ToArray();
Generates a sequence of integral numbers within a specified range.

Using Enumerable.Range
int[] array = Enumerable.Range(0, nums).ToArray();

Maybe I'm missing something here, but here is the best way I know of:
int[] data = new int [] { 383, 484, 392, 975, 321 };
from MSDN
even simpler:
int[] data = { 383, 484, 392, 975, 321 };

Related

How can i convert my int array to string array in c#?

I'm new in c# unity. I've to save my array of positions inside firebase for that I'm creating an int array like
int[] positions = new int[] {2, 4, 3};
its working fine but I don't know how can I convert this into string array like "[2, 4, 3]" to save in firebase.
I've searched on google and tried
string stringPositions = string.Join("", positions);
but it completely converts my array into a string like 234. And also how can I encode this string again into an array. Let me know if there is any other approach to do this. thanks!
First of all your question is wrong, you want to convert int array into string.
Use this:
int[] positions = new int[] {2, 4, 3};
string result = "[" + string.Join(",", positions) + "]";
Or this:
int[] positions = new int[] {2, 4, 3};
StringBuilder stb = new StringBuilder();
stb.Append("[");
stb.Append(string.Join(",", positions));
stb.Append("]");
string result = stb.ToString();
Or if you have C#6 or higher:
int[] positions = new int[] {2, 4, 3};
string result = $"[{string.Join(",", positions)}]";
Also if you want to convert back to your int array, for example you can just write your converter:
private int[] ConvertToIntArray(string myCustomString) //myCustomString is in "[1,2,3]" format
{
return myCustomString.Substring(1, myCustomString.Length - 2)
.Split(',')
.Select(s => int.Parse(s))
.ToArray();
}
"[1,2,3,4]"
is a json format of int array. Not string array.
You can use any JSON parser to do this.
I would recommend using JsonUtility which is built in Unity API.
Follow this guide to understand how it works:
Serialize and Deserialize Json and Json Array in Unity
Hope this helps.
Since you are new better use loop
int[] positions = new int[] {2, 4, 3};
string[] s = new string[positions.Length];
for (int x=0; x<positions.Length; i++)
s[x] = positions[x].ToString();
You have to do it manually.
String arrStr = "[";
for ( int i = 0; i < arr.length() - 1; i++) {
arrStr.join(arr[i]);
arrStr.join(",");
}
arrStr.join(arr[arr.length() - 1]);
arrStr.join("]");
Now you will have your array as you desired.
You have asked for a string array but your example is actually just a string that happens to look how you'd declare your int array in code.
For an actual array of strings you'd do what someone else has said and use linq
string[] stringArray = positions.select(p => p.ToString());
This would give you a new array who's item data type would be string .
If you want an actual string of text that looks like what you've asked for
string stringRepresentation = $"[{string.Join(", ", positions)}]";
Or with an old fashioned string format:
string stringRepresentation = string.Format("[{0}]", string.Join(", ", positions);
But just to be clear. This is isn't in depth stuff. Some quick googling and understanding of how to use the string.Join method would have brought you this answer.
So I'm going to l leave you with a pointer towards the trim method on a string and also the split method which should give you everything you need to recreate your int array

Accessing arrays dynamically

I'm working on a project. I've a situation here. I'm having arrays with similar names consider arr1, arr2, arr3, etc.
Now I know the array number which I'm supposed to use let it be 2. Is there any way in c# to make the array name dynamically through strings and use it.
Like in flash action script we can do
_root["arr"+i][0]
here i contains the array number to be used.
No - you cannot access variable names dynamically. You can use reflection to dynamically access properties, but not variables. I would use a List<int[]> like so:
List<int[]> arrList = new List<int[]> {arr1, arr2, arr3);
int[] arr = arrList[i-1]; // since lists and arrays use 0-based indexes
You can use a dictionary:
var dictionary = new Dictionary<string, int[]>();
dictionary.Add("array1", arr1);
dictionary.Add("array2", arr2);
dictionary.Add("array3", arr3);
var arr = dictionary[string.Format("array{0}", i)];
What you want is something what JavaScript or dynamic languages have, but their array types are rather associative arrays. To reach the functionality you want you can use Dictionary:
var arr1 = new int[] { 0, 1, 2, 3 };
var arr2 = new int[] { 0, 1, 2, 3 };
var arr3 = new int[] { 0, 1, 2, 3 };
var _root = new Dictionary<string, int[]>();
_root.Add("arr1", arr1);
_root.Add("arr2", arr2);
_root.Add("arr3", arr3);
for (int i = 1; i <= 3; i++)
{
int arrElem = _root["arr" + i][0];
}
Note the expression within the for loop, it's like what you were asking for.
use list for performing dynamic operations
As suggested in other answers the way to achieve the dynamism you're looking for is to put all of the arrays in a collection ( List<int[]> ) and then you can write more generalized code which operates on the contents of a given array without knowing which array it's operating on at compile time.

C# 3 dimensional array

I want to store ARRAY from 3 dimensional array into buildingCostIds, but it says I MUST have 3rd number.
public static int[, ,] buildingCost = { {{0,1,2},{5,5,5}}};
public static void addBuilding(int[] ids, int[] amounts, int buildingId)
{
int[] buildingCostIds = buildingCost[buildingId, 0, *];
}
*I need third number here, but I don't want it because it will extract just number, I want whole array!
PROBLEM SOLVED, solution:
public static Array extractArray(int dim1, int dim2)
{
int[] tempArray = { };
for (int number=0;number<=2; number++)
{
tempArray[number] = buildingCost[dim1, dim2, number];
}
return tempArray;
}
This might be simpler if you use an array-of-arrays, or jagged array [][][] like
int[][][] buildingCost = new int[2][][];
Then you can access buildingCost[buildingId, 0] which is an array of ints.
There is a related question here
EDIT
Be aware the "problem solved" you added to the question duplicates the data, so you may run out of memory if you keep doing this.
Consider using a List of Lists of Lists and lazy evaluating what you need.
Try This
int[, ,] array3D = new int[3,3,3]

C#: Elegant code for getting a random value from an IEnumerable

In Python, I can do this:
>>> import random
>>> ints = [1,2,3]
>>> random.choice(ints)
3
In C# the first thing I did was:
var randgen = new Random();
var ints = new int[] { 1, 2, 3 };
ints[randgen.Next(ints.Length)];
But this requires indexing, also the duplication of ints bothers me. So, I came up with this:
var randgen = new Random();
var ints = new int[] { 1, 2, 3 };
ints.OrderBy(x=> randgen.Next()).First();
Still not very nice and efficient. Is there a more elegant way of getting a random value from an IEnumberable?
Here's a couple extension methods for you:
public static T RandomElement<T>(this IEnumerable<T> enumerable)
{
return enumerable.RandomElementUsing<T>(new Random());
}
public static T RandomElementUsing<T>(this IEnumerable<T> enumerable, Random rand)
{
int index = rand.Next(0, enumerable.Count());
return enumerable.ElementAt(index);
}
// Usage:
var ints = new int[] { 1, 2, 3 };
int randomInt = ints.RandomElement();
// If you have a preexisting `Random` instance, rand, use it:
// this is important e.g. if you are in a loop, because otherwise you will create new
// `Random` instances every time around, with nearly the same seed every time.
int anotherRandomInt = ints.RandomElementUsing(rand);
For a general IEnumerable<T>, this will be O(n), since that is the complexity of .Count() and a random .ElementAt() call; however, both special-case for arrays and lists, so in those cases it will be O(1).
No, that's basically the easiest way. Of course, that's only semi-random, but I think it fits most needs.
EDIT: Huge Point Here...
If you only want ONE value randomly chosen from the list... then just do this:
var myRandomValue = ints[(new Random()).Next(0, ints.Length)];
That's a O(1) operation.
Sorting will be far less efficient. Just use Skip(n) and First():
var randgen = new Random();
var ints = new int[] { 1, 2, 3};
ints.Skip(x=> randgen.Next(0, ints.Count())).First();
ints.ElementAt(x=> randgen.Next(0, ints.Count()));
How about something simple and readable:
ints[randgen.Next(ints.Length)];
Seriously, why obfuscate your code with lambdas .OrderBy and .First and .Skip and so forth!?

Obtaining the min and max of a two-dimensional array using LINQ

How would you obtain the min and max of a two-dimensional array using LINQ? And to be clear, I mean the min/max of the all items in the array (not the min/max of a particular dimension).
Or am I just going to have to loop through the old fashioned way?
Since Array implements IEnumerable you can just do this:
var arr = new int[2, 2] {{1,2}, {3, 4}};
int max = arr.Cast<int>().Max(); //or Min
This seems to work:
IEnumerable<int> allValues = myArray.Cast<int>();
int min = allValues.Min();
int max = allValues.Max();
here is variant:
var maxarr = (from int v in aarray select v).Max();
where aarray is int[,]
You could implement a List<List<type>> and find the min and max in a foreach loop, and store it to a List. Then you can easily find the Min() and Max() from that list of all the values in a single-dimensional list.
That is the first thing that comes to mind, I am curious of this myself and am gonna see if google can grab a more clean cut approach.

Categories