Encuentre y devuelva el índice de una string dada en una array multidimensional

Dada una array multidimensional stringArr de strings y una keyString que se va a encontrar, la tarea es devolver las coordenadas/índices de esa string clave en la array.

Ejemplo:

Entrada: stringArr[][] = { { “a”, “h”, “b”}, {“c”, “d”, “e”}, {“g”, “t”, “r”} }, keyString = “e”
Salida = {1, 2}
Explicación: siguiendo la indexación basada en 0, keyString está presente en (1, 2) en la array multidimensional.

Enfoque: Siga los pasos para encontrar las coordenadas/índices de una string en una array multidimensional:

  • En primer lugar, itere sobre todos los elementos de la array comprobando cada elemento en la primera fila, luego en la segunda fila y así sucesivamente. 
  • Luego, si la string de claves se encuentra en la array, simplemente devuelva los índices 
  • de lo contrario, simplemente devuelva -1 como índices.

A continuación se muestra la implementación del enfoque anterior:

C++

// CPP Program to return indices of a given
// string from the multidimensional array
#include <bits/stdc++.h>
using namespace std;
 
// Method to return an array of indices
// of keyString
vector<int> findIndex(vector<vector<string> > stringArr,
                      string keyString)
{
 
    // Initialising result array to -1
    // in case keyString is not found
    vector<int> result{ -1, -1 };
 
    // Iteration over all the elements
    // of the 2-D array
 
    // Rows
    for (int i = 0; i < stringArr.size(); i++) {
 
        // Columns
        for (int j = 0; j < stringArr[i].size(); j++) {
 
            // If keyString is found
            if (stringArr[i][j] == keyString) {
                result[0] = i;
                result[1] = j;
                return result;
            }
        }
    }
 
    // If keyString is not found
    // then -1 is returned
    return result;
}
 
// Driver Code
int main()
{
 
    // Given string array
    vector<vector<string> > stringArr{ { "a", "h", "b" },
                                       { "c", "d", "e" },
                                       { "g", "t", "r" } };
 
    // Given key String to be found
    string keyString = "e";
 
    // Calling the method which
    // returns an array of indices
    vector<int> result = findIndex(stringArr, keyString);
 
    // Printing the indices returned
    cout << "The indices are: ";
    for (int i = 0; i < result.size(); i++) {
        cout << result[i] << " ";
    }
}

Java

// Java Program to return indices of a given string
// from the multidimensional string array
 
public class Main {
    // method to return an array of indices of keyString
    public static int[] findIndex(String stringArr[][],
                                  String keyString)
    {
        // initialising result array to -1 in case keyString
        // is not found
        int result[] = { -1, -1 };
        // iteration over all the elements of the 2-D array
        // rows
        for (int i = 0; i < stringArr.length; i++) {
            // columns
            for (int j = 0; j < stringArr[i].length; j++) {
                // if keyString is found
                if (stringArr[i][j].equals(keyString)) {
                    result[0] = i;
                    result[1] = j;
                    return result;
                }
            }
        }
        // if keyString is not found then -1 is returned
        return result;
    }
 
    // Driver Code
    public static void main(String args[])
    {
        // given string array
        String[][] stringArr = { { "a", "h", "b" },
                                 { "c", "d", "e" },
                                 { "g", "t", "r" } };
        // given key String to be found
        String keyString = "e";
        // calling the method which returns an array of
        // indices
        int[] result = findIndex(stringArr, keyString);
        // printing the indices returned
        System.out.print("The indices are:- ");
        for (int i = 0; i < result.length; i++) {
            System.out.print(result[i] + " ");
        }
    }
}

Python3

#  Python Program to return indices of a given
#  string from the multidimensional array
 
#  Method to return an array of indices
#  of keyString
 
