Reputation: 15
I have created a multi-dimensional array that contains the values 0 - 2, and I need a way of going through this array to check if any of the values are either 1 or 2. I'm making it so that when there are no 1s or 2s left in the array, the program ends, but I'm unsure of how to check each element. I've added the array in question below, but this will be filled with values as the program runs.
Dim ownership = New Integer(7, 7) {{0, 0, 0, 0, 0, 0, 0, 0},
{0, 0, 0, 0, 0, 0, 0, 0},
{0, 0, 0, 0, 0, 0, 0, 0},
{0, 0, 0, 0, 0, 0, 0, 0},
{0, 0, 0, 0, 0, 0, 0, 0},
{0, 0, 0, 0, 0, 0, 0, 0},
{0, 0, 0, 0, 0, 0, 0, 0},
{0, 0, 0, 0, 0, 0, 0, 0}}
Is there a way of running through the array to check for the number of each value? Any help would be appreciated!
Upvotes: 1
Views: 517
Reputation: 32223
If you like LINQ
, you can use the Any() method to check whether the array contains any value > 0
:
Dim result As Boolean = ownership.OfType(Of Integer).Any(Function(v) v > 0)
If result = True
, there are values > 0
If you want a reference of all the elements that have a value > 0
, you can filter your array using a Where() condition: this filter will create a collection of elements that satisfy the condition:
Dim FilterResult = ownership.OfType(Of Integer).
Select(Function(elm, idx) New With {elm, idx}).
Where(Function(arr) arr.elm > 0).ToArray()
This query will return an array (it could be a List, using ToList()
instead of ToArray()
) of all the elements that have a value > 0
and their Index (position) inside the ownership
array.
Note:
As commented by djv, the LINQ
query flattens the array indexes.
When a conversion from 1D to 2D indexing is required (using LINQ
wouldn't matter, the flat index can be used in the queries), you can use this transformation (or something similar):
Dim Position2D As (Row As Integer, Col As Integer) =
(result1(0).idx \ (ownership.GetUpperBound(0) + 1),
result1(0).idx Mod (ownership.GetUpperBound(1) + 1))
Dim ValueAt2DIndex = ownership(Position2D.Row, Position2D.Col)
Upvotes: 1
Reputation: 11773
So this should help
Dim ownership(,) As Integer = {{0, 0, 0, 0, 0, 0, 0, 0},
{0, 0, 0, 0, 0, 0, 0, 0},
{0, 0, 0, 0, 0, 0, 0, 0},
{0, 0, 0, 0, 0, 0, 0, 0},
{0, 0, 0, 0, 0, 0, 0, 0},
{0, 0, 0, 0, 0, 0, 0, 0},
{0, 0, 0, 0, 0, 0, 0, 0},
{0, 0, 0, 0, 0, 0, 0, 0}}
Dim fndNZ As Boolean = False
Dim ctZ As Integer = 0
For x As Integer = ownership.GetLowerBound(0) To ownership.GetUpperBound(0)
For y As Integer = ownership.GetLowerBound(1) To ownership.GetUpperBound(1)
If ownership(x, y) <> 0 Then
fndNZ = True
Exit For
Else
ctZ += 1
End If
Next
If fndNZ Then Exit For
Next
If fndNZ Then
'exit program
End If
There is more than needed but it might help.
Upvotes: 0