Returning booleans in a C# method - c#

I have an array of booleans which gets filled by a loop. The method that owns the array needs to return a single boolean. So can I do this:
bool[] Booleans = new bool[4];
// do work - fill array
return (Booleans[0] && Booleans[1] && Booleans[2] && Booleans[3]);
So if I have: T,T,F,T will I get F back since there is one in the array or will it send back something else or just crash all together?

A single false will result in false being returned with boolean AND logic.
You can also rewrite as:
return Booleans.All(b => b);
For the sake of completeness, or if LINQ is not an option, you can achieve the same via a loop:
var list = new List<bool> { true, false, true };
bool result = true;
foreach (var item in list)
{
result &= item;
if (!item)
break;
}
Console.WriteLine(result);
For small samples what you have is fine, but as the number of items grow either of the above approaches will make the code a lot friendlier.

If you must process the array and return only a single boolean, then the best approach would be to just set a value to true, then loop through until the value is false, or you reach the end of the loop.
This way you won't have to process past the first false value, since that makes the entire result false.
How you loop through depends on which version of .NET you are using.

Related

Determine if array contains all zeroes

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.

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);
}

C#: How to check if all the elements in an array of boolean variables are of the same value (All true or All false)?

I have an array of boolean variables and I want to return true if all the elements in this array are of the same value, false otherwise. I know I can loop through all the elements, but I'm wondering if there are any faster ways in C#.
var allAreTheSame = myArray.All(a => a) || myArray.All(a => !a)
var result = array.Distinct().Count() == 1;
// Assuming the array is NOT empty
// Get first value
var firstValue = myArray.First();
// Check if all other values are identical
var allidentical = myArray.Skip(1).All(z => z == firstValue);
Enumerable.Range(0, array.Length-1).All(i => array[i] == array[i+1])
Edit: Fix after comments
Enumerable.Range(1, array.Length).All(i => array[i] == array[0])
var allAreTheSame = myArray.Distinct().Count() == 1
Just an alternative to David's approach, slightly shorter and possibly more efficient since I think the enumerator combination will cause the Array to be looped only once.
I would go for an extension method. I'd always love those methods:
The class containing the extension method will be:
public static class ExtensionMethods
{
public static bool AreAll<T>(this T[] source, Func<T, bool> condition)
{ return source.Where(condition).Count() == source.Count(); }
public static bool AreAllTheSame<T>(this IEnumerable<T> source)
{ return source.Distinct().Count() == 1; }
}
You see that I have 2 extension methods, one taking a Func and one taking no parameter.
The first one is called when you want to check if all the elements in the array has the same value (for example, all elements are true, or all elements are false).
The second one is called, when you don't want to check against a specific parameter, but if you just want to see if all the values are the same.
And than a little demo to demonstrate the extension method itself:
class Program
{
static void Main(string[] args)
{
bool[] array = { true, false, true, false, true };
bool[] trueArray = { true, true, true, true };
Console.WriteLine("Searching with a predicate:");
Console.WriteLine(array.AreAll(x => x).ToString());
Console.WriteLine(array.AreAll(x => !x).ToString());
Console.WriteLine(trueArray.AreAll(x => x).ToString());
Console.WriteLine(trueArray.AreAll(x => !x).ToString());
Console.WriteLine("Searching without a predicate:");
Console.WriteLine(array.AreAllTheSame().ToString());
Console.WriteLine(array.AreAllTheSame().ToString());
Console.WriteLine(trueArray.AreAllTheSame().ToString());
Console.WriteLine(trueArray.AreAllTheSame().ToString());
Console.ReadLine();
}
}
This will produce the following output:
Let's hope it helps.
Just for fun a little different solution:
!(array.Any(b => b) && array.Any(b => !b));
There are two loops here. One of them should exit on the first element in the array. The other one should exit on the first occurrence that is different from the first in the array. It will also return true for empty arrays.

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) ...

How check bitArray contains any true or any false value?

In C# and Vb.net,is any way without iterating by loop a bitarray to check contins any true or false value (Dotnet 2.0) ?
I doubt there's any way you could do it without a loop under the hood (as a BitArray can be arbitrarily long, unlike BitVector32), but if you just don't want to write it yourself:
var hasAnyTrue = input.Cast<bool>().Contains(true);
var hasAnyFalse = input.Cast<bool>().Contains(false);
If you are using the BitArray class from System.Collections you can use the following code to determine if anything is true.
C# version
var anyTrue = myArray.Cast<bool>().Any(x => x);
VB.Net Version
Dim anyTrue = myArray.Cast(Of Boolean)().Any(Function(x) x)
Indexing into the BitArray and checking the individual boolean values is an obvious solution. If you are concerned about performance, you should first and foremost consider creating your own abstraction, but if you prefer using BitArray for most of your operations, then you could do the check using CopyTo to an int[] of the right size (Count >> 5), and then perform zero or non-zero checks on these ints as appropriate.
I don't know if you can do it using a BitArray, but if you use an int, long etc. and then check to see if it is greater than 0 (for true) or less than the max value of the data type (for false) that would do it.
so something like this:
bool IsTrue (int bitArray)
{
return bitArray != 0;
}
bool isFalse (int bitArray)
{
return bitArray != int.MinValue;
}

Categories

Resources