Sort the strings based on the numbers of matchsticks required to represent them | Java 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 ; Utility Pair implementation ; 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 ; ArrayList to store the number of sticks required with respective strings ; Inserting number of sticks with respective strings ; Sort the list , ; Print the sorted vector ; Driver Code
import java . io . * ; import java . util . * ; class GFG { static 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 } ; static int number [ ] = { 6 , 2 , 5 , 5 , 4 , 5 , 6 , 3 , 7 , 6 } ; static class Pair implements Comparable < Pair > { int num_sticks ; String str ; Pair ( int n , String s ) { num_sticks = n ; str = s ; } public int compareTo ( Pair p ) { return this . num_sticks - p . num_sticks ; } } static int countSticks ( String str ) { int cnt = 0 ; int n = str . length ( ) ; for ( int i = 0 ; i < n ; i ++ ) { char ch = str . charAt ( i ) ; if ( ch >= ' A ' && ch <= ' Z ' ) { cnt += sticks [ ch - ' A ' ] ; } else { cnt += number [ ch - '0' ] ; } } return cnt ; } static void sortArr ( String arr [ ] , int n ) { ArrayList < Pair > list = new ArrayList < > ( ) ; for ( int i = 0 ; i < n ; i ++ ) { list . add ( new Pair ( countSticks ( arr [ i ] ) , arr [ i ] ) ) ; } Collections . sort ( list ) ; for ( int i = 0 ; i < list . size ( ) ; i ++ ) System . out . print ( list . get ( i ) . str + " ▁ " ) ; } public static void main ( String [ ] args ) { String arr [ ] = { " GEEKS " , " FOR " , " GEEKSFORGEEKS " } ; int n = arr . length ; sortArr ( arr , n ) ; } }