Determine if array contains all zeroes - c#

I create the following array like this:
array<UInt16>^ temp = gcnew array<UInt16>(1000);
How do I determine if this entire array has been filled with zero or not.
I think I may be able to use TrueForAll(T) but I'm not sure.

var allElementsAreZero = temp.All(o => o == 0);
Simple as that.
It'll return when it finds one that doesn't satisfy the condition, so may not necessarily iterate through your whole collection:
"The enumeration of source is stopped as soon as the result can be determined."
https://msdn.microsoft.com/en-us/library/bb548541(v=vs.110).aspx

This should work properly (here I used LINQ):
IEnumerable<int> values = new List<int>(); // Or use any array type instead of List.
... Add your values here ...
var allAreZero = !values.Any(v => v != 0);
P.S. the array class inherits IEnumerable.
And here is a solution with foreach:
var isAllZero = true;
foreach (var value in values)
{
if (value != 0)
{
isAllZero = false;
break;
}
}
UPDATE
The really difference between TrueForAll, and my LINQ code is: LINQ code uses the fluent (or maybe also query) syntax, where TrueForAll is just a normal function where you send the array as a parameter.

initialize a counter from 0 then use for loop to interate through the array and increment the counter whenever it finds 0, and at the end compare the counter with size of array if its equal, it has all zeros

Reading the C++/CLI specification, it has been filled with
0s because you created it with a "new-expression" and the default value of the element type is 0.
24.2 CLI array creation
CLI array instances are created by new-expressions containing gcnew (§15.4.6) or …
Elements of CLI arrays created by new-expressions are always initialized to their default value.

Related

Search for an existing object in a list

