Initializing size of 2D array in runtime using C# - c#

I need to create a 2D array where size of column is fixed as 6 but size of row may vary . How to give dynamic row size in 2D array ?
Below is the code I tried but no luck.
int n;
string num = console.ReadLine();
Int32.TryParse(num,out n);
int[,] ar = new int[n,6] ;

There's nothing wrong with the way you're constructing the mulitidimentional array. The following code is valid so I suspect your error is somewhere else:
int n = 9;
int[,] ar = new int[n,6];
I'm guessing your input is not coming through correctly so add some error checks to figure out what went wrong. First, Console.ReadLine() has to be capitalized or it wont compile. Next, make sure TryParse is actually functioning properly (it returns a bool indicating success or failure:
int n;
string num = Console.ReadLine();
if (num == null) {
// ERROR, No lines available to read.
}
if (!Int32.TryParse(num,out n)) {
// ERROR, Could not parse num.
}
int[,] ar = new int[n,6];
If issues persist, people generally appreciate more descriptive explanations than "I tried but no luck." Make sure to inform people viewing your question that it was a compilation error or a runtime error and be as specific as you can.

I would use a Dictionary as so.
Dictionary<int,List<int>> numbers = new Dictionary<int,List<int>>();
And you could add an item like this:
numbers.Add(1,new List<int>(){1,2,3,4,5,6});
And to add numbers to a particular row.
numbers[1].Add(7);
And to access a number in a specific row and column.
numbers[1][2] = 34;

Related

C# - leetcode 189, array hasn't changed

The problem is as follows:
Given an array, rotate the array to the right by k steps, where k is non-negative.
Example 1:
Input: nums = [1,2,3,4,5,6,7], k = 3
Output: [5,6,7,1,2,3,4]
Explanation:
rotate 1 steps to the right: [7,1,2,3,4,5,6]
rotate 2 steps to the right: [6,7,1,2,3,4,5]
rotate 3 steps to the right: [5,6,7,1,2,3,4]
My code:
public class Solution
{
public void Rotate(int[] nums, int k)
{
List<int> list = nums.ToList();
for (int i = 0; i < k; i ++)
{
int first = nums[0];
list.RemoveAt(0);
list.Add(first);
}
nums = list.ToArray();
}
}
And I got a wrong answer as follows:
Wrong Answer
Runtime: 156 ms
Your input
[1,2,3,4,5,6,7]
3
Output
[1,2,3,4,5,6,7]
Expected
[5,6,7,1,2,3,4]
My question:
I assign the adjusted list to nums but why it hasn't changed?
Objects in C# are reference types, but they're passed by value.
Imagine if I gave you a box. You're welcome to do whatever you want with the contents, and when I return to collect the box I keep whatever you've put in it.
However, if you decide to replace my box with a new box, and you put things in the new box, then I don't get those things when I come back to collect the original box I gave to you.
When you call
nums = list.ToArray();
you are discarding the nums that was passed to you and you are replacing it with something else. That replaced value does not leave the function. The leetcode script that called your function checks the original nums object (box) and finds its contents unchanged.
Try doing the following instead of the assignment expression I mentioned above:
for(int i=0; i<list.Count(); i++)
{
nums[i] = list[i];
}
Here you're modifying the contents of nums without changing the object.
I assign the adjusted list to nums but why it hasn't changed?
nums is a regular parameter, and as such is passed by value. Any changes you make to its handle (like assigning to it) won't be visible to the array passed in from the outside.
So either replace the items in the array given to you one by one, or pass the array parameter by reference (ref int[] nums).
As an aside, your solution is incredibly bad. You took what should have been a time-linear and memory-constant solution and made a time-quadratic monstrosity that allocates two entire needless arrays.

Trying to delete an entry from a structure array in C#. Getting conflicting information?

