Filling a Two-Dimensional Array with 2 values - c#

First. I'm sorry if the question the question is badly formulated because I don't really understand the question myself.
Hello,
I'm currently helping a friend with his practice tasks about 2-Dimensional Arrays.
The following task is: Expand the array with the missing columns. Fill the column with two values each.
Now my question is how? Is it even possible to put 2 values in one?
For a better understanding, see this code:
static int[][] BSP = {
new int[] { 1, 2, 3, 4 },
new int[] { 1, 2, 3 } ,
new int[] { 1, 2, 3, 4, 5, 6 }
};
Now we should expand the array to the task I mentioned above. I understand the Task like this:
Instead of one value there should be 2.
Can you help me or did I misunderstood the question.

When you are going to expand (or shrink) try to use list List<T> instead of array T[]. We want to extend lines while keeping columns intact, so we can use List<T[]> - list of arrays:
static List<int[]> BSP = new List<int[]>() {
new int[] { 1, 2, 3, 4 },
new int[] { 1, 2, 3 },
new int[] { 1, 2, 3, 4, 5, 6 },
};
then you can just Add to extend (and RemoveAt to shrink):
// 4th row with 2 values: 12 and 21
BSP.Add(new int[] { 12, 21 });

Related

How to get the number of elements before the second last element in an array C#

Consider the int array below of n elements.
1, 3, 4, 5, 7. In this example the second last item is 5. I want to get the number of elements in this array before the second last value. There are 3 elements before the second last element. I will store the result in an int variable to use later. We obviously take into account that the array will have more than two element all the time.
This array will have different size everytime.
How can I achieve this in the most simplistic way?
The answer will always be n-2, so a very quick solution is to use .Length property and to subtract 2.
You can use Range from C# 8:
int[] arr = new int[]{1, 3, 4, 5, 7};
int[] newArr = arr.Length>=2 ? arr[..^2] : new int[0];
This will return all elements except the last 2, or an empty array if the lenght is less than 2. If it is guaranteed that the array will always have more than 2 elements, then you can simplify:
int[] newArr = arr[..^2];
If you are only interested about the quantity of the numbers then .Length-2 is the best way as it was stated by others as well.
If you are interested about the items as well without using C# 8 features then you can use ArraySegment (1).
It is really powerful, like you can reverse the items without affecting the underlying array.
int[] arr = new int[] { 1, 3, 4, 5, 7 };
var segment = new ArraySegment<int>(arr, 0, arr.Length - 2);
var reversedSegment = segment.Reverse(); //ReverseIterator { 4, 3, 1 }
//arr >> int[5] { 1, 3, 4, 6, 7 }
Please bear in mind that the same is not true for Span (2).
var segment = new Span<int>(arr, 0, arr.Length - 2);
segment.Reverse();
//arr >> int[5] {4, 3, 1, 6, 7 }
There is a ReadOnlySpan, which does not allow to perform such operation as Reverse.
If you would need that then you have to manually iterate through that in a reversed order.

How to use elements which are not in the second List<>()

I have two lists like this List... In first I have some elements and I want to use a element in the second list which is not one of the first using LINQ. For example:
List one has: 1, 2
List two has: 1, 2, 3, 4, 5, 6
So my output should be: 3, 4, 5, 6.
You can use Except to subtract the first list from the second one.
var list3 = list2.Except(list1).ToList();
Use the Except method:
List<int> a = new List<int> { 1, 2 };
List<int> b = new List<int> { 1, 2, 3, 4, 5 };
var result = b.Except(a).ToList();
Yes you could do that with a foreach loop, no you shouldn't do it this way. What yolu should do is read about IEquatable and override the Equals method. This will let you control the property which excludes the elements.

Why can't I use array initialisation syntax separate from array declaration?

