I've been trying to find a solution to this problem in particular.
Write a procedure that modifies the incoming array of ints by reversing it. Because this is a procedure, it will not return anything. Instead, I will have to modify the array directly, and because arrays are reference type variables, the array will be permanently changed even after this procedure. To reverse an array, imagine the array with an imaginary line in the middle of it, and then swap the numbers on the left with the numbers on the right side.
At the moment, this is the only code I've written down for the problem. Based on the code I've written so far, I don't think I'm approaching it towards the correct solution for it.
public void Test10(int[] numbers)
{
for (int i = 0; i < numbers.Length; i++)
{
}
You could use built-in Array.Reverse method, which reverses the sequence of the elements in the entire one-dimensional Array.
Array.Reverse(array); // reverse supplied array
Please note, System.Array.Reverse() does in place transformation.
There are 2 options based on your preference and need
int[] array = {1,3};
Array.Reverse(array);
This will reverse the original array
int[] array = {1,3};
var reversedArray = array.Reverse().ToArray();
This will use linq and new reversed array will be returned and original array will remain as it is
Related
I have a function that can take a 1d array (double[]) as an argument while my source data is a 2d array (double[,]) of 'cnt' number of 3d points, like so
double[,] points = new double[3,cnt]
But what I actually want to do is to pass on each of the three 2nd dim arrays to the function gpu.Average(double[] arg), preferably without having to copy the content of the arrays value[i] by value[i]. Is that possible in C#?
EXAMPLE CODE
This works:
double[] points1d = new double[cnt];
// ... fill points1d with data, then
double a = gpu.Average(points1d); // <- Alea.gpu.Average() accepts a 1d array
But as said, I want to pass on the second dimension to the function gpu.Average() whithout having to run for-loops three times to copy into 1d arrays:
double[,] points2d = new double[3,cnt];
// ... fill points2d with 'cnt' items of data and
// then pass it on
double x = gpu.Average(points2d[0,??]); // How to pass on 2nd dim?
double y = gpu.Average(points2d[1,??]);
double z = gpu.Average(points2d[2,??]);
Is this possible without having to copy the data into 1d arrays?
(BTW, calculating average is not a good example use of gpu parallel library, this is just a test case comparing execution times for different data types & structures).
// Rolf
No this is not possible in managed code without copying the contents of e.g. points2d[1,*] to a new single dimensional array.
In managed code every array has to know its length, so that every index access can be checked and ArrayIndexOutOfBounds exception thrown if the index is out of bounds. The length (integer value) is stored before the first element of the array, so that the runtime knows where to find it. Now with this I guess one can see why you cannot split array into several parts and treat those as new arrays. Note that the story is even more complicated for multidimensional arrays, which have to store the number of dimensions and the size of each dimension...
What you can do is to use jagged array:
double[][] points2d = new double[3][];
points2[0] = new double[cnt];
...
gpu.Average(points2d[0]);
Jagged arrays are faster than multidimensional arrays and are recommended to be used instead of multidimensional arrays even by MS.
Dear developers why i get error? (index was outside the bounds of the array)
Note that you create MagicList as an array of 450, but in the debugger, it says it's an array of 300. This is because the array you explicitly create is never actually used. It's immediately replaced by the array returned by GetAsBinary. That array is only 300 bytes long, and that's why your code fails. Your loop exit condition must take the actual array size into account, instead of assuming the size. The following code shows a way you could avoid the problem.
byte[] magicList = DBLite.dbMu.GetAsBinary("magicList");
DBLite.dbMu.Close();
for (int i = 0; i < magicList.Length/3; i++) {
I'm trying to find multiple ways to solve Project Euler's problem #13. I've already got it solved two different ways, but what I am trying to do this time is to have my solution read from a text file that contains all of the numbers, from there it converts it and adds the column numbers farthest to the right. I also want to solve this problem in a way such that if we were to add new numbers to our list, the list can contain any amount of rows or columns, so it's length is not predefined (non array? I'm not sure if a jagged array would apply properly here since it can't be predefined).
So far I've got:
static void Main(string[] args)
{
List<int> sum = new List<int>();
string bigIntFile = #"C:\Users\Justin\Desktop\BigNumbers.txt";
string result;
StreamReader streamReader = new StreamReader(bigIntFile);
while ((result = streamReader.ReadLine()) != null)
{
for (int i = 0; i < result.Length; i++)
{
int converted = Convert.ToInt32(result.Substring(i, 1));
sum.Add(converted);
}
}
}
which reads the file and converts each character from the string to a single int. I'm trying to think how I can store that int in a collection that is like 2D array, but the collection needs to be versatile and store any # of rows / columns. Any ideas on how to store these digits other than just a basic list? Is there maybe a way I can set up a list so it's like a 2D array that is not predefined? Thanks in advance!
UPDATE: Also I don't want to use "BigInteger". That'd be a little too easy to read the line, convert the string to a BigInt, store it in a BigInt list and then sum up all the integers from there.
There is no resizable 2D collection built into the .NET framework. I'd just go with the "jagged arrays" type of data structure, just with lists:
List<List<int>>
You can also vary this pattern by using an array for each row:
List<int[]>
If you want to read the file a little simpler, here is how:
List<int[]> numbers =
File.EnumerateLines(path)
.Select(lineStr => lineStr.Select(#char => #char - '0').ToArray())
.ToList();
Far less code. You can reuse a lot of built-in stuff to do basic data transformations. That gives you less code to write and to maintain. It is more extensible and it is less prone to bugs.
If you want to select a column from this structure, do it like this:
int colIndex = ...;
int[] column = numbers.Select(row => row[index]).ToArray();
You can encapsulate this line into a helper method to remove noise from your main addition algorithm.
Note, that the efficiency of all those patterns is far less than a 2D array, but in your case it is good enough.
In this case you can simply use an 2D array, since you actually do know in advance its dimensions: 100 x 50.
If for some reason you want to solve a more general problem, you may indeed use a List of Lists, List>.
having said that, I wonder: are you actually trying to sum up all the numbers? if so, I would suggest another approach: consider just which section part of the 50 digit numbers actually influences the first digits of their sum. Hint: you don't need the entire number.
My users pass me an array of some type, say int[] or string[]. I can easily query the types of the elements via GetElementType, and I can find out how long the array was when it was passed to me via GetRank, GetLength, etc.
The arrays are passed in a params list, so visualize code like this:
public void Resizer(params object[] objs)
{
foreach (object o in objs)
Array.Resize(ref o, 3);
}
What I would like to do is the converse of the Get methods that are available and that do work: I want to resize the array that was passed to me, setting the length to some other length (like 3 in this silly example).
I'm doing this because in my setting the array will contain data received from a set of cloud computing servers and we can't know how many will respond in advance, hence can't preallocate the array to have the right length. Ideally, in fact, my user passes in an array of length 0, and I pass back an array of length n, signifying that I got n replies from the servers that were queries.
I can't do this with Array.Resize(ref T, int) because I don't know T at compile time.
Is there a way to pull this off?
This should work:
static void Resize(ref Array array, int newSize) {
Type elementType = array.GetType().GetElementType();
Array newArray = Array.CreateInstance(elementType, newSize);
Array.Copy(array, newArray, Math.Min(array.Length, newArray.Length));
array = newArray;
}
Why not just create a new array of whichever type you need that is the size that you want? Then populate it from the array you want to resize, setting non existent values to some default.
In case anyone is curious, I ended up switching my code to use List
I agree with the comments that you should be using List(Of T), but if you want to copy your array into a new array of the same type, you could do something like the following.
// Your passed in array.
object[] objs = new object[5] {1,2,3,4,5};
// Create an array of the same type.
Array a = Array.CreateInstance(objs[0].GetType(), objs.Length+3);
// Copy in values.
objs.CopyTo(a,0);
I guess I'll just switch to using Lists, but this is a shame; the code will be quite a bit messier looking and since my users are basically at the level of first-semester ugrads, each little thing will make their lives less good. But I'm suspecting that you folks don't see a way to do this either. Oh well....
What is an efficient way to shrink a two dimensional array to a smaller size in C#?
For example:
var bigArray = new object[100, 100];
var smallArray = new object[10, 10];
bigArray[0, 0] = 1;
bigArray[0, 1] = 2;
...
bigArray[99, 99] = 100000;
startRowIndex = 0;
startColumnIndex = 0;
endRowIndex = 9;
endColumnIndex = 9;
smallArray = bigArray.SomeShirnkingMethod(startRowIndex, startColumnIndex, endRowIndex, endColumnIndex);
How will you write SomeShrinkingMethod() ?
Thanks!
EDIT: I'm simply trying to get the first 10 rows and columns of the bigArray into the smallArray but I'm not sure if a looping through the array is the most efficient method.
You've got to create a new array of the desired size (in your code, you've already done this) and copy the content. I'm not sure what the “shrinking” operation needs to do in your case. However, you cannot modify the dimensions of an existing array.
The function you proposed is defective because it can't know the dimensions of the target array. Either you pass it the dimensions and dimension the new array internally or you pass it the target array and simply copy the contents.
Edit:
In response to your edit: Yes, looping will be the reasonable way to do this and this is also reasonably fast. I'm not aware of a block-copying mechanism in .NET that can be applied to multidimensional arrays.
Depends on what you want your shrinking function to do. You've got to make a new array and do the copy based on whatever your criteria is. My assumption is that you've got a 2d array for a reason, right? The copy could either be trivia (find the next location that has a non-zero value and put it in the next available location in the target) or based on something else. Can you provide more info?
Yes the best method is almost certainly to loop over each cell, although it might be possible to copy a sequence of each 'row'. The method would need to know lower indices of the square to be copied from the source square, and the size (which might be implicit in the destination square definition).