This is my first question here so I hope I'm doing right.
I have to create a List of array of integer:
List<int[]> finalList = new List<int[]>();
in order to store all the combinations of K elements with N numbers.
For example:
N=5, K=2 => {1,2},{1,3},{1,4},...
Everything is all right but I want to avoid the repetitions of the same combination in the list({1,2} and {2,1} for example). So before adding the tmpArray (where I temporally store the new combination) in the list, I want to check if it's already stored.
Here it's what I'm doing:
create the tmpArray with the next combination (OK)
sort tmpArray (OK)
check if the List already contains tmpArray with the following code:
if (!finalList.Contains(tmpArray))
finalList.Add(tmpArray);
but it doesn't work. Can anyone help me with this issue?
Array is a reference type - your Contains query will not do what you want (compare all members in order).
You may use something like this:
if (!finalList.Any(x => x.SequenceEqual(tmpArray))
{
finalList.Add(tmpArray);
}
(Make sure you add a using System.Linq to the top of your file)
I suggest you learn more about value vs. reference types, Linq and C# data structure fundamentals. While above query should work it will be slow - O(n*m) where n = number of arrays in finalList and m length of each array.
For larger arrays some precomputing (e.g. a hashcode for each of the arrays) that allows you a faster comparison might be beneficial.
If I remember correctly, contains will either check the value for value data types or it will check the address for object types. An array is an object type, so the contains is only checking if the address in memory is stored in your list. You'll have to check each item in this list and perform some type of algorithm to check that the values of the array are in the list.
Linq, Lambda, or brute force checking comes to mind.
BrokenGlass gives a good suggestion with Linq and Lambda.
Brute Force:
bool itemExists = true;
foreach (int[] ints in finalList)
{
if (ints.Length != tmpArray.Length)
{
itemExists = false;
break;
}
else
{
// Compare each element
for (int i = 0; i < tmpArray.Length; i++)
{
if (ints[i] != tmpArray[i])
{
itemExists = false;
break;
}
}
// Have to check to break from the foreach loop
if (itemExists == false)
{
break;
}
}
}
if (itemExists == false)
{
finalList.add(tmpArray);
}

Deleting a specific item of an array [duplicate]

This question already has answers here:
Remove element of a regular array
(15 answers)
Closed 9 years ago.
string[] columns
I want to delete the item on an index specified by a variable of type int.
How do I do this ?
I tried
columns.RemoveAt(MY_INT_HERE);
But apparently this does not works.
Array is immutable class, you can't change it, all you can do is to re-create it:
List<String> list = columns.ToList(); // <- to List which is mutable
list.RemoveAt(MY_INT_HERE); // <- remove
string[] columns = list.ToArray(); // <- back to array
May be the best solution is to redesign your code: change immutable array into List<String>:
List<String> columns = ...
columns.RemoveAt(MY_INT_HERE);
If you don't want to use linq you can use this function :
public string[] RemoveAt(string[] stringArray, int index)
{
if (index < 0 || index >= stringArray.Length)
return stringArray;
var newArray = new string[stringArray.Length - 1];
int j = 0;
for (int i = 0; i < stringArray.Length; i++)
{
if(i == index)continue;
newArray[j] = stringArray[i];
j++;
}
return newArray;
}
You use it like that : columns = RemoveAt(columns, MY_INT_HERE)
You can also make it to an extension method.
You cannot delete items in an array, because the length of a C# array is fixed at the time when it is created, and cannot be changed after that.
You can null out the corresponding element to get rid of the string, or use LINQ to produce a new array, like this:
columns = columns.Take(MY_INT_HERE-1).Concat(columns.Skip(MY_INT_HERE)).ToArray();
You need to add using System.Linq at the top of your C# file in order for this to compile.
However, using a List<string> would be a better solution:
List<string> columns;
columns.RemoveAt(MY_INT_HERE);
Try one of the following (depending on what you need):
columns[MY_INT_HERE] = null;
columns[MY_INT_HERE] = string.Empty;
...otherwise you'll just have to create a new array which has a length of 1 less than your current array, and copy the values over.
If you want something more flexible, you might use a something like a List<string>, where you can use RemoveAt()
Arrays are faster for the computer to work with but slower for a programmer. You will have to find that value with a loop or some other means, then set that position to null. You will end up with an empty space in the array. You could reallocate the array etc etc...
What is easier to use for relatively small amounts of data is a List. You can do myList.RemoveAt(100); and it will work nicely.
You can not delete it.You can recreate the array or I advice you to use List<string> for the same.
List<string> columns = new List<string>();
columns.RemoveAt(1);
It will remove the 2nd element from your List<String> columns

Cannot implicitily convert type `double[]` to `System.Collections.Generic.List<double>`

I am getting the following error message with the code below. I thought the data type List<double> was the same as double[] but that C# required it to be instantiated using the first syntax for the variable to work as an object. What am I doing wrong or is my thinking wrong?
Cannot implicitily convert type `double[]` to `System.Collections.Generic.List<double>`
Code:
private void RunScript(List<Curve> crv, double nb, ref object DivPts)
{
List<double> nbtemp = new List<double>();
List<double> Divpt = new List<double>();
for(int i = 0; i < crv.Count;i = i + 2)
{
nbtemp = crv[i].DivideByLength(nb, true);
}
Divpt = nbtemp;
No, a list is not an array, even though the concepts are somewhat similar. The List<T> class in C# is actually implemented with a behind-the-scenes array.
If you want to set a List from an array, you can use something like this:
nbtemp = new List<double>(crv[i].DivideByLength(nb, true));
that will create a new List, and initialize it with the array. You can also use the AddRange method of the List, if you would like to append an array to an existing list, like this:
nbtemp.AddRange(crv[i].DivideByLength(nb, true));
You can't convert from Array to List, but you can easily call:
nbtemp = crv[i].DivideByLength(nb, true).ToList();
Or, since you already have to Lists defined, you could also:
nbtemp.AddRange(crv[i].DivideByLength(nb, true));
You are using an assignment and it is hard to tell what DivideByLength returns, if a single value then use:
nbtemp.Add(crv[i].DivideByLength(nb, true));
Otherwise, if it is returning an array, try changing your definition to allow the list to contain arrays:
List<double[]> nbtemp = new List<double[]>();
Note that List is not equivalent to double[]. List has many features that a simple array does not. You can see the differences by looking at the two different MSDN articles for which methods are publicly exposed.
List
Array
Also, your for loop as it stands is using an assignment. Without a change to that part of the code, you will only assign the last iteration of the for loop to the variable nbtemp (assuming you remove the error)
They are both IEnumerable implementers but they are not equivalent types. You will need to perform a cast or a method call. In the code above I would say you'd need:
nbtemp = (crv[i].DivideByLength(nb, true)).ToList();
or
nbtemp.AddRange(crv[i].DivideByLength(nb, true));

How delete an item from struct array in C#

I have a struct in C# and I define and array list of my struct based on my code that I express here. I add items in my array list, but I need to delete a few rows from my list too. Could you help me how can I delete item or items from my struct array list:
public struct SwitchList
{
public int m_Value1, m_Value2;
public int mValue1
{
get { return m_Value1; }
set {m_Value1 = value; }
}
public int mValue2
{
get { return m_Value2; }
set {m_Value2 = value; }
}
}
//Define an array list of struct
SwitchList[] mSwitch = new SwitchList[10];
mSwitch[0].mValue1=1;
mSwitch[0].mValue2=2;
mSwitch[1].mValue1=3;
mSwitch[1].mValue2=4;
mSwitch[2].mValue1=5;
mSwitch[2].mValue2=6;
Now how can I delete one of my items, for example item 1.
Thank you.
Arrays are fixed length data structures.
You will need to create a new array, sized one less than the original and copy all items to it except the one you want to delete and start using the new array instead of the original.
Why not use a List<T> instead? It is a dynamic structure that lets you add and remove items.
You will need to move elements around and resize the array (which is expensive), since there is some complexity there you going to want to hide it in class that just presents the collection without exposing the implementation details of how its stored. Fortunately Microsoft has already provided a class that does just this called List<T> which along with a few other collection types in System.Collections.Generic namespace meet most common collection needs.
as a side note, you should use auto-properties instead of the trivial property style that you ha
That's not possible, because an array is a fixed size block of elements. Because structs are values types and not reference types, you also can't just set the element zo null. One option would be to create a new smaller array and to copy your remaining values to the new array. But the better approach would be to use a List in my opinion.
If you really, really want to use arrays and move things around, here are some examples of how to do it:
{
// Remove first element from mSwitch using a for loop.
var newSwitch = new SwitchList[mSwitch.Length - 1];
for (int i = 1; i < mSwitch.Length; i++)
newSwitch[i - 1] = mSwitch[i];
mSwitch = newSwitch;
}
{
// Remove first element from mSwitch using Array.Copy.
var newSwitch = new SwitchList[mSwitch.Length - 1];
Array.Copy(mSwitch, 1, newSwitch, 0, mSwitch.Length - 1);
mSwitch = newSwitch;
}

How to Compare Values in Array

If you have a string of "1,2,3,1,5,7" you can put this in an array or hash table or whatever is deemed best.
How do you determine that all value are the same? In the above example it would fail but if you had "1,1,1" that would be true.
This can be done nicely using lambda expressions.
For an array, named arr:
var allSame = Array.TrueForAll(arr, x => x == arr[0]);
For an list (List<T>), named lst:
var allSame = lst.TrueForAll(x => x == lst[0]);
And for an iterable (IEnumerable<T>), named col:
var first = col.First();
var allSame = col.All(x => x == first);
Note that these methods don't handle empty arrays/lists/iterables however. Such support would be trivial to add however.
Iterate through each value, store the first value in a variable and compare the rest of the array to that variable. The instant one fails, you know all the values are not the same.
How about something like...
string numArray = "1,1,1,1,1";
return numArrray.Split( ',' ).Distinct().Count() <= 1;
I think using List<T>.TrueForAll would be a slick approach.
http://msdn.microsoft.com/en-us/library/kdxe4x4w.aspx
Not as efficient as a simple loop (as it always processes all items even if the result could be determined sooner), but:
if (new HashSet<string>(numbers.Split(',')).Count == 1) ...

Categories

Resources