mrjimoy_05
mrjimoy_05

Reputation: 3568

Get a value from array based on the value of others arrays (VB.Net)

Supposed that I have two arrays:

Dim RoomName() As String = {(RoomA), (RoomB), (RoomC), (RoomD), (RoomE)}
Dim RoomType() As Integer = {1, 2, 2, 2, 1} 

I want to get a value from the "RoomName" array based on a criteria of "RoomType" array. For example, I want to get a "RoomName" with "RoomType = 2", so the algorithm should randomize the index of the array that the "RoomType" is "2", and get a single value range from index "1-3" only.

Is there any possible ways to solve the problem using array, or is there any better ways to do this? Thank you very much for your time :)

Upvotes: 0

Views: 201

Answers (1)

kaj
kaj

Reputation: 5251

Note: Code examples below using C# but hopefully you can read the intent for vb.net

Well, a simpler way would be to have a structure/class that contained both name and type properties e.g.:

  public class Room
  {
      public string Name { get; set; }
      public int Type { get; set; }

      public Room(string name, int type)
      {
          Name = name;
          Type = type;
      }
  }

Then given a set of rooms you can find those of a given type using a simple linq expression:

var match = rooms.Where(r => r.Type == 2).Select(r => r.Name).ToList();

Then you can find a random entry from within the set of matching room names (see below)

However assuming you want to stick with the parallel arrays, one way is to find the matching index values from the type array, then find the matching names and then find one of the matching values using a random function.

var matchingTypeIndexes = new List<int>();
int matchingTypeIndex = -1;
do
{
  matchingTypeIndex = Array.IndexOf(roomType, 2, matchingTypeIndex + 1);
  if (matchingTypeIndex > -1)
  {
    matchingTypeIndexes.Add(matchingTypeIndex);
  }
} while (matchingTypeIndex > -1);

List<string> matchingRoomNames = matchingTypeIndexes.Select(typeIndex => roomName[typeIndex]).ToList();

Then to find a random entry of those that match (from one of the lists generated above):

var posn = new Random().Next(matchingRoomNames.Count);
Console.WriteLine(matchingRoomNames[posn]);

Upvotes: 1

Related Questions