I want to create an array of references to my arrays. The reason for this is because i want to optimise my fast Fourier transform algorithm to be branchless - or rather, less branchy.
The idea behind it is i have two arrays:
Array1 and Array2
I need to ping pong between the two in a for loop so i want to store the reference to the arrays like this:
[0] = Array1Ref
[1] = Array2Ref
[2] = Array1Ref
. . .
Is it possible to do this in C#? If so how would you define such an array - would i need to use unsafe ?
If you just want to access a different array in each iteration of the for loop without using a conditional, you can keep swapping two variables and use one of them.
var arrayRef = Array1;
var theOtherArrayRef = Array2;
for (...) {
// use arrayRef in places where you would have accessed the array of array references
...
// C# 7 tuple syntax
(arrayRef, theOtherArrayRef) = (theOtherArrayRef, arrayRef);
// pre-C# 7:
/*
var temp = arrayRef;
arrayRef = theOtherArrayRef;
theOtherArrayRef = arrayRef;
*/
}
Related
This question already has answers here:
Copy Arrays to Array
(7 answers)
Closed 1 year ago.
In C# and many other languages, if you pass an array to a function it passes the pointer/reference which means you can change the value of an array from inside a function.
From Microsoft:
Arrays can be passed as arguments to method parameters. Because arrays are reference types, the method can change the value of the elements.
I have a special case where I need to access and change an array's contents from a function but I do not want to change the original array. I thought this would be quite simple. I could set a new array equal to the old array and change the new array. This acts the same, however, because the new array is just a pointer to the old one.
static void AddToArray(string[] array) {
var newArray = array;
newArray[2] = "y";
}
static void Main(string[] args) {
string[] array = new string[5];
array[0] = "h";
array[1] = "e";
AddToArray(array);
}
If you print the contents of array at each step:
"he"
"hey" (inside function)
"hey" (after function call)
I've done a lot of research online but somehow haven't found many other people who needed help with this. Advice is greatly appreciated!
You are not creating your array using "new" Keyword inside function. Change below line -
var newArray = array;
To
var newArray = new string[args.Length];
and after creating this as a new array, you can copy the values from args (passed) array
I'm a little bit confused. I try to assign a string array to a two dimensional string array. But get "Wrong number of indices" error.
I understand the error, but should it not be possible to assign an array to the second dimension array field?
As sortedString has x number of fields with each an string array, should it not be possible to assign an string array to just a indexed field? (as the s.Split(';') already creates an array)
string[,] sortedString = new string[count,columns];
sortedString[counter] = s.Split(';');
You're confusing a multidimensional array with a jagged array. sortedString is a 2-dimensional array of type string, so you must always provide the correct number of indices - in this case, 2. You can't say sortedString[x], you can only say sortedString[x, y].
You're probably thinking of a jagged array - i.e., a single-dimensional array, where each element is itself a (usually single-dimensional) array. Declare sortedString like this:
string[][] sortedString = new string[count][];
This will allow each "inner" array to be of a different length (depending on how many ; there are in each s), which might not be what you want.
C# has two kinds of 2D arrays. If you need access to one dimension at a time as it's own array, you must use the "jagged" variety, like this:
string[][] sortedString = new string[count][];
for(int i = 0; i<sortedString.Length;i++)
sortedString[i] = new string[columns];
Or, even better:
var sortedString = new List<string[]>;
I am just beginning with programming in c#;
I got a list of int variables that I want to sort, and find the number 1.
int Weapon_Count1, Weapon_Count2, Weapon_Count3, Weapon_Count4, Weapon_Count5, Weapon_Count6, Weapon_Count7, Weapon_Count8, Weapon_Count9
do I need to do this with an array?
By using the yellow book of C# I found out how to make an array, but I can't figure out how to assign the variables to the array.
int [] Weapon_Count = new int [11] ;
for ( int i=0; i<11; i=i+1)
{
Weapon_Count [i] = ??? ;}
I hope this does make sense..
Please let me explain how to use a C#-array.
This creates an unitialized integer-array with 5 elements:
int[] a1= new int[5];
Assigning values 9,8,7,6 and 5:
(Please note that only indexes from 0 to 4 can be used. Index 5 is not valid.)
a1[0]=9;
a1[1]=8;
a1[2]=7;
a1[3]=6;
a1[4]=5;
The same can also achieved with just one line:
int[] a1= new int[] {9,8,7,6,5};
This might help you.
// Declaring the array
int[] Weapon_Count;
// Initializing the array with a size of 11
Weapon_Count = new int[11];
// Adding values to the array
for (int i = 0; i < Weapon_Count.Length; i++)
{
Weapon_Count[i] = i + 100;
}
// Printing the values in the array
for (int i = 0; i < Weapon_Count.Length; i++)
{
Console.WriteLine(Weapon_Count[i]);
}
// Same thing with a list
// Daclare and initializing the List of integers
List<int> weapon_list = new List<int>();
// Adding some values
weapon_list.Add(1);
weapon_list.Add(2);
weapon_list.Add(3);
weapon_list.Add(4);
weapon_list.Add(5);
// Printing weapin_list's values
for (int i = 0; i < weapon_list.Count; i++)
{
Console.WriteLine(weapon_list[i]);
}
// This is just for the console to wait when you are in debug mode.
Console.ReadKey();
Dont forget to include the using statment if you want to use lists (in short hand - dynamic arrays that can change in size.)
using System.Collections.Generic;
The easiest way to do this, assuming there is a finite list of variables to check, would be to throw them into a temporary array and call either Max() or Min() from the System.Linq namespace.
int maxCount = new int[] { Weapon_Count1, Weapon_Count2, Weapon_Count3, Weapon_Count4, Weapon_Count5, Weapon_Count6, Weapon_Count7, Weapon_Count8, Weapon_Count9 }.Max(); // or .Min()
EDIT
If you still want to get those variables into an array, I would recommend using a System.Collections.Generic.List which has a dynamic size and helper methods such as .Add() to simplify things. Lists can also be used with Linq functions similar to the first part of my answer. See Dot Net Perls for some really good examples on different C# data types and functions.
EDIT 2
As #kblok says, you'll want to add using System.Linq; at the top of your file to gain access to the functions such as Max and Min. If you want to try using the List type, you'll need to add using System.Collections.Generic; as well. If you're in Visual Studio 2017 (maybe 2015 as well?) you can type out the data type and then hit Ctrl + . to get suggestions for namespaces that might contain that data type.
Before we start, you might edit your array to look like this:
int[] weapons = { Weapon_Count1, Weapon_Count2, Weapon_Count3, Weapon_Count4, Weapon_Count5, Weapon_Count6, Weapon_Count7, Weapon_Count8, Weapon_Count9 };
This means that you've created an array called weapons and it is holding integer values.
After you did this, lets find out which element in your array has value of number one.
To find which value has value "1" we must look at each element in array, and we might do that on few ways but I would like recommend foreach or for loop, in this case I will choose foreach loop.
foreach(var item in weapons)
{
if (item == 1)
//Do something
}
This above means, loop throught all of my elements, and in case some of them is equal to number one please do something..
P.S
(I may advice to create one variable which will hold an element which has value '1' and when you find it in a loop assing that variable to that element, and later you can do whatever you want with that variable.. and if you think there will be more elements with value of number one and you need all of them, instead of variable I mentioned above you will create list or array to hold all of your elements and also you can do later with them whatever you want to.)
Thanks and if you are interested in this kind of solution, leave me a comment so let me help you till the end to solve this if you are still struggling.
In C# you can do this:
poules = new int[aantal, aantal, 2];
I couldn't find a way in PHP to do this. All I can find is a two dimensional array.
The example you presented is creating a 3D array, and getting it by a method (which is a bit slower, since a method is used). PHP uses jagged arrays.
An array in PHP is created using the array function.
To match your example: (for fixed array length)
$myArr = new SplFixedArray($aantal);
for ($i = 0; $i < $aantal; $i++) {
$myArr[$i] = new SplFixedArray($aantal);
for ($j = 0; $j < $aantal; $j++) {
$myArr[$i][$j] = new SplFixedArray(2);
}
}
SplFixedArray is used to define an array with a fixed size.
As claimed in comments, you will rarely see a PHP code as the above.
you can access the array cells like this:
$val = $myArr[$x][$y][$z];
Here is a reference: SplFixedArray
I'm not a C# person, so take this with a grain of salt. After perusing the documentation though, new int[aantal, aantal, 2] seem to be the syntax to declare multi-dimensional int arrays, in this case a 3-dimensional array.
PHP doesn't have multi-dimensional arrays. It only has arrays, and you can have arrays of arrays. I guess this is called a "jagged array" in C#. PHP arrays are also not typed, there's no equivalent to int[].
You can simply declare/access several dimensions at once though:
$arr = array();
$arr[1][2][3] = 'foo';
PHP will create the intermediate arrays as needed. The array is jagged though, there's no $arr[0][2][3] after the above code executed.
If you need to pre-allocate all dimensions beforehand, you will have to recursively loop. This is not really something done very often in PHP though, you should adapt your practices to work with jagged arrays to get things done.
This would be a php array:
$poules = array('aantal', 'anntal', '2');
In case aantal is a variable, just the same without quotes:
$poules = array($aantal, $anntal, '2');
In PHP you don't need to specify the variable type. Although you can use it to validate or filter inputs.
You can read more about PHP arrays in the official documentation:
http://uk3.php.net/manual/en/language.types.array.php
$poules = array('aantal', 'aantal', 2);
Or are aanta1 arrays too? Because in php you can do:
$myArray = array("some data", array("more data", "in a other array"), array("key1" => "even with keys"));
I am using a class called BigNumDesc that represents a number. I have a jagged array of that numbers, that represent a matrix.
I first declare this matrix the following way:
BigNumDec[][] matrix = new BigNumDec[][] {
new BigNumDec[] { 1, 2 },
new BigNumDec[] { 3, 4 }
};
Now, I have this method I want to call:
static BigNumDec[][] GetStrictlyUpperTriangle(BigNumDec[][] matrix)
{
BigNumDec[][] newMatrix = new BigNumDec[matrix.Length][];
matrix.CopyTo(newMatrix, 0);
return null;
}
I have a break-point in the last line. If in the watch window, I take any item of matrix, and change it, it will change too newMatrix, as all BigNumDec are reference types(bad design decision from the creator of it?). How can I accomplish this? I need to make modifications to newMatrix, so I must copy it first from matrix.
edit: Tried the same now with ints, but it's happening just the same. I'd it wouldn't happen with value types?
BigNumDec is immutable.
The reason it's still happening with value types is because you're using an array of arrays. You're shallow-copying the "outer" array, which just copies the references to the two "inner" arrays.
You haven't shown whether BigNumDec is immutable or not (I would hope so) but if it is, you should be fine if you just deep copy the array. Alternatively, can you use a rectangular array [,] instead of a jagged array [][]? If so, a simple copy would suffice. There are performance implications with rectangular arrays, mind you - it's worth testing this to see whether it'll be a problem for you. You get better locality of reference, but the actual array access isn't as fast.
The issue is with your initialisation of the BigNumDec array, you are creating a 1-dimensional array of BigNumDec objects. [0] = { 1, 2 }, [1] = { 3. 4 }. You are then effectively copying the references those objects, not their content, hence why the values continue to change.
Change your initialisation to:
BigNumDec[,] matrix = new BigNumDec[,] {
{ 1, 2 },
{ 3, 4 }
};
If your objects are Serializable you can implement deep copy using serialization. It's not very efficient (by performance) but it's simple.
public BigNumDec[][] CopyUsingSerialization(BigNumDec[][] original)
{
var binaryFormatter = new BinaryFormatter();
var serializationStream = new MemoryStream();
binaryFormatter.Serialize(serializationStream, original);
serializationStream.Position = 0;
var copy = (BigNumDec[][])binaryFormatter.Deserialize(serializationStream);
return copy;
}
You have to declare the BigNumDec as [Serializable]:
[Serializable]
public class BigNumDec
{
//class content
}
(as said in other answers here, if you can move to two dimensional array instead of jagged you'll get better solution)