Count number of non null matrix elements - c#

I have an array of arrays something like arr[26,20] with the alphabet in the first position of each array.
So laid out in matrix form it would something like.
ABCDEFGHIJKLMNOPQRSTUVWXYZ
//////////////////////////
//////////////////////////
//////////////////////////
//////////////////////////
The forward slashes representing null values.
I'm trying to get the number of non null elements in a single colomn.
So the code I could use on a normal array would be
int number = arr[0].Count(s => s != null);
However, how would I do this for a matrix like described?

You could use Enumerable.Range() to generate rows indexes:
int colIdx = 0; // column index to check
int num = Enumerable.Range(0,arr.GetLength(0)).Count(i => arr[i,colIdx] != null);
where GetLength(dim) gives the number of elements along dimension dim (0 - first dimension, 1 - second dimensions etc.).

you may simply use:
int columnIndex = 1;// column index to check
arr.Count(s => s[columnIndex] != null);

You can use
arr.Cast<YourArrayElementType>().Count(s => s != null);
The reason is that a multi-dimensional array is a non-generic IEnumerable, but unfortunately not IEnumerable<YourArrayElementType>.
Oops, this counts non-null elements in the entire matrix, not just one column/row. So use digEmAll's answer instead. Or why not use a good old for loop?

Related

Using one array to populate a corresponding second array in C#

I am taking a class in c# programming and cannot figure out how to do the following. I have spent hours researching and nobody else seems to have the same issues.
The question is:
Write a function named, evenOrOdd, that will accept three parameters. The first parameter is the integer array used in the above function. The second parameter is the string array from step 2 and the third parameter is an integer indicating the size of the two arrays. This function will perform the following tasks:
This function will loop through the first array, checking each value to see if it is even or odd.
For each item in the integer array, the function will then place the appropriate value, “even” or “odd”, in the corresponding position of the string array.
Hint: Using the modulus operator, (also called the modulo), to divide the number by 2 will result in either a remainder of 0 or 1. A remainder of 0 indicates an even number and a remainder of 1 indicates an odd number. The modulus operator for all of the languages in this class is %.
After calling both functions, print the maximum number determined by findMax as well as the array index position of the largest number. Next, the program will loop through the two arrays and print the integer from integer array followed by the corresponding “even” or “odd” value from the string array
I do not understand how to populate the second string array with "even" or "odd".
The two arrays should be something like this:
array1 [1,2,3,4,5,6,7,8,9,10]
then run through a loop to determine if the values are even or odd and then assign the values to the second array so it is something like this:
array2 [odd,even,odd,even,odd,even,odd,even,odd,even]
I am confused how I "link" these two arrays together so that it know index of array 1=index of array 2.
You don't have to "link" the arrays together. You can use a variable which contains the current index and use it for both arrays. Like this:
for (int i = 0; i < array1.Length; i++){
//array1[i]...
//array2[i] = ...
}
This way, you can check if the number at index i in array 1 is even or odd and then modify the index i of array 2 accordingly.
Instead of array1.Length, you can also use the third argument of the method.
It looks like a code challenge. I highly recommend you find your own way to understand and solve this kind of problem and the fundamental concepts behind it as well.
One way to code the EvenOrOdd method:
public void EvenOrOdd(int[] numbers,
string[] natures, int size)
{
for(int i=0; i < size; i++)
if(numbers[i] % 2 == 0)
natures[i] = "even";
else
natures[i] = "odd";
}
One wat to code FindMax Function:
public static (int MaxValue, int MaxIndex) FindMax(int[] numbers)
{
int major = int.MinValue;
int majorIndex = -1;
for(int i=0; i < numbers.Length; i++)
if(numbers[i] > major)
{
major = numbers[i];
majorIndex = i;
}
return (major, majorIndex);
}
Check it in dotnetFiddle

Finding string in the beginning of a larger string

I'm trying to find, in an array of strings, which one starts with a particular substring. One of the strings in the array is guaranteed to start with the particular substring.
I tried to use:
int index = Array.BinarySearch (lines, "^"+subString);
Where lines is the array of strings and I'm looking for the index of the array that starts with subString. However, I'm either using regex improperly or there's a much better way to go about this?
BinarySearch can be used only to find a complete string, so you cannot use it for a substring match. You also have to ensure that the array is ordered in the first place to use BinarySearch.
You can use Array.FindIndex:
int index = Array.FindIndex(lines, line => line.TrimStart().StartsWith(subString));
Do you need to find the index of the (first) occurence, or do you need to find the actual strings that match that criterium?
myString.StartsWith(myPrefix); //returns bool
That should do the trick. Or a little more verbose:
var matchedLines = lines.Where(line => line.StartsWith(substring)).ToList();
If you need the index of the first occurence, I'd address it as an array:
var firstOccurence = String.Empty;
var firstOccurenceIndex = -1;
for(int i = 0; i < lines.Length; i++)
{
if(lines[i].StartsWith(substring))
{
firstOccurence = lines[i];
firstOccurenceIndex = i;
break;
}
}
Note: you don't HAVE to use an array. It could just as well have been done with a foreach, manual counter incrementor and a break statement. I just prefer to work with arrays if I'm looking for an index.
Yet, another solution:
int index = lines.ToList().FindIndex(line => line.TrimStart().StartsWith(subString));

