Physical Address

304 North Cardinal St.
Dorchester Center, MA 02124

Chef and Codes CodeChef Solution

Problem -Chef and Codes CodeChef Solution

This website is dedicated for CodeChef solution where we will publish right solution of all your favourite CodeChef problems along with detailed explanatory of different competitive programming concepts and languages.

Chef and Codes CodeChef Solution in C++14

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

int main()
{
    int t;
    cin >> t;
    while (t--)
    {
        string f, c;
        cin >> f;
        cin.ignore();
        getline(cin, c);
        int a[26] = {0};
        for (int i = 0; i < c.size(); i++)
        {
            if (c[i] >= 'a' && c[i] <= 'z')
                a[c[i] - 'a']++;
            else if (c[i] >= 'A' && c[i] <= 'Z')
                a[c[i] - 'A']++;
        }
        vector<pair<int, char>> v;
        for (int i = 0; i < 26; i++)
            v.push_back({a[i], ('a' + i)});
        sort(v.begin(), v.end());
        unordered_map<char, char> m;
        for (int i = 0; i < 26; i++)
            if (v[i].first != 0)
                m[v[i].second] = f[i];
        for (int i = 0; i < c.size(); i++)
        {
            if (c[i] >= 'a' && c[i] <= 'z')
                cout << m[c[i]];
            else if (c[i] >= 'A' && c[i] <= 'Z')
                cout << char('A' + (m['a' + (c[i] - 'A')] - 'a'));
            else
                cout << c[i];
        }
        cout << "\n";
    }
}

Chef and Codes CodeChef Solution in PYTH 3

# cook your dish here
from collections import Counter
t = int(input())
for _ in range(t):
    freq = str(input())[::-1]
    cryp = str(input())
    fcount = Counter(cryp.lower())
    #print(cryp)
    csort = []
    enc = {}
    for f in fcount:
        if f.isalpha(): csort.append([fcount[f],f])
        else: enc[f] = f
    csort.sort(reverse=True)
    #print(csort)
    for c in range(len(csort)):
        enc[csort[c][1]]=freq[c]
    fin = ''
    for c in cryp:
        if c.islower(): fin+=enc[c]
        elif c.isupper(): fin+=enc[c.lower()].upper()
        else: fin+=enc[c]
    print(fin)

Chef and Codes CodeChef Solution in C

#include<stdio.h>
#include<stdlib.h>
#include<string.h>
#define lli long long int
#define li long int
#define inf 10000

typedef struct 
{
    lli letter_id; //0 for a, 25 for z
    lli freq;
}LETTER;

int max(int a, int b)
{
    int m = a;
    if(b>a)
        m = b;
    return m;
}

int min(int a, int b)
{
    int m = a;
    if(b<a)
        m = b;
    return m;
}

// Merges two subarrays of arr[].
// First subarray is arr[l..m]
// Second subarray is arr[m+1..r]
void merge(LETTER arr[], lli l, lli m, lli r)
{
    lli i, j, k;
    lli n1 = m - l + 1;
    lli n2 = r - m;
 
    /* create temp arrays */
    LETTER L[n1], R[n2];
 
    /* Copy data to temp arrays L[] and R[] */
    for (i = 0; i < n1; i++)
        L[i] = arr[l + i];
    for (j = 0; j < n2; j++)
        R[j] = arr[m + 1 + j];
 
    /* Merge the temp arrays back into arr[l..r]*/
    i = 0; // Initial index of first subarray
    j = 0; // Initial index of second subarray
    k = l; // Initial index of merged subarray
    while (i < n1 && j < n2) {
        if (L[i].freq < R[j].freq) {
            arr[k] = L[i];
            i++;
        }
        else if(L[i].freq > R[j].freq) {
            arr[k] = R[j];
            j++;
        }
        else
        {
            if (L[i].letter_id <= R[j].letter_id) {
            arr[k] = L[i];
            i++;
            }
            else if(L[i].letter_id > R[j].letter_id) {
                arr[k] = R[j];
                j++;
            }
        }
        k++;
    }
 
    /* Copy the remaining elements of L[], if there
    are any */
    while (i < n1) {
        arr[k] = L[i];
        i++;
        k++;
    }
 
    /* Copy the remaining elements of R[], if there
    are any */
    while (j < n2) {
        arr[k] = R[j];
        j++;
        k++;
    }
}
 
