Sort numbers based on count of letters required to represent them in words | C ++ program to sort the strings based on the numbers of letters required to represent them ; letters [ i ] stores the count of letters required to represent the digit i ; Function to return the sum of letters required to represent N ; Function to sort the array according to the sum of letters to represent n ; Vector to store the digit sum with respective elements ; Inserting digit sum with elements in the vector pair ; Making the vector pair ; Sort the vector , this will sort the pair according to the sum of letters to represent n ; Print the sorted vector content ; Driver code
#include <bits/stdc++.h> NEW_LINE using namespace std ; const int letters [ ] = { 4 , 3 , 3 , 3 , 4 , 4 , 3 , 5 , 5 , 4 } ; int sumOfLetters ( int n ) { int sum = 0 ; while ( n > 0 ) { sum += letters [ n % 10 ] ; n = n / 10 ; } return sum ; } void sortArr ( int arr [ ] , int n ) { vector < pair < int , int > > vp ; for ( int i = 0 ; i < n ; i ++ ) { vp . push_back ( make_pair ( sumOfLetters ( arr [ i ] ) , arr [ i ] ) ) ; } sort ( vp . begin ( ) , vp . end ( ) ) ; for ( int i = 0 ; i < vp . size ( ) ; i ++ ) cout << vp [ i ] . second << " ▁ " ; } int main ( ) { int arr [ ] = { 12 , 10 , 31 , 18 } ; int n = sizeof ( arr ) / sizeof ( arr [ 0 ] ) ; sortArr ( arr , n ) ; return 0 ; }