Academic Integrity: tutoring, explanations, and feedback — we don’t complete graded work or submit on a student’s behalf.

Implement a comparator NumStrComp on strings that does the following: for each d

ID: 3734159 • Letter: I

Question

Implement a comparator NumStrComp on strings that does the following: for each digit and letter, it assigns a number ("0" = 0, "1" = 1, "2" = 2, ..., "9" = 9, "A" = 10, "B" = 11, "C" = 12, ..., "Z" = 35; same numbers for lowercase letters as for uppercase letters); all other characters are 0. It then simply adds up all the numbers assigned to all digits and letters in the string, and sorts by the sum. Ties are broken lexicographically, i.e., with the "standard" string comparison for C++. Add the functor NumStrComp to functor.cpp and functor.h.

Explanation / Answer

Code

#include<bits/stdc++.h>

#include<map>

#include<string.h>

#define ASCII_SIZE 256

using namespace std;

list<string>::const_iterator i;

string::iterator it;

list<int>::iterator j;

//calculate the sum of characters in strings and return total

int getTotal(string str, map<char, int> val)

{ int sum = 0;

for ( it = str.begin() ; it < str.end(); it++ )

{

sum = sum + val[*it];

  

}

return sum;

}

//compare the strings in the list and display the sorted one

void NumStrComp(list<string>& prms, map<char, int> val){

list<int> sums; //list to store sum of a string

map<int, string> result; //map to store strings corresponding to their total

for(i = prms.begin(); i != prms.end(); ++i)

{

int total = getTotal(*i, val);

sums.push_back(total); //push the sums in the list

result[total] = *i;

}

sums.sort(); //sort the list sums

  

for(j = sums.begin(); j != sums.end(); ++j)

cout<<result[*j]<<endl; //print the string corresponding to their sorted sums

}

// Driver program to test the above function

int main()

{ map<char, int> value;

list<string> listOfStrings;

//push any number of string in the list

listOfStrings.push_back("hello");

listOfStrings.push_back("hi");

//initialize value of integers

for( int i=0; i<9; i++)

{

value['i'] = i;

}

//initialize the values of characters

for(int i=0; i<26 ; ++i)

{

value['a' + i] = i+10;

value['A' + i] = i+10;

}

//call the comparator

NumStrComp(listOfStrings, value);

}

Output

Hire Me For All Your Tutoring Needs
Integrity-first tutoring: clear explanations, guidance, and feedback.
Drop an Email at
drjack9650@gmail.com
Chat Now And Get Quote