I have been researching this topic and got conflicting answers. Any help is appreciated.
For an assignment, I am instructed to create a structure of arrays. I am trying to delete an entry in one case, and change in another. This is supposed to be by one of the fields and not by index number.
var countOfEmployees = 0;
var employees = new EmployeeData[100];
Console.Write("Please enter employee you want to delete:");
string deleteEmployee = Console.ReadLine();
bool deleted = false;
for (int x = 0; x < countOfemployees; x++)
{
if (items[x].ItemNumber == deleteItemNumber)
{
deleted = true;
}
if (true)
{
//code goes here
}
Any help is appreciated!
In an array, you might be able to delete the value from the place holder, but you will not be able to remove the actual item without some footwork.
Basically, what you can do is: Find the value you've searched for, and replace it with a null and treat it orrespondingly in every other function.
Option 2 would be to remove the item and then use a function that would "shift" all the values with a higher index upwards.
Option 3 is to use the advanced functions C#/.NET has to offer with collections, create a List, remove the item and cast back to an array.
var employees = new EmployeeData[100];
var list = employees.ToList();
int index=-1;
//search through in a loop (won't write it here)...
index = x; //get the index in your list then break the loop
break; //end the loop
list.RemoveAt(index); //delete the spot outside the loop
employees=list.ToArray();
Of course there's checks needed if the search didn't find anything, but i think you can manage to implement that without my help.
And this is of course me assuming that there's only ONE entry with that kind of value in the array.
If it's not, you're gonna have to loop through and erase them until the search doesn't find anything anymore.

Index Out of Range on accessing List<List<T>> with For loops

Hobbyist start C# coder here. Think I am missing something basic here. I am trying to create a new List by parsing through a List> using two for loops. I am getting Index Out of Range although from what I can tell in debugging, there is data in the Deal object in the [index][index] location being accessed.
List<List<Deal>> Deals = await Database.LoadRecordsAsync(form, depts);
for (int dept = 0; dept <= Deals.Count; dept++)
{
List<Deal> batch = new List<Deal>();
for (int deal = Deals[dept].Count; deal >= 0; deal--)
{
batch.Add(Deals[dept][deal]); // Error here
}
}
Deals in debugging has indexes as expected with data as expected. Am I initializing something incorrectly?
The problem is the following line:
deal = Deals[dept].Count
This line should change as below:
deal = Deals[dept].Count - 1
as well the upper bound of the first for. The following
dept <= Deals.Count
should change as below:
dept < Deals.Count
Generally speaking, if you declare an array of n items the last item of the array can be accessed by using the index n-1.
That being said if you declare deal as Deals[dept].Count and later on you attempt to read this:
Deals[dept][deal]
you are out of the range of the array you have defined.

Exception from HRESULT: 0x800A03EC - Writing array to range in Excel Add-In

I have the following code in an Excel Add-In in C#:
long lngArrayLength = 14;
long lngArrayLength2 = array2.Length;
Excel.Range rngValues1 = (Excel.Range)wsNew.Cells[2, 1];
Excel.Range rngValues2 = (Excel.Range)wsNew.Cells[lngArrayLength2 + 1, lngArrayLength];
Excel.Range rngValues = wsNew.get_Range(rngValues1, rngValues2);
rngValues.Value = array2;
For reference, array2 has ten elements, each of which has 14 sub-elements. Example:
array2 = { (0, "a0", "b0", "c0"... "n0"), ... {9, "a9", "b9", "c9"... "n9) }
rngValues above is sized as {[1..10,1..14]}
Every time I try to run, I get the following error:
Exception from HRESULT: 0x800A03EC
I have ruled out:
1) File format, saving Book1 as .xlsx does not help
2) Reaching the column or row limit, does the same thing with thousands of elements or 10 of them
3) [0] vs [1] - indexed arrays and/or ranges, doesn't seem to matter/help
I am still having trouble debugging this... Is it possible this has something to do with the dimensions of the array vs the range? How would I determine if that's the case or not?
UPDATE 1:
I created a loop that populates an array with data:
for (i = 1; i <= lngRows; i++)
{
for (j = 1; j <= lngCols; j++)
{
strTest[i-1, j-1] = "test (" + i.ToString() + "," + j.ToString() + ")";
}
}
...and this works fine.
It now occurs to me that may of the elements in the array contain NULL values.
I'm thinking this may be the problem... Is it?
UPDATE 2:
Okay, so I now wrote a small routine to convert any NULLs to 0 (b/c the data type is decimal? (nullable decimal) and I guess I really need decimal instead:
public decimal replaceNullDec(decimal? decInput)
{
if (decInput != null)
{
decimal rtn = (decimal)decInput;
return rtn;
}
else
{
decimal rtn = 0;
return rtn;
}
}
So, now I have confirmed that all the NULLs are being replaced, but I'M STILL GETTING THE ERROR when writing the array to a range...
UPDATE 3:
Okay, so then I thought that maybe it's a data type issue, so I rewrote the code to convert all the elements in the array to strings instead before writing to the sheet. I now get data, but instead of the actual values, I get text telling me the original TYPE (which in this case is a custom class called Response).
The interesting thing I noticed is that I'm getting 10 COLUMNS of text, and 4 COLUMNS of #N/A.
This makes me think that maybe I need to transpose the array?
Driving me crazy, but still trying.
Any help would be GREAT!
UPDATE 4:
Okay, I believe I'm getting closer. In digging into how to transpose a 2d array in C#, I was getting some errors that lead me to believe I DON'T actually have a 2d array, but instead an "array of arrays" (which is what I thought a 2d array was, honestly) and it's probably the conversion of my List to Array using the ToArray() method that's an issue.
Here's that code:
object[] array2 = listAllData.ToArray();
So the next question becomes "how to convert a list to a 2d array?"
ANSWER:
The issue came down to the fact that I was NOT writing a 2D array to the range, but instead I was building an array of Response objects and trying to write that to a range.
More details on the solution are found in this related post:
How to Convert 2D List to 2D Array in C#

C# List of List of Lines Index was out of range

I have a problem very much like the one mentioned here:
ArgumentOutOfRangeException Was Unhandled
I believe that contiguousLines[columnNum].Add(...) is what is causing the error because I am indexing with columnNum
List<line> freeLines = new List<line>();
List<List<line>> contiguousLines = new List<List<line>>();
while(freeLines.Count > 0)
{
int columnNum = contiguousLines.Count;
contiguousLines[columnNum].Add(freeLines[0]);
freeLines.RemoveAt(0);
for(int i = 0; i < freeLines.Count; i++)
{
int last = contiguousLines[columnNum].Count;
if(contiguousLines[columnNum][last].upDown(freeLines[i]))
{
contiguousLines[columnNum].Add(freeLines[i]);
freeLines.RemoveAt(i);
i = -1;
}
}
// Further code that pulls individual elements from freeLines and
// is intended to place them into contiguousLines.
}
The function upDown just compares Start and End points of the lines to see if one (freeLines[i]) is the downstream of the other (contiguousLines[columnNum]).
System.ArgumentOutOfRangeException was unhandled
Message=Index was out of range. Must be non-negative and less than the size of
the collection. Parameter name: index
What is the proper syntax when dealing with a List of Lists?
(Note: I don't often program in C# and this project is something I wrote and have working in C++ only to be later informed C# would play better with the rest of the utilities for my job. In C++ I used vectors for my containers, but apparently copy/pasting the logic won't work as there is some nuance of Lists that I am unaware of.)
I suppose it is also possible to just make a ContiguousLine class that holds a list of Lines, then add to a List<ContiguousLine> from freeLines. Even if that were to be a better solution, I am still curious why I can not address a List of Lists of Lines in this way.
int last = contiguousLines[columnNum].Count;
As lists are 0-indexed, you're 1 over.
you need to add a List first before access the column
contiguousLines.Add(new List<line>());
contiguousLines[columnNum].Add(freeLines[0]);

Categories

Resources