/* l is for left index and r is right index of the
sub-array of arr to be sorted */
void mergeSort(LETTER arr[], lli l, lli r)
{
    if (l < r) {
        // Same as (l+r)/2, but avoids overflow for
        // large l and h
        lli m = l + (r - l) / 2;
 
        // Sort first and second halves
        mergeSort(arr, l, m);
        mergeSort(arr, m + 1, r);
 
        merge(arr, l, m, r);
    }
}


char Upc2Lowc(char c)
{
    char u = c;
    if(c>='A' && c<='Z')
        u = c - 'A' + 'a';
    return u;
}

int Char2Dig(char c)
{
    int d;
    d = (int)(c - 'a');
    return d;
}

int isLetter(char c)
{
    int flag = 0;
    if((c>='a' && c<='z') || (c>='A' && c<='Z'))
    {
        flag = 1;
    }
    return flag;
}

void program()
{
    char FreqSeq[27];
    char EncrypText[150000], FinalText[150000];
    fflush(stdin);
    scanf("%s", FreqSeq);
    fflush(stdin);
    scanf(" %[^\n]s", EncrypText);
    // printf("%s %s\n", FreqSeq, EncrypText);
    LETTER LetArr[26];
    int i;
    for ( i = 0; i < 26; i++)
    {
        LetArr[i].freq = 0;
        LetArr[i].letter_id = i;
    }
    i = 0;
    while(EncrypText[i] != '\0')
    {
        if(isLetter(EncrypText[i]) == 1)
        {
            char let = Upc2Lowc(EncrypText[i]);
            int ind = Char2Dig(let);
            // printf("%d\n", ind);
            (LetArr[ind].freq)++;
        }
        i++;
    }
    /*for ( i = 0; i < 26; i++)
    {
        printf("%lld %lld   ", LetArr[i].letter_id, LetArr[i].freq);
    }*/
    mergeSort(LetArr, 0, 25);
    /*for ( i = 0; i < 26; i++)
    {
        printf("%lld %lld   ", LetArr[i].letter_id, LetArr[i].freq);
    }*/
    char HashTable[26];
    for ( i = 25; i >= 0; i--)
    {
        HashTable[LetArr[i].letter_id] = FreqSeq[i];
    }
    /*for ( i = 0; i < 26; i++)
    {
        printf("%c ", HashTable[i]);
    }*/
    i = 0;
    while(EncrypText[i] != '\0')
    {
        if(EncrypText[i]>='a' && EncrypText[i]<='z')
        {
            FinalText[i] = HashTable[Char2Dig(EncrypText[i])];
        }
        else if(EncrypText[i]>='A' && EncrypText[i]<='Z')
        {
            FinalText[i] = HashTable[Char2Dig(Upc2Lowc(EncrypText[i]))];
            FinalText[i] += 'A' - 'a';
        }
        else
        {
            FinalText[i] = EncrypText[i];
        }
        i++;
    }
    FinalText[i] = '\0';
    printf("%s\n", FinalText);
}

int main(void) 
{
    long long int T;
    scanf("%lld", &T);
    //printf("%lld\n", T);
    // T = 1;
    for (long long int i = 0; i < T; i++)
    {
        program();
    }
	return 0;
}

Chef and Codes CodeChef Solution in JAVA

/* package codechef; // don't place package name! */

import java.util.*;
import java.lang.*;
import java.io.*;

