I’ve got a 2D array of int’s in a console c# code (7X3 ‘cells’). The moment I create it, it is initialized with zeros.
I’ve got to change the value of only five ‘cells’ into 1, without changing the value of other ‘cells’. I know it is a basic thing, but, as an absolute rookie in C#, I can’t get it to work, no matter what cell I use. Can you help me?
Thanks in advance.
(Note: As I am a frequent user/contributer, I know it looks like a classic “Do my homework” question and I apologize, but as I’m really stuck on this weenie part (and the rest of my project is OK), I’d appreciate the help).
Here are two ways of solving this issue, the first one; called
BruteForceRandomImplementationis easy to implement and understand but quite slow once you attempt to mark a very large number of locations with 1s due to it’s brute-force like usage ofRandomtill it fills enough locations.With the following helper method to keep our
locationsToFindrange sane:My second implementation called
ShuffleImplementationis a lot faster when you are marking large numbers of unique locations. It creates a one-dimensional array, fills this with enough 1s to satisify your needs then shuffles this array using the Fisher-Yates shuffle to finally proceed to expand this one-dimensional array into a two-dimensional one:Usage:
Or:
Depending on which one you want to use. For a good example of the performance difference between the two, try:
On my laptop BruteForceRandomImplementation took 1205ms and ShuffleImplementation took 67ms or nearly 18x faster.