Sort the strings based on the numbers of matchsticks required to represent them | C ++ implementation to sort the strings with the number of sticks required to represent them ; Stick [ ] stores the count of sticks required to represent the alphabets ; Number [ ] stores the count of sticks required to represent the numerals ; Function that return the count of sticks required to represent the given string str ; Loop to iterate over every character of the string ; Add the count of sticks required to represent the current character ; Function to sort the array according to the number of sticks required to represent it ; Vector to store the number of sticks required with respective strings ; Inserting number of sticks with respective strings ; Sort the vector , ; Print the sorted vector ; Driver Code
#include <bits/stdc++.h> NEW_LINE using namespace std ; int sticks [ ] = { 6 , 7 , 4 , 6 , 5 , 4 , 6 , 5 , 2 , 4 , 4 , 3 , 6 , 6 , 6 , 5 , 7 , 6 , 5 , 3 , 5 , 4 , 6 , 4 , 3 , 4 } ; int number [ ] = { 6 , 2 , 5 , 5 , 4 , 5 , 6 , 3 , 7 , 6 } ; int countSticks ( string str ) { int cnt = 0 ; for ( int i = 0 ; str [ i ] ; i ++ ) { char ch = str [ i ] ; if ( ch >= ' A ' && ch <= ' Z ' ) { cnt += sticks [ ch - ' A ' ] ; } else { cnt += number [ ch - '0' ] ; } } return cnt ; } void sortArr ( string arr [ ] , int n ) { vector < pair < int , string > > vp ; for ( int i = 0 ; i < n ; i ++ ) { vp . push_back ( make_pair ( countSticks ( arr [ i ] ) , arr [ i ] ) ) ; } sort ( vp . begin ( ) , vp . end ( ) ) ; for ( int i = 0 ; i < vp . size ( ) ; i ++ ) cout << vp [ i ] . second << " ▁ " ; } int main ( ) { string arr [ ] = { " GEEKS " , " FOR " , " GEEKSFORGEEKS " } ; int n = sizeof ( arr ) / sizeof ( arr [ 0 ] ) ; sortArr ( arr , n ) ; return 0 ; }