/* Name of the class has to be "Main" only if the class is public. */
class Codechef
{
    public static class Pair{
        int freq;
        char c ;
        Pair(int freq, char c){
            this.freq = freq;
            this.c =c;
        }
    }
	public static void main (String[] args) throws java.lang.Exception
	{
		// your code goes here
// 		Scanner sc = new Scanner(System.in);
		InputStreamReader input = new InputStreamReader(System.in);
BufferedReader reader = new BufferedReader(input);
		int T =Integer.parseInt(reader.readLine());
		while(T-->0){
		    char[] s = reader.readLine().toCharArray();
		  //  String enc = sc.nextLine();
		    
		    
		    int[] map = new int[26];
		    char[] res =  reader.readLine().toCharArray();
		  //  System.out.println(s.toString());
		    for (char c : res) {
		        if (c-'a' >= 0 && c-'a'<26) {
		            map[c-'a']++;
		        } else if (c-'A'>=0 && c-'A'<26) map[c-'A']++;
		    }
		   ArrayList<Pair> as = new ArrayList<>();
		   for(int i=0;i<26;i++){
		       if(map[i]!=0){
		           as.add(new Pair(map[i],(char)(i+'a')));
		       }
		   }
		   
		    Collections.sort(as, (a, b) -> {
		       if (a.freq==b.freq) {
		           return Character.compare(a.c, b.c);
		       } else {
		           return Integer.compare(a.freq,b.freq);
		       } 
		    });
		  // Collections.sort()
		  Map<Character,Character> decode = new HashMap<>();
		  int idx =26-as.size();
		  for(Pair p : as){
		      decode.put(p.c,s[idx]);
		      idx++;
		  }
		  
		  String result ="";
		  for(char x : res){
		      if(x-'a'>=0&& x-'a'<26){
		          x = decode.getOrDefault(x,x);
		      }else if(x-'A'>=0&&x-'A'<26){
		          x =  Character.toUpperCase(decode.getOrDefault((char)(x-'A' + 'a'),x));
		      }
		      result+=x;
		      
		  }
		  
		  
		  System.out.println(result);
		}
	}
}

Chef and Codes CodeChef Solution in PYPY 3

from collections import Counter


for _ in range(int(input())):
    f=input()
    a=input()
    s=[]
    for i in range(len(a)):
        if a[i].isalpha():
            s.append(a[i].lower())
    s.sort(reverse=True)
    c=Counter(s)
    replacer={}
    for t,i in enumerate(c.most_common()):
        replacer[i[0]]=f[-t-1]
    for i in range(len(a)):
        if a[i].isalpha():
            if a[i].isupper():
                print(replacer[a[i].lower()].upper(),end="")
            else:
                print(replacer[a[i]],end="")
        else:
            print(a[i],end="")
    print()

Chef and Codes CodeChef Solution in PYTH

from string import *

T = int(raw_input())

for i in range(0,T):
    eng = raw_input()
    word = raw_input()

    count = [0] * 26
    for let in word:
        if let in ascii_letters :
            idx = ord(let.lower()) - ord('a')
            count[idx] = count[idx] + 1

    indices = [i[0] for i in sorted(enumerate(count), key=lambda x:x[1])]

    outp = ''
    for let in word:
        if let in ascii_letters:
            idx = indices.index(ord(let.lower())-ord('a'))
            if let in ascii_uppercase:
                outp = outp + eng[idx].upper()
            else:
                outp = outp + eng[idx]
        else:
            outp = outp + let

    print outp

Chef and Codes CodeChef Solution in C#

using System;
using System.Linq;
using System.Collections.Generic;
using System.Text.RegularExpressions;
using System.Text;
using System.Numerics;