I can do this with an integer:
int a;
a = 5;
But I can't do this with an integer array:
int[] a;
a = { 1, 2, 3, 4, 5 };
Why not?
To clarify, I am not looking for the correct syntax (I can look that up); I know that this works:
int[] a = { 1, 2, 3, 4, 5 };
Which would be the equivalent of:
int a = 5;
What I am trying to understand is, why does the code fail for arrays? What is the reason behind the code failing to be recognised as valid?
The reason there is a difference is that the folks at Microsoft decided to lighten the syntax when declaring and initializing the array in the same statement, but did not add the required syntax to allow you to assign a new array to it later.
This is why this works:
int[] a = { 1, 2, 3, 4, 5 };
but this does not:
int[] a;
a = { 1, 2, 3, 4, 5 };
Could they have added the syntax to allow this? Sure, but they didn't. Most likely they felt that this use-case is so seldom used that it didn't warrant prioritizing over other features. All new features start with minus 100 points and this probably just didn't rank high enough on the priority list.
Note that { 1, 2, 3, 4, 5 } by itself has no meaning; it can only appear in two places:
As part of an array variable declaration:
int[] a = { 1, 2, 3, 4, 5 };
As part of an array creation expression:
new int[] { 1, 2, 3, 4, 5 }
The number 5, on the other hand, has a meaning everywhere it appears in C#, which is why this works:
int a;
a = 5;
So this is just special syntax the designers of C# decided to support, nothing more.
This syntax is documented in the C# specification, section 12.6 Array Initializers.
The reason your array example doesn't work is because of the difference between value and reference types. An int is a value type. It is a single location in memory whose value can be changed.
Your integer array is a reference type. It is not equivalent to a constant number of bytes in memory. Therefore, it is a pointer to the bytes where that data is stored.
In this first line, you are assigning null to a.
int[] a;
In the next line, if you want to change the value of the array, you need to assign it to a new array.
a = new[] {1, 2, 3, 4, 5};
That is why you need the new[] before the list of values within the array if you strongly type your declaration.
int[] a = {1, 2, 3, 4, 5}; // This will work.
var a = {1, 2, 3, 4, 5}; // This will not.
However, as many of the other answers have said, if you declare it in a single line, then you do not need the new[]. If you separate the declaration and initialization, then you are required to use new[].
{} syntax is available for array initialization, not to be used after declaration.
To initialize an array you should try like this:
int[] a = { 1, 2, 3, 4, 5 };
Other ways to Initializing a Single-dimensional array:
int[] a = new int[] { 1, 2, 3, 4, 5 };
int[] a = new int[5] { 1, 2, 3, 4, 5 };
Have a look at this: different ways to initialize different kinds of arrays

Why are arrays only allowed in certain places?

As I understand it, C# has a syntax for writing arrays as such: { 1, 2, 3 }. Why is this invalid:
x = { 1, 2, 3 }.GetLength(0);
while this is valid?
int[] numbers = { 1, 2, 3 };
x = numbers.GetLength(0);
Isn't the datatype of the expression { 1, 2, 3 } the same as numbers?
Arrays are allowed anywhere - but you can only use that particular syntax (which is called an array initializer for creating them as part of a variable declaration - or as part of a larger expression called an array creation expression.
You can still create them though:
x = new int[] { 1, 2, 3 }.GetLength(0);
So within that, new int[] { 1, 2, 3 } is the array creation expression, and the { 1, 2, 3 } part is the array initializer.
Array creation expressions are described in section 7.6.10.4 of the C# 5 spec, and array initializers are described in section 12.6.
The syntax you refer to is an object collection initializer. It is useful when initializing an instance of different types. It does not, in itself, create an instance of a given type.
For instance, you can use it to declare arrays:
int[] nums = new int[] { 1, 2, 3 };
Lists:
List<int> nums = new List<int> { 1, 2, 3 };
Dictionary:
Dictionary<string, int> pairs = { { "One", 1 }, { "Two", 2 }, { "Three", 3 } };
You can still inline things to achieve your initial intention with a little more code:
new[] { 1, 2, 3 }.GetLength(0);
x = new[] { 1, 2, 3 }.GetLength(0); will get you what you want since {1, 2, 3} isn't on its own an array, but rather an array initializer. And GetLength() works with the former but not the latter.

C# massive insertion into data structures

In C#, you can do the following:
List<int> registers = new List<int> { 1, 2, 3, 4 };
This will produce a list with 1, 2, 3, and 4 in the list. Suppose that I am given a list from some function and I want to insert a bunch of numbers like the following:
List<int> register = somewhere();
register.Add(1);
register.Add(2);
register.Add(3);
register.Add(4);
Is there a cleaner way of doing this like the snippet above?
Assuming the new items are in some kind of enumerable form already, the AddRange() method allows you to add them all in one go:
var toBeAdded = new int[] { 1,2,3,4 };
register.AddRange(toBeAdded);
You mean something like this?
List<int> register = somewhere();
register.AddRange(new List<int> { 1, 2, 3, 4 });
I think the cleanest you can get is this:
List<int> register = somewhere();
register.AddRange(new[] { 1, 2, 3, 4 });
However, it may not always be possible to implicitly type the array.

Categories

Resources