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.
Related
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
int[] listOfValues = {1, 2, 5, 2, 6};
I need to be able to find all pair combinations of this array, including repetitions. Each value in the array comes from a deck of cards. So, if the value "2" appears twice in the array, for example, we can assume that these are two different values, and as such, need to be treated separately.
Sample of expected pairs of cards:
{1, 2}
{1, 2}
{2, 1}
{2, 1}
{2, 2}
{1, 5}
{1, 6}
etc.......
These separate int[] results will then need to be added to a List (if you can even add duplicate int[] values to a list, that is!), once all possible values have been found.
I have looked for a few hours online, and can't seem to get any of the solutions working for my particular task.
Does anyone have any ideas please?
You should really do homework on your own. Or at least try it first. You haven't provided code, so I cannot ethically give you the full solution.
However, this will get you started:
Think about it as if you were to do it by hand. Most people would pick the first value and the second value and write them down. Then they would write that pair backwards. Then they would do the first value and the third, then backwards, and so on and so on.
It would look something like:
{1,2}
{2,1}
{1,5}
{5,1}
{1,2}
{2,1}
{1,6}
{6,1}
{2,5} -Now we iterate again, starting with the second value
So how would we express that in code? Nested loops!
Here is the skeleton of an algorithm to solve your problem:
List<int[]> pairs = new List<int[]>();
for(int x = 0; x < listOfValues.Length - 1; x++)
{
for(int y = x+1; y < listOfValues.Length; y++)
{
// Create an array of the [x] position and [y] position of listOfValues
// Create another array, except swap the positions {[y],[x]}
// Add both arrays to the "pairs" List
}
}
Try to understand what this code is doing. Then fill in the blanks. You should get the correct answer. Always make sure to understand why, though. Also, try to see if you can figure out any improvements to this code.
With linq you could do it this way.
int[] listOfValues = { 1, 2, 5, 2, 6 };
var combination = listOfValues.Select(i => listOfValues.Select(i1 => new Tuple<int, int>(i, i1)).ToList())
.ToList()
.SelectMany(list => list.Select(x => x)).ToList();
With thanks to Clay07g's post, I was able to resolve the problem with the following code:
public static List<int[]> getCardCombos(int[] values)
{
List<int[]> pairs = new List<int[]>();
for (int x = 0; x < values.Length - 1; x++)
{
for (int y = x + 1; y < values.Length; y++)
{
int firstValue = values[x];
int secondValue = values[y];
// Create an array of the [x] position and [y] position of listOfValues
int[] xAndY = { firstValue, secondValue};
// Create another array, except swap the positions {[y],[x]}
int[] yAndX = { secondValue, firstValue };
pairs.Add(xAndY);
pairs.Add(yAndX);
// Add both arrays to the "pairs" List
}
}
return pairs;
}
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 };
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!?
I have to copy the following int array in to Array :
int[] intArray=new int[] {10,34,67,11};
i tried as
Array copyArray=Array.CreateInstance(typeof(int),intArray.Length,intArray);
intArray.CopyTo(copyArray,0);
But ,it seems i have made a mistake,so i did not get the result.
This works:
int[] intArray = new int[] { 10, 34, 67, 11 };
Array copyArray = Array.CreateInstance(typeof(int), intArray.Length);
intArray.CopyTo(copyArray, 0);
foreach (var i in copyArray)
Console.WriteLine(i);
You had one extra "intArray" in your Array.CreateInstance line.
That being said, this can be simplified if you don't need the Array.CreateInstance method (not sure if that's what you're trying to work out, though):
int[] intArray = new int[] { 10, 34, 67, 11 };
int[] copyArray = new int[intArray.Length];
intArray.CopyTo(copyArray, 0);
Even simpler:
int[] intArray = new int[] { 10, 34, 67, 11 };
int[] copyArray = (int[])intArray.Clone();
Are you aware that an int[] is already an Array? If you just need to pass it to something accepting Array, and you don't mind if it changes the contents, just pass in the original reference.
Another alternative is to clone it:
int[] clone = (int[]) intArray.Clone();
If you really need to use Array.CopyTo then use the other answers - but otherwise, this route will be simpler :)
Try this instead:
int[] copyArray = new int[intArray.Length];
Array.Copy(intArray, copyArray, intArray.Length);
In this particular case, just use
int[] copyArray = (int[]) intArray.Clone();