0 like 0 dislike
756 views
| 756 views

0 like 0 dislike
Sort a list of strings according to a given order of the alphabets.

For example, ["abcd","yyyy","zk"], order="yzxabcdefghijklmnopqrstuvw"

Output: ["yyyy","zk",abcd"]

Can we design a custom comparator to sort the list using collections.sort in java?
by Expert (30,360 points)
0 like 0 dislike
from typing import List
def list_sorter(inp_list: List) -> List:
order = "yzxabcdefghijklmnopqrstuvw"
result = sorted(inp_list, key = lambda word: [order.index(ch) for ch in word])
return result
by Expert (30,360 points)
0 like 0 dislike

C++ attempt :

#include <bits/stdc++.h>
using namespace std;

int32_t main() {
ios_base::sync_with_stdio(false);
cin.tie(nullptr); cout.tie(nullptr);
int n;cin>>n;
vector v(n,"");
for(string &e:v){
cin>>e;
}
string s;cin>>s; //"yzxabcdefghijklmnopqrstuvw"
vector frq(256,-1);vector back(256,-1);
for(int i=0;i<s.length();i++){
char c=s[i]; //y && i==0
frq[c]=i+97;
back[i+97]=c;
}
for(int j=0;j<v.size();j++){
string it=v[j];
for(int i=0;i<it.length();i++){
it[i]=(char)frq[it[i]];
}
v[j]=it;
}
sort(v.begin(),v.end());

``````for(int j=0;j<v.size();j++){
string it=v[j];
for(int i=0;i<it.length();i++){
it[i]=(char)back[it[i]];
}
v[j]=it;
}
for(auto it:v){
cout<<it<<endl;
}
return 0;
``````

}

by Expert (30,360 points)