public class Test
{
	public static void Main()
	{
	    var WS = new StringBuilder();
	    int A = GetInt();
	    while(A-- != 0){

            var counts = new Dictionary<char, int>(26);
            var trans = new Dictionary<char, char>(26);
                for (var c = 'a'; c <= 'z'; c++)
                    counts[c] = 0;

                var frequencyMap = Console.ReadLine();
                var message = Console.ReadLine().ToCharArray();

                foreach (var c in message)
                {
                    var d = char.ToLower(c);
                    if (d >= 'a' && d <= 'z')
                        counts[d] += 1;
                }

                var freq = counts.OrderBy(kvp => kvp.Value)
                    .ThenBy(kvp => kvp.Key)
                    .Select(kvp => kvp.Key)
                    .ToList();

                for (var j = 0; j < 26; j++)
                    trans[freq[j]] = frequencyMap[j];

                for (var j = 0; j < message.Length; j++)
                {
                    if (message[j] >= 'a' && message[j] <= 'z')
                        message[j] = trans[message[j]];
                    if (message[j] >= 'A' && message[j] <= 'Z')
                        message[j] = char.ToUpper(trans[char.ToLower(message[j])]);
                }

                Console.WriteLine(message);
	    }
	    
		// your code goes here
	}
	
		public static void Writex(string s) => (Console.WriteLine(s));
	public static int GetInt() => int.Parse(Console.ReadLine());
    public static long GetLong() => long.Parse(Console.ReadLine());
    public static string GetString() => (Console.ReadLine());

    public static string[] GetStringArray() => Console.ReadLine().Trim().Split(' ');
    public static int[] GetIntArray() => Console.ReadLine().Trim().Split(' ').Select(int.Parse).ToArray();
        public static long[] GetLongArray() =>  Console.ReadLine().Trim().Split(' ').Select(long.Parse).ToArray();
}

Chef and Codes CodeChef Solution in GO

package main

import (
	"bufio"
	"os"
	"sort"
	"strconv"
	"strings"
)

func main() {
	w := bufio.NewWriter(os.Stdout)
	s := bufio.NewReader(os.Stdin)
	l, _ := s.ReadString('\n')
	T, _ := strconv.Atoi(strings.Fields(l)[0])

	var counts [26]int
	var d [26]uint8
	for ; T > 0; T-- {
		for i := range counts {
			counts[i] = 0
		}
		line, _ := s.ReadBytes('\n')
		message, _ := s.ReadBytes('\n')
		for _, chr := range message {
			if 'a' <= chr && chr <= 'z' {
				counts[chr - 'a']++
			} else if 'A' <= chr && chr <= 'Z' {
				counts[chr - 'A']++
			}
		}
		ordered := make([]int, 26)
		for i, count := range counts {
			ordered[i] = count
		}
		sort.Ints(ordered)
		for j := 25; j >= 0 && ordered[j] > 0; j-- {
			for k := 25; k >= 0; k-- {
				if counts[k] == ordered[j] {
					counts[k] = 0
					d[k] = line[j]
					break
				}
			}
		}
		for _, chr := range message {
			if 'a' <= chr && chr <= 'z' {
				w.WriteByte(d[chr-'a'])
			} else if 'A' <= chr && chr <= 'Z' {
				w.WriteByte(d[chr-'A'] + 'A' - 'a')
			} else {
				w.WriteByte(chr)
			}
		}
	}
	w.Flush()
}
Chef and Codes CodeChef Solution Review:

In our experience, we suggest you solve this Chef and Codes CodeChef Solution and gain some new skills from Professionals completely free and we assure you will be worth it.

If you are stuck anywhere between any coding problem, just visit Queslers to get the Chef and Codes CodeChef Solution.

Find on CodeChef

Conclusion:

I hope this Chef and Codes CodeChef Solution would be useful for you to learn something new from this problem. If it helped you then don’t forget to bookmark our site for more Coding Solutions.

This Problem is intended for audiences of all experiences who are interested in learning about Programming Language in a business context; there are no prerequisites.

Keep Learning!

More Coding Solutions >>

Cognitive Class Answer

CodeChef Solution

Microsoft Learn

Leave a Reply

Your email address will not be published. Required fields are marked *