def findIndex(stringArr, keyString):
 
    #  Initialising result array to -1
    #  in case keyString is not found
    result = []
 
    #  Iteration over all the elements
    #  of the 2-D array
 
    #  Rows
    for i in range(len(stringArr)):
 
        #  Columns
        for j in range(len(stringArr[i])):
            #  If keyString is found
            if stringArr[i][j] == keyString:
                result.append(i)
                result.append(j)
                return result
    result.append(-1)
    result.append(-1)
    #  If keyString is not found
    #  then -1 is returned
    return result
 
 
   
# Driver Code
# Given string array
stringArr = [["a", "h", "b"],
             ["c", "d", "e"],
             ["g", "t", "r"]]
 
# Given key String to be found
keyString = "e"
 
# Calling the method which
# returns an array of indices
result = findIndex(stringArr, keyString)
 
# Printing the indices returned
print("The indices are:", result[0], result[1])
 
# This code has been contributed by Sachin Sahara (sachin801)

C#

// C# Program to return indices of a given string
// from the multidimensional string array
 
using System;
 
public class GFG
{
   
    // method to return an array of indices of keyString
    public static int[] findIndex(string [,] stringArr,
                                  string keyString)
    {
       
        // initialising result array to -1 in case keyString
        // is not found
        int []result = { -1, -1 };
       
        // iteration over all the elements of the 2-D array
        // rows
        for (int i = 0; i < stringArr.Length; i++)
        {
           
            // columns
            for (int j = 0; j < stringArr.GetLength(0); j++)
            {
               
                // if keyString is found
                if (stringArr[i,j].Equals(keyString)) {
                    result[0] = i;
                    result[1] = j;
                    return result;
                }
            }
        }
       
        // if keyString is not found then -1 is returned
        return result;
    }
 
    // Driver Code
    public static void Main(string []args)
    {
       
        // given string array
        string[,] stringArr = { { "a", "h", "b" },
                                 { "c", "d", "e" },
                                 { "g", "t", "r" } };
       
        // given key String to be found
        string keyString = "e";
       
        // calling the method which returns an array of
        // indices
        int[] result = findIndex(stringArr, keyString);
       
        // printing the indices returned
        Console.Write("The indices are:- ");
        for (int i = 0; i < result.Length; i++) {
            Console.Write(result[i] + " ");
        }
    }
}
 
// This code is contributed by AnkThon

Javascript

<script>
 
// JavaScript Program to return indices of a given
// string from the multidimensional array
 
 
// Method to return an array of indices
// of keyString
function findIndex(stringArr,keyString)
{
 
    // Initialising result array to -1
    // in case keyString is not found
    let result = [ -1, -1 ];
 
    // Iteration over all the elements
    // of the 2-D array
 
    // Rows
    for (let i = 0; i < stringArr.length; i++) {
 
        // Columns
        for (let j = 0; j < stringArr[i].length; j++) {
 
            // If keyString is found
            if (stringArr[i][j] == keyString) {
                result[0] = i;
                result[1] = j;
                return result;
            }
        }
    }
 
    // If keyString is not found
    // then -1 is returned
    return result;
}
 
// Driver Code
 
// Given string array
let stringArr = [[ "a", "h", "b" ],
                [ "c", "d", "e" ],
                [ "g", "t", "r" ]];
 
// Given key String to be found
let keyString = "e";
 
// Calling the method which
// returns an array of indices
let result = findIndex(stringArr, keyString);
 
// Printing the indices returned
document.write("The indices are: ");
for (let i = 0; i < result.length; i++) {
    document.write(result[i]," ");
}
 
// This code is contributed by shinjanpatra
 
</script>
Producción

The indices are: 1 2 

Complejidad del tiempo: O(N 2 )

Espacio Auxiliar: O(1)

Publicación traducida automáticamente

Artículo escrito por sachin801 y traducido por Barcelona Geeks. The original can be accessed here. Licence: CCBY-SA

Deja una respuesta

Tu dirección de correo electrónico no será publicada. Los campos obligatorios están marcados con *