How to find an item in an array that sum of all values before that is a spcific value? (C++ and C#)

Assume that I have an array of integers with a specific size (say 1000)
I want to find the index of an item in this array, given the sum of all items in the array before this item (or including this item).
for example assume that I have the following array:
int[] values={1,2,3,1,3,6,4,8,2,11}
Input value is 6, then I need to return the index 2 (zero based indexing for 3 in above example) and when given 10, I should return the index 4.
What is the fastest way to do this? in C++ and c#?
If you need to do it only once, then the naive way is also the fastest way: walk the array, and keep the running total. Once you reach the target sum, return the current index.
If you need to run multiple queries for different sums, create an array and set up sums in it, like this:
var sums = new int[values.Length];
sums[0] = values[0];
for (int i = 1 ; i < sums.Length ; i++) {
sums[i] = sums[i-1] + values[i];
}
If all values are positive, you can run binary search on sums to get to the index in O(log(n)).
learn BST, it's will the fastest algo for your problem:
http://en.wikipedia.org/wiki/Binary_search_tree

adding two int array

I have to add two int[] array in which a mian int[] array is intially vacant. I want to add the elements of another array in the main array . In the Main array, there would be more addtion that would be added in the last postion of the main array.
I have an array as -
var planetNotInRange = new int[7] ;
if(planetSign.Contains(tempFrind))
{
var result = planetSign.Select((b, k) => b.Equals(tempFrind) ? k : -1)
.Where(k => k != -1).ToArray();
// Here I want to add this result Array in to the planetNotInRange array,
// when ever there is some value in the result array.
}
this is in loop will give a number of array of integers. Now I want to concat in PLanetInRange Array one after other.
It sounds like you shouldn't have an array to start with, if you want to add elements to it. Once an array has been created, its size is fixed.
Use a List<int> instead, and you can use
list.AddRange(array);
I'd usually advise using lists (and other collection types) over arrays anyway. Arrays are useful, obviously, but they're somewhat more primitive and low-level than other collections.

Difference between array.GetLength(0) and array.GetUpperBound(0)

What is the difference between these two methods and when would you use one instead of the other?
int[,] array = new int[4,3];
int length0 = array.GetLength(0);
int upperbound0 = array.GetUpperBound(0);
MSDN says that GetLength return the number of elements where as GetUpperBound determine the max index, but how could this be different since arrays are initialized with elements for each index?
Take a look at this (rarely used) method. From Docs:
public static Array CreateInstance(Type elementType, int[] lengths, int[] lowerBounds)
Creates a multidimensional Array of the specified Type and dimension lengths, with the specified lower bounds.
With it, you can create an array with indices from -5 ... +5. If you ever use this kind of array, then GetUpperBound() suddenly becomes a lot more useful than GetLength()-1. There also exists a GetLowerBound().
But the C# support for this kind of arrays is low, you cannot use []. You would only need those methods in combination with the Array.GetValue() and SetValue() methods.
Array.Length returns the length of the array (number of elements) you need
to subtract 1 from it to get the UpperBound.
Array.GetUpperBound(0) returns the upper bound of the array, you can use it
as is.
GetUpperBound returns the highest index in the array, the GetLength returns the number of elements of the array.
i.e. GetUpperBound = GetLength - 1
Generally, array.GetUpperBound(0) = array.Length - 1, but since we can create arrays that have a Nonzero lower bound, that is not always true.
I realise this is an old question but I think it's worth emphasising that GetUpperBound returns the upper boundary of the specified dimension. This is important for a multidimensional array as in that case the two functions are not equivalent.
// Given a simple two dimensional array
private static readonly int[,] USHolidays =
{
{ 1, 1 },
{ 7, 4 },
{ 12, 24 },
{ 12, 25 }
};
The Length property will output 8 as there are 8 elements in the array.
Console.WriteLine(USHolidays.Length);
However, the GetUpperBound() function will output 3 as the upper boundary of the first dimension is 3. In other words I can loop over array indexes 0, 1, 2 and 3.
Console.WriteLine(USHolidays.GetUpperBound(0));
for (var i = 0; i <= USHolidays.GetUpperBound(0); i++)
{
Console.WriteLine("{0}, {1}", USHolidays[i, 0], USHolidays[i, 1]);
}
if lower bound of your array is 0 then you can use either of them without any confusion but i would recommend array.length-1 as it is widely used. however, if the lower bound of your array is less than 0 then you should use array.GetUpperBound(0) because in this case array.length-1 != array.getUpperBound(0)

Categories