Generate a string from an array of alphanumeric strings based on given conditions

09 Jun, 2021
Given an array of strings arr[] where each string is of the form “name:number” and a character T as input, the task is to generate a new string based on the following conditions:  
In each string find the maximum digit in “number” which is less than or equal to the length of the string “name”.
If any such digit d is obtained, then append character at index d of the string name to the output string. Otherwise, append character T to the output string.
Examples:  
Input: arr[] = {“Robert:36787”, “Tina:68721”, “Jo:56389”}, T = ‘X’ Output: tiX Explanation: For the first string “Robert:36787”: Length of “Robert” is 6. Since 6 is present in the string “36787”, 6th character of “Robert”, i.e. t is appended to the answer. For the second string “Tina:68721”: Length of “Tina” is 4. The highest number less than equal to 4, which is present in “68721” is 2. Therefore, 2nd character of “Tina”, i.e. i is appended to the answer. For the third string “Jo:56389”: Length of “Jo” is 2. Since no number less than equal to 2 is present in “56389”, T( = ‘X’) is appended to the answer. Therefore, the final string after the above operations is “tiX”.Input: arr[] = {“Geeks:89167”, “gfg:68795”}, T = ‘X’ Output: GX Explanation: For the first string “Geeks:89167”, length of “Geeks” = 5 and the “89167” number has digit 1 which is less than 5. So, the resultant string will have the character at the 1st position of the name, which is ‘G’. For the second string “gfg:68795”, the length of “gfg” = 3, and the “68795” doesn’t have a digit less than or equals to 3. So, the resultant string will have the character T. Therefore, the final string after the above operations is “GX”.  
Approach: To solve the problem follow the steps given below:  
Traverse through the array of strings and split each string around “:“. The first part contains the name and the second part contains the number.Store the length of the name in a variable and find the maximum digit less than or equal to the length of the number.If any such digit found is found, extract the character at that index of name and append to the resultant string. Otherwise, append T to the resultant string.Print the resultant string after repeating the above operations for all the strings in the array.
Traverse through the array of strings and split each string around “:“. The first part contains the name and the second part contains the number.
Store the length of the name in a variable and find the maximum digit less than or equal to the length of the number.
If any such digit found is found, extract the character at that index of name and append to the resultant string. Otherwise, append T to the resultant string.
Print the resultant string after repeating the above operations for all the strings in the array.
Below is the implementation of the above approach:
C++
Java
Python3
C#
Javascript
// C++ program for the// above approach#include<bits/stdc++.h>using namespace std;     // Function to generate required stringstring generatePassword(vector<string>arr,                        char T){  // To store the result  string result;  for (auto s:arr)  {    // Split name and number    int index;         for(int i = 0; i < s.size(); i++)    {      if(s[i] == ':')      {        index = i;        break;      }    }         string name = s.substr(0, index);    string number = s.substr(index + 1,                             s.size() -                             index - 1);    int n = name.length();         // Stores the maximum number    // less than or equal to the    // length of name    int max = 0;     for (int i = 0; i < number.length(); i++)    {      // Check for number by parsing      // it to integer if it is greater      // than max number so far      int temp = number[i] - '0';       if (temp > max && temp <= n)        max = temp;    }     // Check if no such number is    // found then we append X    // to the result.    if (max == 0)      result.push_back(T);     // Otherwise    else       // Append max index      // of the name      result.push_back(name[max - 1]);  }   // Return the final string  return result;} // Driver Codeint main(){  vector<string>arr = {"Geeks:89167",                       "gfg:68795"};  char T = 'X';   // Function Call  cout << (generatePassword(arr, T));} // This code is contributed by Stream_Cipher
// Java program for the above approach import java.io.*; class GFG {     // Function to generate required string    public static String    generatePassword(String s[], char T)    {        // To store the result        StringBuilder result            = new StringBuilder();         for (String currentString : s) {             // Split name and number            String person[]                = currentString.split(":");            String name = person[0];            String number = person[1];             int n = name.length();             // Stores the maximum number            // less than or equal to the            // length of name            int max = 0;             for (int i = 0;                 i < number.length(); i++) {                 // Check for number by parsing                // it to integer if it is greater                // than max number so far                int temp = Integer.parseInt(                    String.valueOf(number.charAt(i)));                 if (temp > max && temp <= n)                    max = temp;            }             // Check if no such number is            // found then we append X            // to the result.            if (max == 0)                result.append(T);             // Otherwise            else                 // Append max index                // of the name                result.append(                    String.valueOf(                        name.charAt(max - 1)));        }         // Return the final string        return result.toString();    }     // Driver Code    public static void        main(String[] args)    {        String arr[] = { "Geeks:89167",                         "gfg:68795" };        char T = 'X';         // Function Call        System.out.println(            generatePassword(arr, T));    }}
# Python3 program for# the above approach # Function to generate# required stringdef generatePassword(s, T):     # To store the result    result = []         for currentString in s:         # Split name and number        person = currentString.split(":")        name = person[0]        number = person[1]        n = len(name)         # Stores the maximum number        # less than or equal to the        # length of name        max = 0         for i in range(len(number)):             # Check for number by parsing            # it to integer if it is greater            # than max number so far            temp = int(number[i])             if(temp > max and temp <= n):                max = temp         # Check if no such number is        # found then we append X        # to the result.        if max == 0:            result.append(T)         # Otherwise        else:             # Append max index            # of the name            result.append(name[max - 1])     # Return the    # final string    return result # Driver Codearr = ["Geeks:89167","gfg:68795"]T = 'X' # Function callprint(*generatePassword(arr, T),       sep = "") # This code is contributed by avanitrachhadiya2155
// C# program for the above approachusing System;using System.Text;class GFG{ // Function to generate required stringpublic static String generatePassword(String []s,                                      char T){    // To store the result    StringBuilder result = new StringBuilder();    foreach (String currentString in s)    {        // Split name and number        String []person = currentString.Split(':');        String name = person[0];        String number = person[1];         int n = name.Length;         // Stores the maximum number        // less than or equal to the        // length of name        int max = 0;         for (int i = 0; i < number.Length; i++)        {            // Check for number by parsing            // it to integer if it is greater            // than max number so far            int temp = Int32.Parse(String.Join("",                                   number[i]));            if (temp > max && temp <= n)                max = temp;        }         // Check if no such number is        // found then we append X        // to the result.        if (max == 0)            result.Append(T);         // Otherwise        else             // Append max index            // of the name            result.Append(String.Join("",                          name[max - 1]));    }     // Return the readonly string    return result.ToString();} // Driver Codepublic static void Main(String[] args){    String []arr = {"Geeks:89167",                    "gfg:68795"};    char T = 'X';     // Function Call    Console.WriteLine(generatePassword(arr, T));}} // This code is contributed by shikhasingrajput
<script>      // JavaScript program for the above approach      // Function to generate required string      function generatePassword(s, T) {        // To store the result        var result = [];         for (const currentString of s) {          // Split name and number          var person = currentString.split(":");          var name = person[0];          var number = person[1];           var n = name.length;           // Stores the maximum number          // less than or equal to the          // length of name          var max = 0;           for (var i = 0; i < number.length; i++) {            // Check for number by parsing            // it to integer if it is greater            // than max number so far            var temp = parseInt(number[i]);            if (temp > max && temp <= n) max = temp;          }           // Check if no such number is          // found then we append X          // to the result.          if (max === 0) result.push(T);          // Otherwise          // Append max index          // of the name          else result.push(name[max - 1]);        }         // Return the readonly string        return result.join("");      }       // Driver Code      var arr = ["Geeks:89167", "gfg:68795"];      var T = "X";       // Function Call      document.write(generatePassword(arr, T) + "<br>");             // This code is contributed by rdtank.    </script>
GX
 
Time Complexity: O(N) Auxiliary Space: O(1) 
shikhasingrajput
avanitrachhadiya2155
Stream_Cipher
rdtank
strings
Arrays
Searching
Strings
Arrays
Searching
Strings
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.