Classify strings from an array using Custom Hash Function - GeeksforGeeks

14 May, 2021
Given an array of strings arr[] consisting of N strings, the task is to categorize the strings according to the hash value obtained by adding ASCII values % 26 of the characters in the string.
Examples:
Input: arr[][] = {“geeks”, “for”, “geeks”}Output:geeks geeksforExplanation:The hash value of string “for” is (102 + 111 + 114) % 26 = 14The hash value of string “geeks” is (103 + 101 + 101 + 107 + 115) % 26 = 7Therefore, two “geeks” are grouped together and “for” is kept in another group.
Input: arr[][] = {“adf”, “aahe”, “bce”, “bgdb”}Output: aahe bgdbbceadf Explanation: The hash value of string “adf” is (97 + 100 + 102)%26 = 13The hash value of string “aahe” is (97 + 97 + 104 + 101)%26 = 9The hash value of string “bce” is (98 + 99 + 101)%26 = 12The hash value of string “bgdb” is (98 + 103 + 100 + 98)%26 = 9Therefore,  strings “aahe” and “bgdb” have same hashed value, so they are grouped together.
Approach: The idea is to use Map Data Structure for grouping together the strings with the same hash values. Follow the steps below to solve the problem:
Initialize a Map, say mp, to map hash values with respective strings in a vector.
Traverse the given array of strings and perform the following steps:Calculate the hash value of the current string according to the given function.Push the string into the vector with the calculated hash values of the string as key in the map mp.
Calculate the hash value of the current string according to the given function.
Push the string into the vector with the calculated hash values of the string as key in the map mp.
Finally, traverse the map mp and print all the strings of respective keys.
Below is the implementation of the above approach:
C++
Java
Python3
Javascript
// C++ program for the above approach #include <bits/stdc++.h>using namespace std; // Function to find the hash// value of the string sint stringPower(string s){    // Stores hash value of string    int power = 0;    int n = s.length();     // Iterate over characters of the string    for (int i = 0; i < n; i++) {         // Calculate hash value        power = (power + (s[i])) % 26;    }     // Return the hash value    return power;} // Function to classify the strings// according to the given conditionvoid categorisation_Of_strings(    vector<string> s, int N){    // Maps strings with their strings    // respective hash values    map<int, vector<string> > mp;     // Traverse the array of strings    for (int i = 0; i < N; i++) {         // Find the hash value of the        // of the current string        int temp = stringPower(s[i]);         // Push the current string in        // value vector of temp key        mp[temp].push_back(s[i]);    }     // Traverse over the map mp    for (auto power : mp) {         // Print the result        for (auto str : power.second) {            cout << str << " ";        }        cout << endl;    }} // Driver Codeint main(){    vector<string> arr{ "adf", "aahe",                        "bce", "bgdb" };    int N = arr.size();     categorisation_Of_strings(arr, N);     return 0;}
// Java program for the above approachimport java.util.Arrays;import java.util.HashMap;import java.util.Map;import java.util.Vector; class GFG{     // Function to find the hash// value of the string sstatic int stringPower(String s){         // Stores hash value of string    int power = 0;    int n = s.length();    char C[] = s.toCharArray();     // Iterate over characters of the string    for(int i = 0; i < n; i++)    {                 // Calculate hash value        power = (power + (C[i])) % 26;    }     // Return the hash value    return power;} // Function to classify the strings// according to the given conditionstatic void categorisation_Of_strings(Vector<String> s,                                      int N){         // Maps strings with their strings    // respective hash values    Map<Integer, Vector<String> > mp = new HashMap<>();         // Traverse the array of strings    for(int i = 0; i < N; i++)    {                 // Find the hash value of the        // of the current string        int temp = stringPower(s.get(i));         // Push the current string in        // value vector of temp key        if (mp.containsKey(temp))        {            mp.get(temp).add(s.get(i));        }        else        {            mp.put(temp, new Vector<String>());            mp.get(temp).add(s.get(i));        }    }     // Traverse over the map mp    for(Map.Entry<Integer,           Vector<String>> entry : mp.entrySet())    {                 // Print the result        for(String str : entry.getValue())        {            System.out.print(str + " ");        }        System.out.println();    }} // Driver codepublic static void main(String[] args){    String[] Sarr = { "adf", "aahe", "bce", "bgdb" };    Vector<String> arr = new Vector<String>(        Arrays.asList(Sarr));    int N = arr.size();     categorisation_Of_strings(arr, N);}} // This code is contributed by abhinavjain194
# Python3 program for the above approach # Function to find the hash# value of the string sdef stringPower(s):       # Stores hash value of string    power = 0    n = len(s)     # Iterate over characters of the string    for i in range(n):               # Calculate hash value        power = (power + ord(s[i])) % 26     # Return the hash value    return power # Function to classify the strings# according to the given conditiondef categorisation_Of_strings(s, N):       # Maps strings with their strings    # respective hash values    mp = {}     # Traverse the array of strings    for i in range(N):               # Find the hash value of the        # of the current string        temp = stringPower(s[i])         # Push the current string in        # value vector of temp key        if temp in mp:            mp[temp].append(s[i])        else:            mp[temp] = []            mp[temp].append(s[i])                 # Traverse over the map mp    for i in sorted (mp) :               # Print the result        for str in mp[i]:            print(str,end = " ")        print("\n",end = "") # Driver Codeif __name__ == '__main__':    arr =  ["adf", "aahe", "bce", "bgdb"]    N = len(arr)    categorisation_Of_strings(arr, N)     # This code is contributed by ipg2016107.
<script> // Javascript program for the above approach // Function to find the hash// value of the string sfunction stringPower(s){         // Stores hash value of string    var power = 0;    var n = s.length;     // Iterate over characters of the string    for(var i = 0; i < n; i++)    {                 // Calculate hash value        power = (power + (s[i].charCodeAt(0))) % 26;    }     // Return the hash value    return power;} // Function to classify the strings// according to the given conditionfunction categorisation_Of_strings(s, N){         // Maps strings with their strings    // respective hash values    var mp = new Map();     // Traverse the array of strings    for(var i = 0; i < N; i++)    {                 // Find the hash value of the        // of the current string        var temp = stringPower(s[i]);         // Push the current string in        // value vector of temp key        if (!mp.has(temp))        {            mp.set(temp, new Array());        }        var tmp = mp.get(temp);        tmp.push(s[i]);        mp.set(temp, tmp);    }     var tmp = Array();     // Traverse over the map mp    mp.forEach((value, key) => {        tmp.push(key);    });     tmp.sort((a, b) => a - b);      // Traverse over the map mp    tmp.forEach((value) => {                 // Print the result        mp.get(value).forEach(element => {            document.write(element + " ");        });        document.write("<br>");    });} // Driver Codevar arr = [ "adf", "aahe", "bce", "bgdb" ];var N = arr.length; categorisation_Of_strings(arr, N); // This code is contributed by rutvik_56 </script>
aahe bgdb 
bce 
adf
 
Time Complexity: O(N*M), where M is the length of the longest string.Auxiliary Space: O(N*M)
ipg2016107
abhinavjain194
rutvik_56
ASCII
cpp-map
Arrays
Hash
Strings
Arrays
Hash
Strings
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Maximum and minimum of an array using minimum number of comparisons
Multidimensional Arrays in Java
Introduction to Arrays
Linear Search
Python | Using 2D arrays/lists the right way
Given an array A[] and a number x, check for pair in A[] with sum as x (aka Two Sum)
Internal Working of HashMap in Java
Hashing | Set 1 (Introduction)
Hashing | Set 3 (Open Addressing)
Count pairs with given sum