This is just a quick question in C#.
I have a scenario where I am working with several devices that all have slightly different data to work with.
When I work out which device I am using, I want to set up a common array to use throughout the code, say arrayCommon.
So I want to move the info from device1 to the common array.
Do I have to do this in a loop for each occurance in the array or can u move the whole array into the common array, as you could in Cobol all those years ago ?
Thanks, George.
I think you are looking for that : Array.Copy
Just a note, if you are needing it in a performance critical section of code, rather use:
Buffer.BlockCopy()
Link here.
Array array = new char["String".Length];
"String".ToCharArray().CopyTo(array, 0);
Related
In C# I'm storing values in an array.
So to create this array I'm using this code, 'int[] values = new int[10];'
But, what if I need more than 10 values, or in the case I never know how many values I will have. Could be 1, 10 or 100.
I understand the idea that I need to let the compiler know how big the array should be so it can allocate memory space for it.
Is there a way to work around that?
You could just use a List and let it do all the heavy lifting for you:
List<int> values = new List<int>();
Arrays must have defined length. If you want dynamic size, consider using List class.
Please take a look at and research the concept of "Immutable objects"
An array has a fixed size, If you need an array with a dynamic size it is best to either create extension methods or a handler that does the work for you.
The work to be done is to get the array, create a new array with the new size based on whether you want to add or remove something, and to populate the new array with the data from the previous array. This will create a new object instead of modifying the previous object and will make sure you don't push items to a full array, or have an array with a size larger than the items that fit in it.
Ofcourse the List class would work as well and would probably solve your problem.
EDIT: I now realized the question was not appropriate for stack but I've gotten a lot of helpful advice anyway. Thanks everyone!
I have a 2d array and I want to group together neighbors of the same value. Using C# (working with unity).
Let's say I have this:
int[,] array {
0,0,0,0,0,0,1,0,0,0,
0,1,1,0,0,0,1,0,0,0,
0,1,0,0,0,0,0,0,0,0,
0,0,0,0,0,0,1,1,1,0,
0,0,0,0,0,0,1,1,1,0
}
There are three "clusters" of 1:s. I want to add them to a dictionary with some variable for identification. So maybe first add the neighboring values to a list, add that list to a dictionary, clear the list and move onto the next cluster.
The columns and rows would be of equal length in the real thing.
I would also want the sorting method to accept arrays of various sizes so no hardcoded values. I parse the array from an XML document.
I've tried looking into Array.Sort but the resources I have found have been exclusively about sorting values in as/descending order. Just pointing me in the right direction, some some relevant web resources would be greatly appreciated!
I'm not going to give you the answer in full code since 1. you shouldn't be asking for it here and 2. you can definitely work it out yourself.
This is a good opportunity for you to whip out your pen and paper and figure out the algorithm. Lets say we want something similar to your task: just grouping the clusters of ones. The pseudocode might look like this.
Create a list of clusters
For each element in the grid, check if its a one.
If it is a one, check if it has a neighbor that is part of a cluster.
If so, add it to that cluster, else create a new cluster an add it.
If would then run through this on paper with a small example.
Once you have your desired algorithm, putting it into a dictionary and sorting it should be trivial.
How can I retrieve the highest number in an array recursively in C#?
Right now you're probably thinking that we're mean for not giving you the answer -- and I admit that I have the answer written down and part of me wants to give it to you, even.
Programming is all about finding the solutions to problems yourself. When you're hired as a programmer, you may have other people to lean on, but they've all got their own problems, and you'll need to be able to pull your own weight.
Recursion (in an oversimplifed answer) means to call the same operation over and over until the result is produced. That means you need in every recursive operation, you need to know (at least) two things:
What you're looking for
What you've found so far
The 'What you're looking for' is the termination condition. Once you find that, all work can stop and you can go home.
The 'what you've found so far' is how you know what've you've checked so you don't retread old ground.
So what do you need to know in order to find the highest value in an array recursively?
The contents of the Array.
The highest number you've found so far.
Have you already looked at this part of the Array? (Why look through it again?)
That would produce a method signature that looks like:
public int GetHighestNumber(int[] array, int highestNumberFound, int lastIndexChecked);
Once you're inside the array, you've got to do the following:
Iterate through the array
Stop when you find a value that is higher than the highestNumberFound
Call GetHighestNumber again with the new highestNumberFound and lastIndexChecked updated.
When there are no more 'higher' numbers, then return the highest number found.
I realize it sounds trite, but learning this stuff on your own will make you a better programmer.
If you want to be a professional programmer, you have got to learn this stuff on your own.
If you don't want to be a professional programmer, then drop the course and do something you love.
Here's just a hint (taking int[] as an example):
public int FindMax(int[] array, int indexSoFar, int maxSoFar)
Think about:
The start conditions
The termination conditions
How you move through the array recursively
Reason of EDIT: Didnt want to spoil the answere.
Greetings.
I have a program that needs to store data values and periodically get the last 'x' data values.
It initially thought a stack is the way to go but I need to be able to see more than just the top value - something like a PeekRange method where I can peek the last 'x' number of values.
At the moment I'm just using a list and get the last, say, 20 values like this:
var last20 = myList.Skip(myList.Count - 20).ToList();
The list grows all the time the program runs, but I only ever want the last 20 values. Could someone give some advice on a better data structure?
I'd probably be using a ring buffer. It's not hard to implement one on your own, AFAIK there's no implementation provided by the Framework..
Well since you mentioned the stack, I guess you only need modifications at the end of the list?
In that case the list is actually a nice solution (cache efficient and with fast insertion/removal at the end). However your way of extracting the last few items is somewhat inefficient, because IEnumerable<T> won't expose the random access provided by the List. So the Skip()-Implementation has to scan the whole List until it reaches the end (or do a runtime type check first to detect that the container implements IList<T>). It is more efficient, to either access the items directly by index, or (if you need a second array) to use List<T>.CopyTo().
If you need fast removal/insertion at the beginning, you may want to consider a ring buffer or (doubly) linked list (see LinkedList<T>). The linked list will be less cache-efficient, but it is easy and efficient to navigate and alter from both directions. The ring buffer is a bit harder to implement, but will be more cache- and space-efficient. So its probably better if only small value types or reference types are stored. Especially when the buffers size is fixed.
You could just removeat(0) after each add (if the list is longer than 20), so the list will never be longer than 20 items.
You said stack, but you also said you only ever want the last 20 items. I don't think these two requirements really go together.
I would say that Johannes is right about a ring buffer. It is VERY easy to implement this yourself in .NET; just use a Queue<T> and once you reach your capacity (20) start dequeuing (popping) on every enqueue (push).
If you want your PeekRange to enumerate from the most recent to least recent, you can defineGetEnumerator to do somehing likereturn _queue.Reverse().GetEnumerator();
Woops, .Take() wont do it.
Here's an implementation of .TakeLast()
http://www.codeproject.com/Articles/119666/LINQ-Introducing-The-Take-Last-Operators.aspx
In my program (a program that assists with pathfinding), i need to store a list that contains entries consisting of a start node and an end node. A dictionary won't work as i cannot guarantee that the "key" (a node of course) will be unique. What is the best way to store this manner of data?
Edit: i use C# and .Net 3.5.
You might be better off simply using an array of structs. Or a vector of structs. This allows for non-unique nodes in your list. Vectors are a standard template in C++, but if C# doesn't support it, then an array should work fine.
Would it be possible for you to use a List of KeyValuePair objects? Like this?
List<KeyValuePair<ObjectA, ObjectB>> list = new List<KeyValuePair<ObjectA, ObjectB>>();
I don't have VS in front of me right now, so I'm not sure if I have the syntax 100% right, but hopefully this helps.
If your language of choice supports sets, a set of (start, end) tuples is what you might be looking for.